babylon.max.js 2.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * 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".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. 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);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * 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".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. 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);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = function (otherSize) {
  2218. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2726. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. 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]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. 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]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. 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);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. 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);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. 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);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. 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);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. 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);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * 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".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * 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".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. 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);
  3508. };
  3509. /**
  3510. * 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".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * 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".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. 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);
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * 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.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. 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);
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * 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.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. 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);
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * 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.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * 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.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. 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);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * 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.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. 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);
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * 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.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. 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);
  3661. };
  3662. /**
  3663. * 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.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. 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);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. Matrix._tempQuaternion = new Quaternion();
  3833. Matrix._xAxis = Vector3.Zero();
  3834. Matrix._yAxis = Vector3.Zero();
  3835. Matrix._zAxis = Vector3.Zero();
  3836. Matrix._updateFlagSeed = 0;
  3837. return Matrix;
  3838. }());
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine.getRenderWidth) {
  4001. var engine = renderWidthOrEngine;
  4002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4003. }
  4004. var renderWidth = renderWidthOrEngine;
  4005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4006. };
  4007. /**
  4008. * Returns a new Viewport copied from the current one.
  4009. */
  4010. Viewport.prototype.clone = function () {
  4011. return new Viewport(this.x, this.y, this.width, this.height);
  4012. };
  4013. return Viewport;
  4014. }());
  4015. BABYLON.Viewport = Viewport;
  4016. var Frustum = (function () {
  4017. function Frustum() {
  4018. }
  4019. /**
  4020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4021. */
  4022. Frustum.GetPlanes = function (transform) {
  4023. var frustumPlanes = [];
  4024. for (var index = 0; index < 6; index++) {
  4025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4026. }
  4027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4028. return frustumPlanes;
  4029. };
  4030. /**
  4031. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4032. */
  4033. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4034. // Near
  4035. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4036. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4037. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4038. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4039. frustumPlanes[0].normalize();
  4040. // Far
  4041. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4042. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4043. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4044. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4045. frustumPlanes[1].normalize();
  4046. // Left
  4047. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4048. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4049. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4050. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4051. frustumPlanes[2].normalize();
  4052. // Right
  4053. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4054. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4055. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4056. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4057. frustumPlanes[3].normalize();
  4058. // Top
  4059. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4060. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4061. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4062. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4063. frustumPlanes[4].normalize();
  4064. // Bottom
  4065. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4066. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4067. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4068. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4069. frustumPlanes[5].normalize();
  4070. };
  4071. return Frustum;
  4072. }());
  4073. BABYLON.Frustum = Frustum;
  4074. var Space;
  4075. (function (Space) {
  4076. Space[Space["LOCAL"] = 0] = "LOCAL";
  4077. Space[Space["WORLD"] = 1] = "WORLD";
  4078. Space[Space["BONE"] = 2] = "BONE";
  4079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4080. var Axis = (function () {
  4081. function Axis() {
  4082. }
  4083. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4086. return Axis;
  4087. }());
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. 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);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * 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.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. 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)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. 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;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. 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)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4644. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4645. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4646. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4647. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4648. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4649. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero(),
  4651. Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4653. return Tmp;
  4654. }());
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. MathTmp.Vector3 = [Vector3.Zero()];
  4661. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4662. MathTmp.Quaternion = [Quaternion.Zero()];
  4663. return MathTmp;
  4664. }());
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:// Mesh reference
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:// Color Curves
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:// Value
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:// Texture
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:// Color3
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:// FresnelParameters
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:// Vector2
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:// Vector3
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:// Mesh reference
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:// Color Curves
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:// Color 4
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:// Image Processing
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:// Value
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:// Texture
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:// Color3
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:// FresnelParameters
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:// Vector2
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:// Vector3
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:// Mesh reference
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:// Color Curves
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:// Color 4
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:// Image Processing
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * 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.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * 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).
  5181. * 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.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @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.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask || obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. if (this.data) {
  5337. this.data.length = 0;
  5338. this.data = null;
  5339. }
  5340. };
  5341. SmartArray.prototype.concat = function (array) {
  5342. if (array.length === 0) {
  5343. return;
  5344. }
  5345. if (this.length + array.length > this.data.length) {
  5346. this.data.length = (this.length + array.length) * 2;
  5347. }
  5348. for (var index = 0; index < array.length; index++) {
  5349. this.data[this.length++] = (array.data || array)[index];
  5350. }
  5351. };
  5352. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5353. if (array.length === 0) {
  5354. return;
  5355. }
  5356. if (this.length + array.length > this.data.length) {
  5357. this.data.length = (this.length + array.length) * 2;
  5358. }
  5359. for (var index = 0; index < array.length; index++) {
  5360. var item = (array.data || array)[index];
  5361. this.pushNoDuplicate(item);
  5362. }
  5363. };
  5364. SmartArray.prototype.indexOf = function (value) {
  5365. var position = this.data.indexOf(value);
  5366. if (position >= this.length) {
  5367. return -1;
  5368. }
  5369. return position;
  5370. };
  5371. SmartArray.prototype.contains = function (value) {
  5372. return this.data.indexOf(value) !== -1;
  5373. };
  5374. // Statics
  5375. SmartArray._GlobalId = 0;
  5376. return SmartArray;
  5377. }());
  5378. BABYLON.SmartArray = SmartArray;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.smartArray.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. // Screenshots
  5384. var screenshotCanvas;
  5385. var cloneValue = function (source, destinationObject) {
  5386. if (!source)
  5387. return null;
  5388. if (source instanceof BABYLON.Mesh) {
  5389. return null;
  5390. }
  5391. if (source instanceof BABYLON.SubMesh) {
  5392. return source.clone(destinationObject);
  5393. }
  5394. else if (source.clone) {
  5395. return source.clone();
  5396. }
  5397. return null;
  5398. };
  5399. var Tools = (function () {
  5400. function Tools() {
  5401. }
  5402. ;
  5403. /**
  5404. * Interpolates between a and b via alpha
  5405. * @param a The lower value (returned when alpha = 0)
  5406. * @param b The upper value (returned when alpha = 1)
  5407. * @param alpha The interpolation-factor
  5408. * @return The mixed value
  5409. */
  5410. Tools.Mix = function (a, b, alpha) {
  5411. return a * (1 - alpha) + b * alpha;
  5412. };
  5413. Tools.Instantiate = function (className) {
  5414. var arr = className.split(".");
  5415. var fn = (window || this);
  5416. for (var i = 0, len = arr.length; i < len; i++) {
  5417. fn = fn[arr[i]];
  5418. }
  5419. if (typeof fn !== "function") {
  5420. return null;
  5421. }
  5422. return fn;
  5423. };
  5424. Tools.SetImmediate = function (action) {
  5425. if (window.setImmediate) {
  5426. window.setImmediate(action);
  5427. }
  5428. else {
  5429. setTimeout(action, 1);
  5430. }
  5431. };
  5432. Tools.IsExponentOfTwo = function (value) {
  5433. var count = 1;
  5434. do {
  5435. count *= 2;
  5436. } while (count < value);
  5437. return count === value;
  5438. };
  5439. /**
  5440. * Find the next highest power of two.
  5441. * @param x Number to start search from.
  5442. * @return Next highest power of two.
  5443. */
  5444. Tools.CeilingPOT = function (x) {
  5445. x--;
  5446. x |= x >> 1;
  5447. x |= x >> 2;
  5448. x |= x >> 4;
  5449. x |= x >> 8;
  5450. x |= x >> 16;
  5451. x++;
  5452. return x;
  5453. };
  5454. /**
  5455. * Find the next lowest power of two.
  5456. * @param x Number to start search from.
  5457. * @return Next lowest power of two.
  5458. */
  5459. Tools.FloorPOT = function (x) {
  5460. x = x | (x >> 1);
  5461. x = x | (x >> 2);
  5462. x = x | (x >> 4);
  5463. x = x | (x >> 8);
  5464. x = x | (x >> 16);
  5465. return x - (x >> 1);
  5466. };
  5467. /**
  5468. * Find the nearest power of two.
  5469. * @param x Number to start search from.
  5470. * @return Next nearest power of two.
  5471. */
  5472. Tools.NearestPOT = function (x) {
  5473. var c = Tools.CeilingPOT(x);
  5474. var f = Tools.FloorPOT(x);
  5475. return (c - x) > (x - f) ? f : c;
  5476. };
  5477. Tools.GetExponentOfTwo = function (value, max, mode) {
  5478. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5479. var pot;
  5480. switch (mode) {
  5481. case BABYLON.Engine.SCALEMODE_FLOOR:
  5482. pot = Tools.FloorPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_NEAREST:
  5485. pot = Tools.NearestPOT(value);
  5486. break;
  5487. case BABYLON.Engine.SCALEMODE_CEILING:
  5488. pot = Tools.CeilingPOT(value);
  5489. break;
  5490. }
  5491. return Math.min(pot, max);
  5492. };
  5493. Tools.GetFilename = function (path) {
  5494. var index = path.lastIndexOf("/");
  5495. if (index < 0)
  5496. return path;
  5497. return path.substring(index + 1);
  5498. };
  5499. Tools.GetDOMTextContent = function (element) {
  5500. var result = "";
  5501. var child = element.firstChild;
  5502. while (child) {
  5503. if (child.nodeType === 3) {
  5504. result += child.textContent;
  5505. }
  5506. child = child.nextSibling;
  5507. }
  5508. return result;
  5509. };
  5510. Tools.ToDegrees = function (angle) {
  5511. return angle * 180 / Math.PI;
  5512. };
  5513. Tools.ToRadians = function (angle) {
  5514. return angle * Math.PI / 180;
  5515. };
  5516. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5517. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5518. var output = "";
  5519. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5520. var i = 0;
  5521. var bytes = new Uint8Array(buffer);
  5522. while (i < bytes.length) {
  5523. chr1 = bytes[i++];
  5524. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5525. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5526. enc1 = chr1 >> 2;
  5527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5529. enc4 = chr3 & 63;
  5530. if (isNaN(chr2)) {
  5531. enc3 = enc4 = 64;
  5532. }
  5533. else if (isNaN(chr3)) {
  5534. enc4 = 64;
  5535. }
  5536. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5537. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5538. }
  5539. return "data:image/png;base64," + output;
  5540. };
  5541. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5542. if (bias === void 0) { bias = null; }
  5543. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5544. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5545. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5546. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5547. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5548. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5549. }
  5550. if (bias) {
  5551. minimum.x -= minimum.x * bias.x + bias.y;
  5552. minimum.y -= minimum.y * bias.x + bias.y;
  5553. minimum.z -= minimum.z * bias.x + bias.y;
  5554. maximum.x += maximum.x * bias.x + bias.y;
  5555. maximum.y += maximum.y * bias.x + bias.y;
  5556. maximum.z += maximum.z * bias.x + bias.y;
  5557. }
  5558. return {
  5559. minimum: minimum,
  5560. maximum: maximum
  5561. };
  5562. };
  5563. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5564. if (bias === void 0) { bias = null; }
  5565. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5566. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5567. if (!stride) {
  5568. stride = 3;
  5569. }
  5570. for (var index = start; index < start + count; index++) {
  5571. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5572. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5573. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5574. }
  5575. if (bias) {
  5576. minimum.x -= minimum.x * bias.x + bias.y;
  5577. minimum.y -= minimum.y * bias.x + bias.y;
  5578. minimum.z -= minimum.z * bias.x + bias.y;
  5579. maximum.x += maximum.x * bias.x + bias.y;
  5580. maximum.y += maximum.y * bias.x + bias.y;
  5581. maximum.z += maximum.z * bias.x + bias.y;
  5582. }
  5583. return {
  5584. minimum: minimum,
  5585. maximum: maximum
  5586. };
  5587. };
  5588. Tools.Vector2ArrayFeeder = function (array) {
  5589. return function (index) {
  5590. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5591. var length = isFloatArray ? array.length / 2 : array.length;
  5592. if (index >= length) {
  5593. return null;
  5594. }
  5595. if (isFloatArray) {
  5596. var fa = array;
  5597. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5598. }
  5599. var a = array;
  5600. return a[index];
  5601. };
  5602. };
  5603. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5604. if (bias === void 0) { bias = null; }
  5605. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5606. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5607. var i = 0;
  5608. var cur = feeder(i++);
  5609. while (cur) {
  5610. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5611. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5612. cur = feeder(i++);
  5613. }
  5614. if (bias) {
  5615. minimum.x -= minimum.x * bias.x + bias.y;
  5616. minimum.y -= minimum.y * bias.x + bias.y;
  5617. maximum.x += maximum.x * bias.x + bias.y;
  5618. maximum.y += maximum.y * bias.x + bias.y;
  5619. }
  5620. return {
  5621. minimum: minimum,
  5622. maximum: maximum
  5623. };
  5624. };
  5625. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5626. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5627. return undefined;
  5628. return Array.isArray(obj) ? obj : [obj];
  5629. };
  5630. // Misc.
  5631. Tools.GetPointerPrefix = function () {
  5632. var eventPrefix = "pointer";
  5633. // Check if pointer events are supported
  5634. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5635. eventPrefix = "mouse";
  5636. }
  5637. return eventPrefix;
  5638. };
  5639. /**
  5640. * @param func - the function to be called
  5641. * @param requester - the object that will request the next frame. Falls back to window.
  5642. */
  5643. Tools.QueueNewFrame = function (func, requester) {
  5644. if (requester === void 0) { requester = window; }
  5645. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5646. /*if(requester.isPresenting) {
  5647. return;
  5648. } else*/ if (requester.requestAnimationFrame)
  5649. requester.requestAnimationFrame(func);
  5650. else if (requester.msRequestAnimationFrame)
  5651. requester.msRequestAnimationFrame(func);
  5652. else if (requester.webkitRequestAnimationFrame)
  5653. requester.webkitRequestAnimationFrame(func);
  5654. else if (requester.mozRequestAnimationFrame)
  5655. requester.mozRequestAnimationFrame(func);
  5656. else if (requester.oRequestAnimationFrame)
  5657. requester.oRequestAnimationFrame(func);
  5658. else {
  5659. window.setTimeout(func, 16);
  5660. }
  5661. };
  5662. Tools.RequestFullscreen = function (element) {
  5663. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5664. if (!requestFunction)
  5665. return;
  5666. requestFunction.call(element);
  5667. };
  5668. Tools.ExitFullscreen = function () {
  5669. if (document.exitFullscreen) {
  5670. document.exitFullscreen();
  5671. }
  5672. else if (document.mozCancelFullScreen) {
  5673. document.mozCancelFullScreen();
  5674. }
  5675. else if (document.webkitCancelFullScreen) {
  5676. document.webkitCancelFullScreen();
  5677. }
  5678. else if (document.msCancelFullScreen) {
  5679. document.msCancelFullScreen();
  5680. }
  5681. };
  5682. Tools.SetCorsBehavior = function (url, img) {
  5683. if (Tools.CorsBehavior) {
  5684. switch (typeof (Tools.CorsBehavior)) {
  5685. case "function":
  5686. var result = Tools.CorsBehavior(url);
  5687. if (result) {
  5688. img.crossOrigin = result;
  5689. }
  5690. break;
  5691. case "string":
  5692. default:
  5693. img.crossOrigin = Tools.CorsBehavior;
  5694. break;
  5695. }
  5696. }
  5697. };
  5698. // External files
  5699. Tools.CleanUrl = function (url) {
  5700. url = url.replace(/#/mg, "%23");
  5701. return url;
  5702. };
  5703. Tools.LoadImage = function (url, onload, onerror, database) {
  5704. if (url instanceof ArrayBuffer) {
  5705. url = Tools.EncodeArrayBufferTobase64(url);
  5706. }
  5707. url = Tools.CleanUrl(url);
  5708. url = Tools.PreprocessUrl(url);
  5709. var img = new Image();
  5710. if (url.substr(0, 5) !== "data:") {
  5711. Tools.SetCorsBehavior(url, img);
  5712. }
  5713. img.onload = function () {
  5714. onload(img);
  5715. };
  5716. img.onerror = function (err) {
  5717. Tools.Error("Error while trying to load image: " + url);
  5718. if (Tools.UseFallbackTexture) {
  5719. img.src = Tools.fallbackTexture;
  5720. onload(img);
  5721. }
  5722. else {
  5723. onerror();
  5724. }
  5725. };
  5726. var noIndexedDB = function () {
  5727. img.src = url;
  5728. };
  5729. var loadFromIndexedDB = function () {
  5730. database.loadImageFromDB(url, img);
  5731. };
  5732. //ANY database to do!
  5733. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5734. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5735. }
  5736. else {
  5737. if (url.indexOf("file:") !== 0) {
  5738. noIndexedDB();
  5739. }
  5740. else {
  5741. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5742. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5743. try {
  5744. var blobURL;
  5745. try {
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5747. }
  5748. catch (ex) {
  5749. // Chrome doesn't support oneTimeOnly parameter
  5750. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5751. }
  5752. img.src = blobURL;
  5753. }
  5754. catch (e) {
  5755. img.src = null;
  5756. }
  5757. }
  5758. else {
  5759. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5760. img.src = Tools.fallbackTexture;
  5761. }
  5762. }
  5763. }
  5764. return img;
  5765. };
  5766. //ANY
  5767. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5768. url = Tools.CleanUrl(url);
  5769. url = Tools.PreprocessUrl(url);
  5770. var noIndexedDB = function () {
  5771. var request = new XMLHttpRequest();
  5772. var loadUrl = Tools.BaseUrl + url;
  5773. request.open('GET', loadUrl, true);
  5774. if (useArrayBuffer) {
  5775. request.responseType = "arraybuffer";
  5776. }
  5777. request.onprogress = progressCallBack;
  5778. request.onreadystatechange = function () {
  5779. // In case of undefined state in some browsers.
  5780. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5781. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5782. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5783. callback(!useArrayBuffer ? request.responseText : request.response);
  5784. }
  5785. else {
  5786. if (onError) {
  5787. onError(request);
  5788. }
  5789. else {
  5790. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5791. }
  5792. }
  5793. }
  5794. };
  5795. request.send(null);
  5796. };
  5797. var loadFromIndexedDB = function () {
  5798. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5799. };
  5800. if (url.indexOf("file:") !== -1) {
  5801. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5802. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5803. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5804. }
  5805. else {
  5806. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5807. }
  5808. }
  5809. else {
  5810. // Caching all files
  5811. if (database && database.enableSceneOffline) {
  5812. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5813. }
  5814. else {
  5815. noIndexedDB();
  5816. }
  5817. }
  5818. };
  5819. /**
  5820. * Load a script (identified by an url). When the url returns, the
  5821. * content of this file is added into a new script element, attached to the DOM (body element)
  5822. */
  5823. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5824. var head = document.getElementsByTagName('head')[0];
  5825. var script = document.createElement('script');
  5826. script.type = 'text/javascript';
  5827. script.src = scriptUrl;
  5828. var self = this;
  5829. script.onload = function () {
  5830. if (onSuccess) {
  5831. onSuccess();
  5832. }
  5833. };
  5834. script.onerror = function () {
  5835. if (onError) {
  5836. onError();
  5837. }
  5838. };
  5839. head.appendChild(script);
  5840. };
  5841. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5842. var reader = new FileReader();
  5843. reader.onload = function (e) {
  5844. //target doesn't have result from ts 1.3
  5845. callback(e.target['result']);
  5846. };
  5847. reader.onprogress = progressCallback;
  5848. reader.readAsDataURL(fileToLoad);
  5849. };
  5850. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5851. var reader = new FileReader();
  5852. reader.onerror = function (e) {
  5853. Tools.Log("Error while reading file: " + fileToLoad.name);
  5854. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5855. };
  5856. reader.onload = function (e) {
  5857. //target doesn't have result from ts 1.3
  5858. callback(e.target['result']);
  5859. };
  5860. reader.onprogress = progressCallBack;
  5861. if (!useArrayBuffer) {
  5862. // Asynchronous read
  5863. reader.readAsText(fileToLoad);
  5864. }
  5865. else {
  5866. reader.readAsArrayBuffer(fileToLoad);
  5867. }
  5868. };
  5869. //returns a downloadable url to a file content.
  5870. Tools.FileAsURL = function (content) {
  5871. var fileBlob = new Blob([content]);
  5872. var url = window.URL || window.webkitURL;
  5873. var link = url.createObjectURL(fileBlob);
  5874. return link;
  5875. };
  5876. // Misc.
  5877. Tools.Format = function (value, decimals) {
  5878. if (decimals === void 0) { decimals = 2; }
  5879. return value.toFixed(decimals);
  5880. };
  5881. Tools.CheckExtends = function (v, min, max) {
  5882. if (v.x < min.x)
  5883. min.x = v.x;
  5884. if (v.y < min.y)
  5885. min.y = v.y;
  5886. if (v.z < min.z)
  5887. min.z = v.z;
  5888. if (v.x > max.x)
  5889. max.x = v.x;
  5890. if (v.y > max.y)
  5891. max.y = v.y;
  5892. if (v.z > max.z)
  5893. max.z = v.z;
  5894. };
  5895. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5896. for (var prop in source) {
  5897. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5898. continue;
  5899. }
  5900. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5901. continue;
  5902. }
  5903. var sourceValue = source[prop];
  5904. var typeOfSourceValue = typeof sourceValue;
  5905. if (typeOfSourceValue === "function") {
  5906. continue;
  5907. }
  5908. if (typeOfSourceValue === "object") {
  5909. if (sourceValue instanceof Array) {
  5910. destination[prop] = [];
  5911. if (sourceValue.length > 0) {
  5912. if (typeof sourceValue[0] == "object") {
  5913. for (var index = 0; index < sourceValue.length; index++) {
  5914. var clonedValue = cloneValue(sourceValue[index], destination);
  5915. if (destination[prop].indexOf(clonedValue) === -1) {
  5916. destination[prop].push(clonedValue);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = sourceValue.slice(0);
  5922. }
  5923. }
  5924. }
  5925. else {
  5926. destination[prop] = cloneValue(sourceValue, destination);
  5927. }
  5928. }
  5929. else {
  5930. destination[prop] = sourceValue;
  5931. }
  5932. }
  5933. };
  5934. Tools.IsEmpty = function (obj) {
  5935. for (var i in obj) {
  5936. return false;
  5937. }
  5938. return true;
  5939. };
  5940. Tools.RegisterTopRootEvents = function (events) {
  5941. for (var index = 0; index < events.length; index++) {
  5942. var event = events[index];
  5943. window.addEventListener(event.name, event.handler, false);
  5944. try {
  5945. if (window.parent) {
  5946. window.parent.addEventListener(event.name, event.handler, false);
  5947. }
  5948. }
  5949. catch (e) {
  5950. // Silently fails...
  5951. }
  5952. }
  5953. };
  5954. Tools.UnregisterTopRootEvents = function (events) {
  5955. for (var index = 0; index < events.length; index++) {
  5956. var event = events[index];
  5957. window.removeEventListener(event.name, event.handler);
  5958. try {
  5959. if (window.parent) {
  5960. window.parent.removeEventListener(event.name, event.handler);
  5961. }
  5962. }
  5963. catch (e) {
  5964. // Silently fails...
  5965. }
  5966. }
  5967. };
  5968. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5969. if (mimeType === void 0) { mimeType = "image/png"; }
  5970. // Read the contents of the framebuffer
  5971. var numberOfChannelsByLine = width * 4;
  5972. var halfHeight = height / 2;
  5973. //Reading datas from WebGL
  5974. var data = engine.readPixels(0, 0, width, height);
  5975. //To flip image on Y axis.
  5976. for (var i = 0; i < halfHeight; i++) {
  5977. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5978. var currentCell = j + i * numberOfChannelsByLine;
  5979. var targetLine = height - i - 1;
  5980. var targetCell = j + targetLine * numberOfChannelsByLine;
  5981. var temp = data[currentCell];
  5982. data[currentCell] = data[targetCell];
  5983. data[targetCell] = temp;
  5984. }
  5985. }
  5986. // Create a 2D canvas to store the result
  5987. if (!screenshotCanvas) {
  5988. screenshotCanvas = document.createElement('canvas');
  5989. }
  5990. screenshotCanvas.width = width;
  5991. screenshotCanvas.height = height;
  5992. var context = screenshotCanvas.getContext('2d');
  5993. // Copy the pixels to a 2D canvas
  5994. var imageData = context.createImageData(width, height);
  5995. var castData = (imageData.data);
  5996. castData.set(data);
  5997. context.putImageData(imageData, 0, 0);
  5998. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5999. };
  6000. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6001. if (mimeType === void 0) { mimeType = "image/png"; }
  6002. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6003. if (successCallback) {
  6004. successCallback(base64Image);
  6005. }
  6006. else {
  6007. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6008. if (("download" in document.createElement("a"))) {
  6009. var a = window.document.createElement("a");
  6010. a.href = base64Image;
  6011. var date = new Date();
  6012. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6013. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6014. window.document.body.appendChild(a);
  6015. a.addEventListener("click", function () {
  6016. a.parentElement.removeChild(a);
  6017. });
  6018. a.click();
  6019. //Or opening a new tab with the image if it is not possible to automatically start download.
  6020. }
  6021. else {
  6022. var newWindow = window.open("");
  6023. var img = newWindow.document.createElement("img");
  6024. img.src = base64Image;
  6025. newWindow.document.body.appendChild(img);
  6026. }
  6027. }
  6028. };
  6029. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6030. if (mimeType === void 0) { mimeType = "image/png"; }
  6031. var width;
  6032. var height;
  6033. // If a precision value is specified
  6034. if (size.precision) {
  6035. width = Math.round(engine.getRenderWidth() * size.precision);
  6036. height = Math.round(width / engine.getAspectRatio(camera));
  6037. }
  6038. else if (size.width && size.height) {
  6039. width = size.width;
  6040. height = size.height;
  6041. }
  6042. else if (size.width && !size.height) {
  6043. width = size.width;
  6044. height = Math.round(width / engine.getAspectRatio(camera));
  6045. }
  6046. else if (size.height && !size.width) {
  6047. height = size.height;
  6048. width = Math.round(height * engine.getAspectRatio(camera));
  6049. }
  6050. else if (!isNaN(size)) {
  6051. height = size;
  6052. width = size;
  6053. }
  6054. else {
  6055. Tools.Error("Invalid 'size' parameter !");
  6056. return;
  6057. }
  6058. if (!screenshotCanvas) {
  6059. screenshotCanvas = document.createElement('canvas');
  6060. }
  6061. screenshotCanvas.width = width;
  6062. screenshotCanvas.height = height;
  6063. var renderContext = screenshotCanvas.getContext("2d");
  6064. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6065. var newWidth = width;
  6066. var newHeight = newWidth / ratio;
  6067. if (newHeight > height) {
  6068. newHeight = height;
  6069. newWidth = newHeight * ratio;
  6070. }
  6071. var offsetX = Math.max(0, width - newWidth) / 2;
  6072. var offsetY = Math.max(0, height - newHeight) / 2;
  6073. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6074. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6075. };
  6076. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6077. if (mimeType === void 0) { mimeType = "image/png"; }
  6078. if (samples === void 0) { samples = 1; }
  6079. var width;
  6080. var height;
  6081. //If a precision value is specified
  6082. if (size.precision) {
  6083. width = Math.round(engine.getRenderWidth() * size.precision);
  6084. height = Math.round(width / engine.getAspectRatio(camera));
  6085. size = { width: width, height: height };
  6086. }
  6087. else if (size.width && size.height) {
  6088. width = size.width;
  6089. height = size.height;
  6090. }
  6091. else if (size.width && !size.height) {
  6092. width = size.width;
  6093. height = Math.round(width / engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (size.height && !size.width) {
  6097. height = size.height;
  6098. width = Math.round(height * engine.getAspectRatio(camera));
  6099. size = { width: width, height: height };
  6100. }
  6101. else if (!isNaN(size)) {
  6102. height = size;
  6103. width = size;
  6104. }
  6105. else {
  6106. Tools.Error("Invalid 'size' parameter !");
  6107. return;
  6108. }
  6109. var scene = camera.getScene();
  6110. var previousCamera = null;
  6111. if (scene.activeCamera !== camera) {
  6112. previousCamera = scene.activeCamera;
  6113. scene.activeCamera = camera;
  6114. }
  6115. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6116. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6117. texture.renderList = null;
  6118. texture.samples = samples;
  6119. texture.onAfterRenderObservable.add(function () {
  6120. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6121. });
  6122. scene.incrementRenderId();
  6123. scene.resetCachedMaterial();
  6124. texture.render(true);
  6125. texture.dispose();
  6126. if (previousCamera) {
  6127. scene.activeCamera = previousCamera;
  6128. }
  6129. camera.getProjectionMatrix(true); // Force cache refresh;
  6130. };
  6131. // XHR response validator for local file scenario
  6132. Tools.ValidateXHRData = function (xhr, dataType) {
  6133. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6134. if (dataType === void 0) { dataType = 7; }
  6135. try {
  6136. if (dataType & 1) {
  6137. if (xhr.responseText && xhr.responseText.length > 0) {
  6138. return true;
  6139. }
  6140. else if (dataType === 1) {
  6141. return false;
  6142. }
  6143. }
  6144. if (dataType & 2) {
  6145. // Check header width and height since there is no "TGA" magic number
  6146. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6147. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6148. return true;
  6149. }
  6150. else if (dataType === 2) {
  6151. return false;
  6152. }
  6153. }
  6154. if (dataType & 4) {
  6155. // Check for the "DDS" magic number
  6156. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6157. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6158. return true;
  6159. }
  6160. else {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. catch (e) {
  6166. // Global protection
  6167. }
  6168. return false;
  6169. };
  6170. /**
  6171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6172. * Be aware Math.random() could cause collisions, but:
  6173. * "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"
  6174. */
  6175. Tools.RandomId = function () {
  6176. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6177. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6178. return v.toString(16);
  6179. });
  6180. };
  6181. Object.defineProperty(Tools, "NoneLogLevel", {
  6182. get: function () {
  6183. return Tools._NoneLogLevel;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Tools, "MessageLogLevel", {
  6189. get: function () {
  6190. return Tools._MessageLogLevel;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Tools, "WarningLogLevel", {
  6196. get: function () {
  6197. return Tools._WarningLogLevel;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Tools, "ErrorLogLevel", {
  6203. get: function () {
  6204. return Tools._ErrorLogLevel;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Tools, "AllLogLevel", {
  6210. get: function () {
  6211. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Tools._AddLogEntry = function (entry) {
  6217. Tools._LogCache = entry + Tools._LogCache;
  6218. if (Tools.OnNewCacheEntry) {
  6219. Tools.OnNewCacheEntry(entry);
  6220. }
  6221. };
  6222. Tools._FormatMessage = function (message) {
  6223. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6224. var date = new Date();
  6225. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6226. };
  6227. Tools._LogDisabled = function (message) {
  6228. // nothing to do
  6229. };
  6230. Tools._LogEnabled = function (message) {
  6231. var formattedMessage = Tools._FormatMessage(message);
  6232. console.log("BJS - " + formattedMessage);
  6233. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6234. Tools._AddLogEntry(entry);
  6235. };
  6236. Tools._WarnDisabled = function (message) {
  6237. // nothing to do
  6238. };
  6239. Tools._WarnEnabled = function (message) {
  6240. var formattedMessage = Tools._FormatMessage(message);
  6241. console.warn("BJS - " + formattedMessage);
  6242. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6243. Tools._AddLogEntry(entry);
  6244. };
  6245. Tools._ErrorDisabled = function (message) {
  6246. // nothing to do
  6247. };
  6248. Tools._ErrorEnabled = function (message) {
  6249. Tools.errorsCount++;
  6250. var formattedMessage = Tools._FormatMessage(message);
  6251. console.error("BJS - " + formattedMessage);
  6252. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6253. Tools._AddLogEntry(entry);
  6254. };
  6255. Object.defineProperty(Tools, "LogCache", {
  6256. get: function () {
  6257. return Tools._LogCache;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Tools.ClearLogCache = function () {
  6263. Tools._LogCache = "";
  6264. Tools.errorsCount = 0;
  6265. };
  6266. Object.defineProperty(Tools, "LogLevels", {
  6267. set: function (level) {
  6268. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6269. Tools.Log = Tools._LogEnabled;
  6270. }
  6271. else {
  6272. Tools.Log = Tools._LogDisabled;
  6273. }
  6274. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6275. Tools.Warn = Tools._WarnEnabled;
  6276. }
  6277. else {
  6278. Tools.Warn = Tools._WarnDisabled;
  6279. }
  6280. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6281. Tools.Error = Tools._ErrorEnabled;
  6282. }
  6283. else {
  6284. Tools.Error = Tools._ErrorDisabled;
  6285. }
  6286. },
  6287. enumerable: true,
  6288. configurable: true
  6289. });
  6290. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6291. get: function () {
  6292. return Tools._PerformanceNoneLogLevel;
  6293. },
  6294. enumerable: true,
  6295. configurable: true
  6296. });
  6297. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6298. get: function () {
  6299. return Tools._PerformanceUserMarkLogLevel;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6305. get: function () {
  6306. return Tools._PerformanceConsoleLogLevel;
  6307. },
  6308. enumerable: true,
  6309. configurable: true
  6310. });
  6311. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6312. set: function (level) {
  6313. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6315. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6316. return;
  6317. }
  6318. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6319. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6320. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6321. return;
  6322. }
  6323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6325. },
  6326. enumerable: true,
  6327. configurable: true
  6328. });
  6329. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6332. };
  6333. Tools._StartUserMark = function (counterName, condition) {
  6334. if (condition === void 0) { condition = true; }
  6335. if (!condition || !Tools._performance.mark) {
  6336. return;
  6337. }
  6338. Tools._performance.mark(counterName + "-Begin");
  6339. };
  6340. Tools._EndUserMark = function (counterName, condition) {
  6341. if (condition === void 0) { condition = true; }
  6342. if (!condition || !Tools._performance.mark) {
  6343. return;
  6344. }
  6345. Tools._performance.mark(counterName + "-End");
  6346. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6347. };
  6348. Tools._StartPerformanceConsole = function (counterName, condition) {
  6349. if (condition === void 0) { condition = true; }
  6350. if (!condition) {
  6351. return;
  6352. }
  6353. Tools._StartUserMark(counterName, condition);
  6354. if (console.time) {
  6355. console.time(counterName);
  6356. }
  6357. };
  6358. Tools._EndPerformanceConsole = function (counterName, condition) {
  6359. if (condition === void 0) { condition = true; }
  6360. if (!condition) {
  6361. return;
  6362. }
  6363. Tools._EndUserMark(counterName, condition);
  6364. if (console.time) {
  6365. console.timeEnd(counterName);
  6366. }
  6367. };
  6368. Object.defineProperty(Tools, "Now", {
  6369. get: function () {
  6370. if (window.performance && window.performance.now) {
  6371. return window.performance.now();
  6372. }
  6373. return new Date().getTime();
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. /**
  6379. * This method will return the name of the class used to create the instance of the given object.
  6380. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6381. * @param object the object to get the class name from
  6382. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6383. */
  6384. Tools.GetClassName = function (object, isType) {
  6385. if (isType === void 0) { isType = false; }
  6386. var name = null;
  6387. if (!isType && object.getClassName) {
  6388. name = object.getClassName();
  6389. }
  6390. else {
  6391. if (object instanceof Object) {
  6392. var classObj = isType ? object : Object.getPrototypeOf(object);
  6393. name = classObj.constructor["__bjsclassName__"];
  6394. }
  6395. if (!name) {
  6396. name = typeof object;
  6397. }
  6398. }
  6399. return name;
  6400. };
  6401. Tools.first = function (array, predicate) {
  6402. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6403. var el = array_1[_i];
  6404. if (predicate(el)) {
  6405. return el;
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * This method will return the name of the full name of the class, including its owning module (if any).
  6411. * 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).
  6412. * @param object the object to get the class name from
  6413. * @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.
  6414. */
  6415. Tools.getFullClassName = function (object, isType) {
  6416. if (isType === void 0) { isType = false; }
  6417. var className = null;
  6418. var moduleName = null;
  6419. if (!isType && object.getClassName) {
  6420. className = object.getClassName();
  6421. }
  6422. else {
  6423. if (object instanceof Object) {
  6424. var classObj = isType ? object : Object.getPrototypeOf(object);
  6425. className = classObj.constructor["__bjsclassName__"];
  6426. moduleName = classObj.constructor["__bjsmoduleName__"];
  6427. }
  6428. if (!className) {
  6429. className = typeof object;
  6430. }
  6431. }
  6432. if (!className) {
  6433. return null;
  6434. }
  6435. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6436. };
  6437. /**
  6438. * 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.
  6439. * @param array
  6440. */
  6441. Tools.arrayOrStringFeeder = function (array) {
  6442. return function (index) {
  6443. if (index >= array.length) {
  6444. return null;
  6445. }
  6446. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6447. if (val && val.getHashCode) {
  6448. val = val.getHashCode();
  6449. }
  6450. if (typeof val === "string") {
  6451. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6452. }
  6453. return val;
  6454. };
  6455. };
  6456. /**
  6457. * Compute the hashCode of a stream of number
  6458. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6459. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6460. * @return the hash code computed
  6461. */
  6462. Tools.hashCodeFromStream = function (feeder) {
  6463. // Based from here: http://stackoverflow.com/a/7616484/802124
  6464. var hash = 0;
  6465. var index = 0;
  6466. var chr = feeder(index++);
  6467. while (chr != null) {
  6468. hash = ((hash << 5) - hash) + chr;
  6469. hash |= 0; // Convert to 32bit integer
  6470. chr = feeder(index++);
  6471. }
  6472. return hash;
  6473. };
  6474. Tools.BaseUrl = "";
  6475. Tools.CorsBehavior = "anonymous";
  6476. Tools.UseFallbackTexture = true;
  6477. // Used in case of a texture loading problem
  6478. 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";
  6479. Tools.PreprocessUrl = function (url) {
  6480. return url;
  6481. };
  6482. // Logs
  6483. Tools._NoneLogLevel = 0;
  6484. Tools._MessageLogLevel = 1;
  6485. Tools._WarningLogLevel = 2;
  6486. Tools._ErrorLogLevel = 4;
  6487. Tools._LogCache = "";
  6488. Tools.errorsCount = 0;
  6489. Tools.Log = Tools._LogEnabled;
  6490. Tools.Warn = Tools._WarnEnabled;
  6491. Tools.Error = Tools._ErrorEnabled;
  6492. // Performances
  6493. Tools._PerformanceNoneLogLevel = 0;
  6494. Tools._PerformanceUserMarkLogLevel = 1;
  6495. Tools._PerformanceConsoleLogLevel = 2;
  6496. Tools._performance = window.performance;
  6497. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6498. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6499. return Tools;
  6500. }());
  6501. BABYLON.Tools = Tools;
  6502. /**
  6503. * This class is used to track a performance counter which is number based.
  6504. * The user has access to many properties which give statistics of different nature
  6505. *
  6506. * The implementer can track two kinds of Performance Counter: time and count
  6507. * 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.
  6508. * 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.
  6509. */
  6510. var PerfCounter = (function () {
  6511. function PerfCounter() {
  6512. this._startMonitoringTime = 0;
  6513. this._min = 0;
  6514. this._max = 0;
  6515. this._average = 0;
  6516. this._lastSecAverage = 0;
  6517. this._current = 0;
  6518. this._totalValueCount = 0;
  6519. this._totalAccumulated = 0;
  6520. this._lastSecAccumulated = 0;
  6521. this._lastSecTime = 0;
  6522. this._lastSecValueCount = 0;
  6523. }
  6524. Object.defineProperty(PerfCounter.prototype, "min", {
  6525. /**
  6526. * Returns the smallest value ever
  6527. */
  6528. get: function () {
  6529. return this._min;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(PerfCounter.prototype, "max", {
  6535. /**
  6536. * Returns the biggest value ever
  6537. */
  6538. get: function () {
  6539. return this._max;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(PerfCounter.prototype, "average", {
  6545. /**
  6546. * Returns the average value since the performance counter is running
  6547. */
  6548. get: function () {
  6549. return this._average;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6555. /**
  6556. * Returns the average value of the last second the counter was monitored
  6557. */
  6558. get: function () {
  6559. return this._lastSecAverage;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(PerfCounter.prototype, "current", {
  6565. /**
  6566. * Returns the current value
  6567. */
  6568. get: function () {
  6569. return this._current;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Object.defineProperty(PerfCounter.prototype, "total", {
  6575. get: function () {
  6576. return this._totalAccumulated;
  6577. },
  6578. enumerable: true,
  6579. configurable: true
  6580. });
  6581. /**
  6582. * Call this method to start monitoring a new frame.
  6583. * 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.
  6584. */
  6585. PerfCounter.prototype.fetchNewFrame = function () {
  6586. this._totalValueCount++;
  6587. this._current = 0;
  6588. this._lastSecValueCount++;
  6589. };
  6590. /**
  6591. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6592. * @param newCount the count value to add to the monitored count
  6593. * @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.
  6594. */
  6595. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6596. if (!PerfCounter.Enabled) {
  6597. return;
  6598. }
  6599. this._current += newCount;
  6600. if (fetchResult) {
  6601. this._fetchResult();
  6602. }
  6603. };
  6604. /**
  6605. * Start monitoring this performance counter
  6606. */
  6607. PerfCounter.prototype.beginMonitoring = function () {
  6608. if (!PerfCounter.Enabled) {
  6609. return;
  6610. }
  6611. this._startMonitoringTime = Tools.Now;
  6612. };
  6613. /**
  6614. * Compute the time lapsed since the previous beginMonitoring() call.
  6615. * @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
  6616. */
  6617. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6618. if (newFrame === void 0) { newFrame = true; }
  6619. if (!PerfCounter.Enabled) {
  6620. return;
  6621. }
  6622. if (newFrame) {
  6623. this.fetchNewFrame();
  6624. }
  6625. var currentTime = Tools.Now;
  6626. this._current = currentTime - this._startMonitoringTime;
  6627. if (newFrame) {
  6628. this._fetchResult();
  6629. }
  6630. };
  6631. PerfCounter.prototype._fetchResult = function () {
  6632. this._totalAccumulated += this._current;
  6633. this._lastSecAccumulated += this._current;
  6634. // Min/Max update
  6635. this._min = Math.min(this._min, this._current);
  6636. this._max = Math.max(this._max, this._current);
  6637. this._average = this._totalAccumulated / this._totalValueCount;
  6638. // Reset last sec?
  6639. var now = Tools.Now;
  6640. if ((now - this._lastSecTime) > 1000) {
  6641. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6642. this._lastSecTime = now;
  6643. this._lastSecAccumulated = 0;
  6644. this._lastSecValueCount = 0;
  6645. }
  6646. };
  6647. PerfCounter.Enabled = true;
  6648. return PerfCounter;
  6649. }());
  6650. BABYLON.PerfCounter = PerfCounter;
  6651. /**
  6652. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6653. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6654. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6655. * @param name The name of the class, case should be preserved
  6656. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6657. */
  6658. function className(name, module) {
  6659. return function (target) {
  6660. target["__bjsclassName__"] = name;
  6661. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6662. };
  6663. }
  6664. BABYLON.className = className;
  6665. /**
  6666. * An implementation of a loop for asynchronous functions.
  6667. */
  6668. var AsyncLoop = (function () {
  6669. /**
  6670. * Constroctor.
  6671. * @param iterations the number of iterations.
  6672. * @param _fn the function to run each iteration
  6673. * @param _successCallback the callback that will be called upon succesful execution
  6674. * @param offset starting offset.
  6675. */
  6676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6677. if (offset === void 0) { offset = 0; }
  6678. this.iterations = iterations;
  6679. this._fn = _fn;
  6680. this._successCallback = _successCallback;
  6681. this.index = offset - 1;
  6682. this._done = false;
  6683. }
  6684. /**
  6685. * Execute the next iteration. Must be called after the last iteration was finished.
  6686. */
  6687. AsyncLoop.prototype.executeNext = function () {
  6688. if (!this._done) {
  6689. if (this.index + 1 < this.iterations) {
  6690. ++this.index;
  6691. this._fn(this);
  6692. }
  6693. else {
  6694. this.breakLoop();
  6695. }
  6696. }
  6697. };
  6698. /**
  6699. * Break the loop and run the success callback.
  6700. */
  6701. AsyncLoop.prototype.breakLoop = function () {
  6702. this._done = true;
  6703. this._successCallback();
  6704. };
  6705. /**
  6706. * Helper function
  6707. */
  6708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6709. if (offset === void 0) { offset = 0; }
  6710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6711. loop.executeNext();
  6712. return loop;
  6713. };
  6714. /**
  6715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6716. * @param iterations total number of iterations
  6717. * @param syncedIterations number of synchronous iterations in each async iteration.
  6718. * @param fn the function to call each iteration.
  6719. * @param callback a success call back that will be called when iterating stops.
  6720. * @param breakFunction a break condition (optional)
  6721. * @param timeout timeout settings for the setTimeout function. default - 0.
  6722. * @constructor
  6723. */
  6724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6725. if (timeout === void 0) { timeout = 0; }
  6726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6727. if (breakFunction && breakFunction())
  6728. loop.breakLoop();
  6729. else {
  6730. setTimeout(function () {
  6731. for (var i = 0; i < syncedIterations; ++i) {
  6732. var iteration = (loop.index * syncedIterations) + i;
  6733. if (iteration >= iterations)
  6734. break;
  6735. fn(iteration);
  6736. if (breakFunction && breakFunction()) {
  6737. loop.breakLoop();
  6738. break;
  6739. }
  6740. }
  6741. loop.executeNext();
  6742. }, timeout);
  6743. }
  6744. }, callback);
  6745. };
  6746. return AsyncLoop;
  6747. }());
  6748. BABYLON.AsyncLoop = AsyncLoop;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.tools.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. var Internals;
  6754. (function (Internals) {
  6755. var _AlphaState = (function () {
  6756. /**
  6757. * Initializes the state.
  6758. */
  6759. function _AlphaState() {
  6760. this._isAlphaBlendDirty = false;
  6761. this._isBlendFunctionParametersDirty = false;
  6762. this._isBlendEquationParametersDirty = false;
  6763. this._isBlendConstantsDirty = false;
  6764. this._alphaBlend = false;
  6765. this._blendFunctionParameters = new Array(4);
  6766. this._blendEquationParameters = new Array(2);
  6767. this._blendConstants = new Array(4);
  6768. this.reset();
  6769. }
  6770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6771. get: function () {
  6772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6778. get: function () {
  6779. return this._alphaBlend;
  6780. },
  6781. set: function (value) {
  6782. if (this._alphaBlend === value) {
  6783. return;
  6784. }
  6785. this._alphaBlend = value;
  6786. this._isAlphaBlendDirty = true;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6792. if (this._blendConstants[0] === r &&
  6793. this._blendConstants[1] === g &&
  6794. this._blendConstants[2] === b &&
  6795. this._blendConstants[3] === a) {
  6796. return;
  6797. }
  6798. this._blendConstants[0] = r;
  6799. this._blendConstants[1] = g;
  6800. this._blendConstants[2] = b;
  6801. this._blendConstants[3] = a;
  6802. this._isBlendConstantsDirty = true;
  6803. };
  6804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6805. if (this._blendFunctionParameters[0] === value0 &&
  6806. this._blendFunctionParameters[1] === value1 &&
  6807. this._blendFunctionParameters[2] === value2 &&
  6808. this._blendFunctionParameters[3] === value3) {
  6809. return;
  6810. }
  6811. this._blendFunctionParameters[0] = value0;
  6812. this._blendFunctionParameters[1] = value1;
  6813. this._blendFunctionParameters[2] = value2;
  6814. this._blendFunctionParameters[3] = value3;
  6815. this._isBlendFunctionParametersDirty = true;
  6816. };
  6817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6818. if (this._blendEquationParameters[0] === rgb &&
  6819. this._blendEquationParameters[1] === alpha) {
  6820. return;
  6821. }
  6822. this._blendEquationParameters[0] = rgb;
  6823. this._blendEquationParameters[1] = alpha;
  6824. this._isBlendEquationParametersDirty = true;
  6825. };
  6826. _AlphaState.prototype.reset = function () {
  6827. this._alphaBlend = false;
  6828. this._blendFunctionParameters[0] = null;
  6829. this._blendFunctionParameters[1] = null;
  6830. this._blendFunctionParameters[2] = null;
  6831. this._blendFunctionParameters[3] = null;
  6832. this._blendEquationParameters[0] = null;
  6833. this._blendEquationParameters[1] = null;
  6834. this._blendConstants[0] = null;
  6835. this._blendConstants[1] = null;
  6836. this._blendConstants[2] = null;
  6837. this._blendConstants[3] = null;
  6838. this._isAlphaBlendDirty = true;
  6839. this._isBlendFunctionParametersDirty = false;
  6840. this._isBlendEquationParametersDirty = false;
  6841. this._isBlendConstantsDirty = false;
  6842. };
  6843. _AlphaState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Alpha blend
  6848. if (this._isAlphaBlendDirty) {
  6849. if (this._alphaBlend) {
  6850. gl.enable(gl.BLEND);
  6851. }
  6852. else {
  6853. gl.disable(gl.BLEND);
  6854. }
  6855. this._isAlphaBlendDirty = false;
  6856. }
  6857. // Alpha function
  6858. if (this._isBlendFunctionParametersDirty) {
  6859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6860. this._isBlendFunctionParametersDirty = false;
  6861. }
  6862. // Alpha equation
  6863. if (this._isBlendEquationParametersDirty) {
  6864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6865. this._isBlendEquationParametersDirty = false;
  6866. }
  6867. // Constants
  6868. if (this._isBlendConstantsDirty) {
  6869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6870. this._isBlendConstantsDirty = false;
  6871. }
  6872. };
  6873. return _AlphaState;
  6874. }());
  6875. Internals._AlphaState = _AlphaState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var Internals;
  6882. (function (Internals) {
  6883. var _DepthCullingState = (function () {
  6884. /**
  6885. * Initializes the state.
  6886. */
  6887. function _DepthCullingState() {
  6888. this._isDepthTestDirty = false;
  6889. this._isDepthMaskDirty = false;
  6890. this._isDepthFuncDirty = false;
  6891. this._isCullFaceDirty = false;
  6892. this._isCullDirty = false;
  6893. this._isZOffsetDirty = false;
  6894. this.reset();
  6895. }
  6896. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6897. get: function () {
  6898. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6904. get: function () {
  6905. return this._zOffset;
  6906. },
  6907. set: function (value) {
  6908. if (this._zOffset === value) {
  6909. return;
  6910. }
  6911. this._zOffset = value;
  6912. this._isZOffsetDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6918. get: function () {
  6919. return this._cullFace;
  6920. },
  6921. set: function (value) {
  6922. if (this._cullFace === value) {
  6923. return;
  6924. }
  6925. this._cullFace = value;
  6926. this._isCullFaceDirty = true;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6932. get: function () {
  6933. return this._cull;
  6934. },
  6935. set: function (value) {
  6936. if (this._cull === value) {
  6937. return;
  6938. }
  6939. this._cull = value;
  6940. this._isCullDirty = true;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6946. get: function () {
  6947. return this._depthFunc;
  6948. },
  6949. set: function (value) {
  6950. if (this._depthFunc === value) {
  6951. return;
  6952. }
  6953. this._depthFunc = value;
  6954. this._isDepthFuncDirty = true;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6960. get: function () {
  6961. return this._depthMask;
  6962. },
  6963. set: function (value) {
  6964. if (this._depthMask === value) {
  6965. return;
  6966. }
  6967. this._depthMask = value;
  6968. this._isDepthMaskDirty = true;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6974. get: function () {
  6975. return this._depthTest;
  6976. },
  6977. set: function (value) {
  6978. if (this._depthTest === value) {
  6979. return;
  6980. }
  6981. this._depthTest = value;
  6982. this._isDepthTestDirty = true;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. _DepthCullingState.prototype.reset = function () {
  6988. this._depthMask = true;
  6989. this._depthTest = true;
  6990. this._depthFunc = null;
  6991. this._cullFace = null;
  6992. this._cull = null;
  6993. this._zOffset = 0;
  6994. this._isDepthTestDirty = true;
  6995. this._isDepthMaskDirty = true;
  6996. this._isDepthFuncDirty = false;
  6997. this._isCullFaceDirty = false;
  6998. this._isCullDirty = false;
  6999. this._isZOffsetDirty = false;
  7000. };
  7001. _DepthCullingState.prototype.apply = function (gl) {
  7002. if (!this.isDirty) {
  7003. return;
  7004. }
  7005. // Cull
  7006. if (this._isCullDirty) {
  7007. if (this.cull) {
  7008. gl.enable(gl.CULL_FACE);
  7009. }
  7010. else {
  7011. gl.disable(gl.CULL_FACE);
  7012. }
  7013. this._isCullDirty = false;
  7014. }
  7015. // Cull face
  7016. if (this._isCullFaceDirty) {
  7017. gl.cullFace(this.cullFace);
  7018. this._isCullFaceDirty = false;
  7019. }
  7020. // Depth mask
  7021. if (this._isDepthMaskDirty) {
  7022. gl.depthMask(this.depthMask);
  7023. this._isDepthMaskDirty = false;
  7024. }
  7025. // Depth test
  7026. if (this._isDepthTestDirty) {
  7027. if (this.depthTest) {
  7028. gl.enable(gl.DEPTH_TEST);
  7029. }
  7030. else {
  7031. gl.disable(gl.DEPTH_TEST);
  7032. }
  7033. this._isDepthTestDirty = false;
  7034. }
  7035. // Depth func
  7036. if (this._isDepthFuncDirty) {
  7037. gl.depthFunc(this.depthFunc);
  7038. this._isDepthFuncDirty = false;
  7039. }
  7040. // zOffset
  7041. if (this._isZOffsetDirty) {
  7042. if (this.zOffset) {
  7043. gl.enable(gl.POLYGON_OFFSET_FILL);
  7044. gl.polygonOffset(this.zOffset, 0);
  7045. }
  7046. else {
  7047. gl.disable(gl.POLYGON_OFFSET_FILL);
  7048. }
  7049. this._isZOffsetDirty = false;
  7050. }
  7051. };
  7052. return _DepthCullingState;
  7053. }());
  7054. Internals._DepthCullingState = _DepthCullingState;
  7055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7056. })(BABYLON || (BABYLON = {}));
  7057. //# sourceMappingURL=babylon.depthCullingState.js.map
  7058. var BABYLON;
  7059. (function (BABYLON) {
  7060. var Internals;
  7061. (function (Internals) {
  7062. var _StencilState = (function () {
  7063. function _StencilState() {
  7064. this._isStencilTestDirty = false;
  7065. this._isStencilMaskDirty = false;
  7066. this._isStencilFuncDirty = false;
  7067. this._isStencilOpDirty = false;
  7068. this.reset();
  7069. }
  7070. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7071. get: function () {
  7072. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7078. get: function () {
  7079. return this._stencilFunc;
  7080. },
  7081. set: function (value) {
  7082. if (this._stencilFunc === value) {
  7083. return;
  7084. }
  7085. this._stencilFunc = value;
  7086. this._isStencilFuncDirty = true;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7092. get: function () {
  7093. return this._stencilFuncRef;
  7094. },
  7095. set: function (value) {
  7096. if (this._stencilFuncRef === value) {
  7097. return;
  7098. }
  7099. this._stencilFuncRef = value;
  7100. this._isStencilFuncDirty = true;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7106. get: function () {
  7107. return this._stencilFuncMask;
  7108. },
  7109. set: function (value) {
  7110. if (this._stencilFuncMask === value) {
  7111. return;
  7112. }
  7113. this._stencilFuncMask = value;
  7114. this._isStencilFuncDirty = true;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7120. get: function () {
  7121. return this._stencilOpStencilFail;
  7122. },
  7123. set: function (value) {
  7124. if (this._stencilOpStencilFail === value) {
  7125. return;
  7126. }
  7127. this._stencilOpStencilFail = value;
  7128. this._isStencilOpDirty = true;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7134. get: function () {
  7135. return this._stencilOpDepthFail;
  7136. },
  7137. set: function (value) {
  7138. if (this._stencilOpDepthFail === value) {
  7139. return;
  7140. }
  7141. this._stencilOpDepthFail = value;
  7142. this._isStencilOpDirty = true;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7148. get: function () {
  7149. return this._stencilOpStencilDepthPass;
  7150. },
  7151. set: function (value) {
  7152. if (this._stencilOpStencilDepthPass === value) {
  7153. return;
  7154. }
  7155. this._stencilOpStencilDepthPass = value;
  7156. this._isStencilOpDirty = true;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7162. get: function () {
  7163. return this._stencilMask;
  7164. },
  7165. set: function (value) {
  7166. if (this._stencilMask === value) {
  7167. return;
  7168. }
  7169. this._stencilMask = value;
  7170. this._isStencilMaskDirty = true;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7176. get: function () {
  7177. return this._stencilTest;
  7178. },
  7179. set: function (value) {
  7180. if (this._stencilTest === value) {
  7181. return;
  7182. }
  7183. this._stencilTest = value;
  7184. this._isStencilTestDirty = true;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. _StencilState.prototype.reset = function () {
  7190. this._stencilTest = false;
  7191. this._stencilMask = 0xFF;
  7192. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7193. this._stencilFuncRef = 1;
  7194. this._stencilFuncMask = 0xFF;
  7195. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7196. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7197. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7198. this._isStencilTestDirty = true;
  7199. this._isStencilMaskDirty = true;
  7200. this._isStencilFuncDirty = true;
  7201. this._isStencilOpDirty = true;
  7202. };
  7203. _StencilState.prototype.apply = function (gl) {
  7204. if (!this.isDirty) {
  7205. return;
  7206. }
  7207. // Stencil test
  7208. if (this._isStencilTestDirty) {
  7209. if (this.stencilTest) {
  7210. gl.enable(gl.STENCIL_TEST);
  7211. }
  7212. else {
  7213. gl.disable(gl.STENCIL_TEST);
  7214. }
  7215. this._isStencilTestDirty = false;
  7216. }
  7217. // Stencil mask
  7218. if (this._isStencilMaskDirty) {
  7219. gl.stencilMask(this.stencilMask);
  7220. this._isStencilMaskDirty = false;
  7221. }
  7222. // Stencil func
  7223. if (this._isStencilFuncDirty) {
  7224. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7225. this._isStencilFuncDirty = false;
  7226. }
  7227. // Stencil op
  7228. if (this._isStencilOpDirty) {
  7229. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7230. this._isStencilOpDirty = false;
  7231. }
  7232. };
  7233. return _StencilState;
  7234. }());
  7235. Internals._StencilState = _StencilState;
  7236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7237. })(BABYLON || (BABYLON = {}));
  7238. //# sourceMappingURL=babylon.stencilState.js.map
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7242. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7243. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7244. gl.compileShader(shader);
  7245. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7246. throw new Error(gl.getShaderInfoLog(shader));
  7247. }
  7248. return shader;
  7249. };
  7250. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7251. var magFilter = gl.NEAREST;
  7252. var minFilter = gl.NEAREST;
  7253. switch (samplingMode) {
  7254. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7255. magFilter = gl.LINEAR;
  7256. if (generateMipMaps) {
  7257. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7258. }
  7259. else {
  7260. minFilter = gl.LINEAR;
  7261. }
  7262. break;
  7263. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7264. magFilter = gl.LINEAR;
  7265. if (generateMipMaps) {
  7266. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7267. }
  7268. else {
  7269. minFilter = gl.LINEAR;
  7270. }
  7271. break;
  7272. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7273. magFilter = gl.NEAREST;
  7274. if (generateMipMaps) {
  7275. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7276. }
  7277. else {
  7278. minFilter = gl.NEAREST;
  7279. }
  7280. break;
  7281. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7282. magFilter = gl.NEAREST;
  7283. if (generateMipMaps) {
  7284. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7285. }
  7286. else {
  7287. minFilter = gl.NEAREST;
  7288. }
  7289. break;
  7290. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7291. magFilter = gl.NEAREST;
  7292. if (generateMipMaps) {
  7293. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7294. }
  7295. else {
  7296. minFilter = gl.LINEAR;
  7297. }
  7298. break;
  7299. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7300. magFilter = gl.NEAREST;
  7301. if (generateMipMaps) {
  7302. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7303. }
  7304. else {
  7305. minFilter = gl.LINEAR;
  7306. }
  7307. break;
  7308. case BABYLON.Texture.NEAREST_LINEAR:
  7309. magFilter = gl.NEAREST;
  7310. minFilter = gl.LINEAR;
  7311. break;
  7312. case BABYLON.Texture.NEAREST_NEAREST:
  7313. magFilter = gl.NEAREST;
  7314. minFilter = gl.NEAREST;
  7315. break;
  7316. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7317. magFilter = gl.LINEAR;
  7318. if (generateMipMaps) {
  7319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7320. }
  7321. else {
  7322. minFilter = gl.NEAREST;
  7323. }
  7324. break;
  7325. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7326. magFilter = gl.LINEAR;
  7327. if (generateMipMaps) {
  7328. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7329. }
  7330. else {
  7331. minFilter = gl.NEAREST;
  7332. }
  7333. break;
  7334. case BABYLON.Texture.LINEAR_LINEAR:
  7335. magFilter = gl.LINEAR;
  7336. minFilter = gl.LINEAR;
  7337. break;
  7338. case BABYLON.Texture.LINEAR_NEAREST:
  7339. magFilter = gl.LINEAR;
  7340. minFilter = gl.NEAREST;
  7341. break;
  7342. }
  7343. return {
  7344. min: minFilter,
  7345. mag: magFilter
  7346. };
  7347. };
  7348. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7350. var img;
  7351. var onload = function () {
  7352. loadedImages[index] = img;
  7353. loadedImages._internalCount++;
  7354. if (scene) {
  7355. scene._removePendingData(img);
  7356. }
  7357. if (loadedImages._internalCount === 6) {
  7358. onfinish(loadedImages);
  7359. }
  7360. };
  7361. var onerror = function () {
  7362. if (scene) {
  7363. scene._removePendingData(img);
  7364. }
  7365. if (onErrorCallBack) {
  7366. onErrorCallBack();
  7367. }
  7368. };
  7369. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7370. if (scene) {
  7371. scene._addPendingData(img);
  7372. }
  7373. };
  7374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7375. if (onError === void 0) { onError = null; }
  7376. var loadedImages = [];
  7377. loadedImages._internalCount = 0;
  7378. for (var index = 0; index < 6; index++) {
  7379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7380. }
  7381. };
  7382. var BufferPointer = (function () {
  7383. function BufferPointer() {
  7384. }
  7385. return BufferPointer;
  7386. }());
  7387. var InstancingAttributeInfo = (function () {
  7388. function InstancingAttributeInfo() {
  7389. }
  7390. return InstancingAttributeInfo;
  7391. }());
  7392. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7393. /**
  7394. * Define options used to create a render target texture
  7395. */
  7396. var RenderTargetCreationOptions = (function () {
  7397. function RenderTargetCreationOptions() {
  7398. }
  7399. return RenderTargetCreationOptions;
  7400. }());
  7401. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7402. /**
  7403. * Regroup several parameters relative to the browser in use
  7404. */
  7405. var EngineCapabilities = (function () {
  7406. function EngineCapabilities() {
  7407. }
  7408. return EngineCapabilities;
  7409. }());
  7410. BABYLON.EngineCapabilities = EngineCapabilities;
  7411. /**
  7412. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7413. */
  7414. var Engine = (function () {
  7415. /**
  7416. * @constructor
  7417. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7418. * @param {boolean} [antialias] - enable antialias
  7419. * @param options - further options to be sent to the getContext function
  7420. */
  7421. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7422. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7423. var _this = this;
  7424. // Public members
  7425. this.forcePOTTextures = false;
  7426. this.isFullscreen = false;
  7427. this.isPointerLock = false;
  7428. this.cullBackFaces = true;
  7429. this.renderEvenInBackground = true;
  7430. this.preventCacheWipeBetweenFrames = false;
  7431. // To enable/disable IDB support and avoid XHR on .manifest
  7432. this.enableOfflineSupport = false;
  7433. this.scenes = new Array();
  7434. this.postProcesses = new Array();
  7435. // Observables
  7436. /**
  7437. * Observable event triggered each time the rendering canvas is resized
  7438. */
  7439. this.onResizeObservable = new BABYLON.Observable();
  7440. /**
  7441. * Observable event triggered each time the canvas lost focus
  7442. */
  7443. this.onCanvasBlurObservable = new BABYLON.Observable();
  7444. // Uniform buffers list
  7445. this.disableUniformBuffers = false;
  7446. this._uniformBuffers = new Array();
  7447. this._windowIsBackground = false;
  7448. this._webGLVersion = 1.0;
  7449. this._badOS = false;
  7450. this._badDesktopOS = false;
  7451. this._drawCalls = new BABYLON.PerfCounter();
  7452. this._renderingQueueLaunched = false;
  7453. this._activeRenderLoops = [];
  7454. // Deterministic lockstepMaxSteps
  7455. this._deterministicLockstep = false;
  7456. this._lockstepMaxSteps = 4;
  7457. // Lost context
  7458. this.onContextLostObservable = new BABYLON.Observable();
  7459. this.onContextRestoredObservable = new BABYLON.Observable();
  7460. this._contextWasLost = false;
  7461. this._doNotHandleContextLost = false;
  7462. // FPS
  7463. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7464. this._fps = 60;
  7465. this._deltaTime = 0;
  7466. /**
  7467. * Turn this value on if you want to pause FPS computation when in background
  7468. */
  7469. this.disablePerformanceMonitorInBackground = false;
  7470. // States
  7471. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7472. this._stencilState = new BABYLON.Internals._StencilState();
  7473. this._alphaState = new BABYLON.Internals._AlphaState();
  7474. this._alphaMode = Engine.ALPHA_DISABLE;
  7475. // Cache
  7476. this._internalTexturesCache = new Array();
  7477. this._maxTextureChannels = 16;
  7478. this._activeTexturesCache = {};
  7479. this._compiledEffects = {};
  7480. this._vertexAttribArraysEnabled = [];
  7481. this._uintIndicesCurrentlySet = false;
  7482. this._currentBoundBuffer = new Array();
  7483. this._currentBufferPointers = new Array();
  7484. this._currentInstanceLocations = new Array();
  7485. this._currentInstanceBuffers = new Array();
  7486. this._vaoRecordInProgress = false;
  7487. this._mustWipeVertexAttributes = false;
  7488. // Hardware supported Compressed Textures
  7489. this._texturesSupported = new Array();
  7490. this._onVRFullScreenTriggered = function () {
  7491. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7492. //get the old size before we change
  7493. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7494. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7495. //get the width and height, change the render size
  7496. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7497. var width, height;
  7498. _this.setHardwareScalingLevel(1);
  7499. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7500. }
  7501. else {
  7502. //When the specs are implemented, need to uncomment this.
  7503. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7504. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7505. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7506. _this._vrDisplayEnabled = undefined;
  7507. }
  7508. };
  7509. var canvas;
  7510. Engine.Instances.push(this);
  7511. options = options || {};
  7512. if (canvasOrContext.getContext) {
  7513. canvas = canvasOrContext;
  7514. this._renderingCanvas = canvas;
  7515. if (antialias != null) {
  7516. options.antialias = antialias;
  7517. }
  7518. if (options.deterministicLockstep === undefined) {
  7519. options.deterministicLockstep = false;
  7520. }
  7521. if (options.lockstepMaxSteps === undefined) {
  7522. options.lockstepMaxSteps = 4;
  7523. }
  7524. if (options.preserveDrawingBuffer === undefined) {
  7525. options.preserveDrawingBuffer = false;
  7526. }
  7527. if (options.audioEngine === undefined) {
  7528. options.audioEngine = true;
  7529. }
  7530. if (options.stencil === undefined) {
  7531. options.stencil = true;
  7532. }
  7533. this._deterministicLockstep = options.deterministicLockstep;
  7534. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7535. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7536. // GL
  7537. if (!options.disableWebGL2Support) {
  7538. try {
  7539. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7540. if (this._gl) {
  7541. this._webGLVersion = 2.0;
  7542. }
  7543. }
  7544. catch (e) {
  7545. // Do nothing
  7546. }
  7547. }
  7548. if (!this._gl) {
  7549. if (!canvas) {
  7550. throw new Error("The provided canvas is null or undefined.");
  7551. }
  7552. try {
  7553. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7554. }
  7555. catch (e) {
  7556. throw new Error("WebGL not supported");
  7557. }
  7558. }
  7559. if (!this._gl) {
  7560. throw new Error("WebGL not supported");
  7561. }
  7562. this._onBlur = function () {
  7563. if (_this.disablePerformanceMonitorInBackground) {
  7564. _this._performanceMonitor.disable();
  7565. }
  7566. _this._windowIsBackground = true;
  7567. };
  7568. this._onFocus = function () {
  7569. if (_this.disablePerformanceMonitorInBackground) {
  7570. _this._performanceMonitor.enable();
  7571. }
  7572. _this._windowIsBackground = false;
  7573. };
  7574. this._onCanvasBlur = function () {
  7575. _this.onCanvasBlurObservable.notifyObservers(_this);
  7576. };
  7577. window.addEventListener("blur", this._onBlur);
  7578. window.addEventListener("focus", this._onFocus);
  7579. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7580. }
  7581. else {
  7582. this._gl = canvasOrContext;
  7583. this._renderingCanvas = this._gl.canvas;
  7584. if (this._gl.renderbufferStorageMultisample) {
  7585. this._webGLVersion = 2.0;
  7586. }
  7587. options.stencil = this._gl.getContextAttributes().stencil;
  7588. }
  7589. // Context lost
  7590. if (!this._doNotHandleContextLost) {
  7591. this._onContextLost = function (evt) {
  7592. evt.preventDefault();
  7593. _this._contextWasLost = true;
  7594. BABYLON.Tools.Warn("WebGL context lost.");
  7595. _this.onContextLostObservable.notifyObservers(_this);
  7596. };
  7597. this._onContextRestored = function (evt) {
  7598. // Rebuild gl context
  7599. _this._initGLContext();
  7600. // Rebuild effects
  7601. _this._rebuildEffects();
  7602. // Rebuild textures
  7603. _this._rebuildInternalTextures();
  7604. // Rebuild buffers
  7605. _this._rebuildBuffers();
  7606. // Cache
  7607. _this.wipeCaches(true);
  7608. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7609. _this.onContextRestoredObservable.notifyObservers(_this);
  7610. _this._contextWasLost = false;
  7611. };
  7612. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7613. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7614. }
  7615. // Viewport
  7616. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7617. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7618. this.resize();
  7619. this._isStencilEnable = options.stencil;
  7620. this._initGLContext();
  7621. if (canvas) {
  7622. // Fullscreen
  7623. this._onFullscreenChange = function () {
  7624. if (document.fullscreen !== undefined) {
  7625. _this.isFullscreen = document.fullscreen;
  7626. }
  7627. else if (document.mozFullScreen !== undefined) {
  7628. _this.isFullscreen = document.mozFullScreen;
  7629. }
  7630. else if (document.webkitIsFullScreen !== undefined) {
  7631. _this.isFullscreen = document.webkitIsFullScreen;
  7632. }
  7633. else if (document.msIsFullScreen !== undefined) {
  7634. _this.isFullscreen = document.msIsFullScreen;
  7635. }
  7636. // Pointer lock
  7637. if (_this.isFullscreen && _this._pointerLockRequested) {
  7638. canvas.requestPointerLock = canvas.requestPointerLock ||
  7639. canvas.msRequestPointerLock ||
  7640. canvas.mozRequestPointerLock ||
  7641. canvas.webkitRequestPointerLock;
  7642. if (canvas.requestPointerLock) {
  7643. canvas.requestPointerLock();
  7644. }
  7645. }
  7646. };
  7647. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7648. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7649. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7650. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7651. // Pointer lock
  7652. this._onPointerLockChange = function () {
  7653. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7654. document.webkitPointerLockElement === canvas ||
  7655. document.msPointerLockElement === canvas ||
  7656. document.pointerLockElement === canvas);
  7657. };
  7658. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7659. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7660. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7661. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7662. this._onVRDisplayPointerRestricted = function () {
  7663. canvas.requestPointerLock();
  7664. };
  7665. this._onVRDisplayPointerUnrestricted = function () {
  7666. document.exitPointerLock();
  7667. };
  7668. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7669. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7670. }
  7671. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7672. Engine.audioEngine = new BABYLON.AudioEngine();
  7673. }
  7674. // Prepare buffer pointers
  7675. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7676. this._currentBufferPointers[i] = new BufferPointer();
  7677. }
  7678. // Load WebVR Devices
  7679. if (options.autoEnableWebVR) {
  7680. this.initWebVR();
  7681. }
  7682. // Detect if we are running on a faulty buggy OS.
  7683. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7684. // Detect if we are running on a faulty buggy desktop OS.
  7685. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7686. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7687. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7688. }
  7689. Object.defineProperty(Engine, "LastCreatedEngine", {
  7690. get: function () {
  7691. if (Engine.Instances.length === 0) {
  7692. return null;
  7693. }
  7694. return Engine.Instances[Engine.Instances.length - 1];
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(Engine, "LastCreatedScene", {
  7700. get: function () {
  7701. var lastCreatedEngine = Engine.LastCreatedEngine;
  7702. if (!lastCreatedEngine) {
  7703. return null;
  7704. }
  7705. if (lastCreatedEngine.scenes.length === 0) {
  7706. return null;
  7707. }
  7708. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. /**
  7714. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7715. */
  7716. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7717. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7718. var engine = Engine.Instances[engineIndex];
  7719. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7720. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7721. }
  7722. }
  7723. };
  7724. Object.defineProperty(Engine, "NEVER", {
  7725. get: function () {
  7726. return Engine._NEVER;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. Object.defineProperty(Engine, "ALWAYS", {
  7732. get: function () {
  7733. return Engine._ALWAYS;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. Object.defineProperty(Engine, "LESS", {
  7739. get: function () {
  7740. return Engine._LESS;
  7741. },
  7742. enumerable: true,
  7743. configurable: true
  7744. });
  7745. Object.defineProperty(Engine, "EQUAL", {
  7746. get: function () {
  7747. return Engine._EQUAL;
  7748. },
  7749. enumerable: true,
  7750. configurable: true
  7751. });
  7752. Object.defineProperty(Engine, "LEQUAL", {
  7753. get: function () {
  7754. return Engine._LEQUAL;
  7755. },
  7756. enumerable: true,
  7757. configurable: true
  7758. });
  7759. Object.defineProperty(Engine, "GREATER", {
  7760. get: function () {
  7761. return Engine._GREATER;
  7762. },
  7763. enumerable: true,
  7764. configurable: true
  7765. });
  7766. Object.defineProperty(Engine, "GEQUAL", {
  7767. get: function () {
  7768. return Engine._GEQUAL;
  7769. },
  7770. enumerable: true,
  7771. configurable: true
  7772. });
  7773. Object.defineProperty(Engine, "NOTEQUAL", {
  7774. get: function () {
  7775. return Engine._NOTEQUAL;
  7776. },
  7777. enumerable: true,
  7778. configurable: true
  7779. });
  7780. Object.defineProperty(Engine, "KEEP", {
  7781. get: function () {
  7782. return Engine._KEEP;
  7783. },
  7784. enumerable: true,
  7785. configurable: true
  7786. });
  7787. Object.defineProperty(Engine, "REPLACE", {
  7788. get: function () {
  7789. return Engine._REPLACE;
  7790. },
  7791. enumerable: true,
  7792. configurable: true
  7793. });
  7794. Object.defineProperty(Engine, "INCR", {
  7795. get: function () {
  7796. return Engine._INCR;
  7797. },
  7798. enumerable: true,
  7799. configurable: true
  7800. });
  7801. Object.defineProperty(Engine, "DECR", {
  7802. get: function () {
  7803. return Engine._DECR;
  7804. },
  7805. enumerable: true,
  7806. configurable: true
  7807. });
  7808. Object.defineProperty(Engine, "INVERT", {
  7809. get: function () {
  7810. return Engine._INVERT;
  7811. },
  7812. enumerable: true,
  7813. configurable: true
  7814. });
  7815. Object.defineProperty(Engine, "INCR_WRAP", {
  7816. get: function () {
  7817. return Engine._INCR_WRAP;
  7818. },
  7819. enumerable: true,
  7820. configurable: true
  7821. });
  7822. Object.defineProperty(Engine, "DECR_WRAP", {
  7823. get: function () {
  7824. return Engine._DECR_WRAP;
  7825. },
  7826. enumerable: true,
  7827. configurable: true
  7828. });
  7829. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7830. get: function () {
  7831. return Engine._ALPHA_DISABLE;
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7837. get: function () {
  7838. return Engine._ALPHA_ONEONE;
  7839. },
  7840. enumerable: true,
  7841. configurable: true
  7842. });
  7843. Object.defineProperty(Engine, "ALPHA_ADD", {
  7844. get: function () {
  7845. return Engine._ALPHA_ADD;
  7846. },
  7847. enumerable: true,
  7848. configurable: true
  7849. });
  7850. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7851. get: function () {
  7852. return Engine._ALPHA_COMBINE;
  7853. },
  7854. enumerable: true,
  7855. configurable: true
  7856. });
  7857. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7858. get: function () {
  7859. return Engine._ALPHA_SUBTRACT;
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7865. get: function () {
  7866. return Engine._ALPHA_MULTIPLY;
  7867. },
  7868. enumerable: true,
  7869. configurable: true
  7870. });
  7871. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7872. get: function () {
  7873. return Engine._ALPHA_MAXIMIZED;
  7874. },
  7875. enumerable: true,
  7876. configurable: true
  7877. });
  7878. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7879. get: function () {
  7880. return Engine._ALPHA_PREMULTIPLIED;
  7881. },
  7882. enumerable: true,
  7883. configurable: true
  7884. });
  7885. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7886. get: function () {
  7887. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7888. },
  7889. enumerable: true,
  7890. configurable: true
  7891. });
  7892. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7893. get: function () {
  7894. return Engine._ALPHA_INTERPOLATE;
  7895. },
  7896. enumerable: true,
  7897. configurable: true
  7898. });
  7899. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7900. get: function () {
  7901. return Engine._ALPHA_SCREENMODE;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7907. get: function () {
  7908. return Engine._DELAYLOADSTATE_NONE;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7914. get: function () {
  7915. return Engine._DELAYLOADSTATE_LOADED;
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7921. get: function () {
  7922. return Engine._DELAYLOADSTATE_LOADING;
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7928. get: function () {
  7929. return Engine._DELAYLOADSTATE_NOTLOADED;
  7930. },
  7931. enumerable: true,
  7932. configurable: true
  7933. });
  7934. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7935. get: function () {
  7936. return Engine._TEXTUREFORMAT_ALPHA;
  7937. },
  7938. enumerable: true,
  7939. configurable: true
  7940. });
  7941. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7942. get: function () {
  7943. return Engine._TEXTUREFORMAT_LUMINANCE;
  7944. },
  7945. enumerable: true,
  7946. configurable: true
  7947. });
  7948. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7949. get: function () {
  7950. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7956. get: function () {
  7957. return Engine._TEXTUREFORMAT_RGB;
  7958. },
  7959. enumerable: true,
  7960. configurable: true
  7961. });
  7962. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7963. get: function () {
  7964. return Engine._TEXTUREFORMAT_RGBA;
  7965. },
  7966. enumerable: true,
  7967. configurable: true
  7968. });
  7969. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7970. get: function () {
  7971. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7977. get: function () {
  7978. return Engine._TEXTURETYPE_FLOAT;
  7979. },
  7980. enumerable: true,
  7981. configurable: true
  7982. });
  7983. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7984. get: function () {
  7985. return Engine._TEXTURETYPE_HALF_FLOAT;
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7991. get: function () {
  7992. return Engine._SCALEMODE_FLOOR;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7998. get: function () {
  7999. return Engine._SCALEMODE_NEAREST;
  8000. },
  8001. enumerable: true,
  8002. configurable: true
  8003. });
  8004. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8005. get: function () {
  8006. return Engine._SCALEMODE_CEILING;
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. Object.defineProperty(Engine, "Version", {
  8012. get: function () {
  8013. return "3.1-alpha";
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8019. get: function () {
  8020. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8021. },
  8022. enumerable: true,
  8023. configurable: true
  8024. });
  8025. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8026. get: function () {
  8027. return this._webGLVersion < 2 || this.forcePOTTextures;
  8028. },
  8029. enumerable: true,
  8030. configurable: true
  8031. });
  8032. Object.defineProperty(Engine.prototype, "badOS", {
  8033. get: function () {
  8034. return this._badOS;
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8040. get: function () {
  8041. return this._badDesktopOS;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8047. get: function () {
  8048. return this._performanceMonitor;
  8049. },
  8050. enumerable: true,
  8051. configurable: true
  8052. });
  8053. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8054. get: function () {
  8055. return this._texturesSupported;
  8056. },
  8057. enumerable: true,
  8058. configurable: true
  8059. });
  8060. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8061. get: function () {
  8062. return this._textureFormatInUse;
  8063. },
  8064. enumerable: true,
  8065. configurable: true
  8066. });
  8067. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8068. // Empty texture
  8069. get: function () {
  8070. if (!this._emptyTexture) {
  8071. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8072. }
  8073. return this._emptyTexture;
  8074. },
  8075. enumerable: true,
  8076. configurable: true
  8077. });
  8078. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8079. get: function () {
  8080. if (!this._emptyCubeTexture) {
  8081. var faceData = new Uint8Array(4);
  8082. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8083. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8084. }
  8085. return this._emptyCubeTexture;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. Engine.prototype._rebuildInternalTextures = function () {
  8091. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8092. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8093. var internalTexture = currentState_1[_i];
  8094. internalTexture._rebuild();
  8095. }
  8096. };
  8097. Engine.prototype._rebuildEffects = function () {
  8098. for (var key in this._compiledEffects) {
  8099. var effect = this._compiledEffects[key];
  8100. effect._prepareEffect();
  8101. }
  8102. BABYLON.Effect.ResetCache();
  8103. };
  8104. Engine.prototype._rebuildBuffers = function () {
  8105. // Index / Vertex
  8106. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8107. var scene = _a[_i];
  8108. scene.resetCachedMaterial();
  8109. scene._rebuildGeometries();
  8110. scene._rebuildTextures();
  8111. }
  8112. // Uniforms
  8113. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8114. var uniformBuffer = _c[_b];
  8115. uniformBuffer._rebuild();
  8116. }
  8117. };
  8118. Engine.prototype._initGLContext = function () {
  8119. // Caps
  8120. this._caps = new EngineCapabilities();
  8121. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8122. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8123. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8124. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8125. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8126. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8127. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8128. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8129. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8130. // Infos
  8131. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8132. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8133. if (rendererInfo != null) {
  8134. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8135. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8136. }
  8137. if (!this._glVendor) {
  8138. this._glVendor = "Unknown vendor";
  8139. }
  8140. if (!this._glRenderer) {
  8141. this._glRenderer = "Unknown renderer";
  8142. }
  8143. // Constants
  8144. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8145. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8146. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8147. this._gl.DEPTH24_STENCIL8 = 35056;
  8148. // Extensions
  8149. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8150. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8151. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8152. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8153. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8154. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8155. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8156. 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');
  8157. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8158. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8159. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8160. this._caps.highPrecisionShaderSupported = true;
  8161. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8162. // Checks if some of the format renders first to allow the use of webgl inspector.
  8163. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8164. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8165. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8166. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8167. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8168. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8169. if (this._webGLVersion > 1) {
  8170. this._gl.HALF_FLOAT_OES = 0x140B;
  8171. }
  8172. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8173. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8174. // Vertex array object
  8175. if (this._webGLVersion > 1) {
  8176. this._caps.vertexArrayObject = true;
  8177. }
  8178. else {
  8179. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8180. if (vertexArrayObjectExtension != null) {
  8181. this._caps.vertexArrayObject = true;
  8182. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8183. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8184. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8185. }
  8186. else {
  8187. this._caps.vertexArrayObject = false;
  8188. }
  8189. }
  8190. // Instances count
  8191. if (this._webGLVersion > 1) {
  8192. this._caps.instancedArrays = true;
  8193. }
  8194. else {
  8195. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8196. if (instanceExtension != null) {
  8197. this._caps.instancedArrays = true;
  8198. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8199. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8200. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8201. }
  8202. else {
  8203. this._caps.instancedArrays = false;
  8204. }
  8205. }
  8206. // Intelligently add supported compressed formats in order to check for.
  8207. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8208. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8209. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8210. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8211. if (this._caps.astc)
  8212. this.texturesSupported.push('-astc.ktx');
  8213. if (this._caps.s3tc)
  8214. this.texturesSupported.push('-dxt.ktx');
  8215. if (this._caps.pvrtc)
  8216. this.texturesSupported.push('-pvrtc.ktx');
  8217. if (this._caps.etc2)
  8218. this.texturesSupported.push('-etc2.ktx');
  8219. if (this._caps.etc1)
  8220. this.texturesSupported.push('-etc1.ktx');
  8221. if (this._gl.getShaderPrecisionFormat) {
  8222. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8223. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8224. }
  8225. // Depth buffer
  8226. this.setDepthBuffer(true);
  8227. this.setDepthFunctionToLessOrEqual();
  8228. this.setDepthWrite(true);
  8229. };
  8230. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8231. get: function () {
  8232. return this._webGLVersion;
  8233. },
  8234. enumerable: true,
  8235. configurable: true
  8236. });
  8237. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8238. /**
  8239. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8240. */
  8241. get: function () {
  8242. return this._isStencilEnable;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Engine.prototype._prepareWorkingCanvas = function () {
  8248. if (this._workingCanvas) {
  8249. return;
  8250. }
  8251. this._workingCanvas = document.createElement("canvas");
  8252. this._workingContext = this._workingCanvas.getContext("2d");
  8253. };
  8254. Engine.prototype.resetTextureCache = function () {
  8255. for (var key in this._activeTexturesCache) {
  8256. this._activeTexturesCache[key] = null;
  8257. }
  8258. };
  8259. Engine.prototype.isDeterministicLockStep = function () {
  8260. return this._deterministicLockstep;
  8261. };
  8262. Engine.prototype.getLockstepMaxSteps = function () {
  8263. return this._lockstepMaxSteps;
  8264. };
  8265. Engine.prototype.getGlInfo = function () {
  8266. return {
  8267. vendor: this._glVendor,
  8268. renderer: this._glRenderer,
  8269. version: this._glVersion
  8270. };
  8271. };
  8272. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8273. if (useScreen === void 0) { useScreen = false; }
  8274. var viewport = camera.viewport;
  8275. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8276. };
  8277. Engine.prototype.getRenderWidth = function (useScreen) {
  8278. if (useScreen === void 0) { useScreen = false; }
  8279. if (!useScreen && this._currentRenderTarget) {
  8280. return this._currentRenderTarget.width;
  8281. }
  8282. return this._gl.drawingBufferWidth;
  8283. };
  8284. Engine.prototype.getRenderHeight = function (useScreen) {
  8285. if (useScreen === void 0) { useScreen = false; }
  8286. if (!useScreen && this._currentRenderTarget) {
  8287. return this._currentRenderTarget.height;
  8288. }
  8289. return this._gl.drawingBufferHeight;
  8290. };
  8291. Engine.prototype.getRenderingCanvas = function () {
  8292. return this._renderingCanvas;
  8293. };
  8294. Engine.prototype.getRenderingCanvasClientRect = function () {
  8295. return this._renderingCanvas.getBoundingClientRect();
  8296. };
  8297. Engine.prototype.setHardwareScalingLevel = function (level) {
  8298. this._hardwareScalingLevel = level;
  8299. this.resize();
  8300. };
  8301. Engine.prototype.getHardwareScalingLevel = function () {
  8302. return this._hardwareScalingLevel;
  8303. };
  8304. Engine.prototype.getLoadedTexturesCache = function () {
  8305. return this._internalTexturesCache;
  8306. };
  8307. Engine.prototype.getCaps = function () {
  8308. return this._caps;
  8309. };
  8310. Object.defineProperty(Engine.prototype, "drawCalls", {
  8311. /** The number of draw calls submitted last frame */
  8312. get: function () {
  8313. return this._drawCalls.current;
  8314. },
  8315. enumerable: true,
  8316. configurable: true
  8317. });
  8318. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8319. get: function () {
  8320. return this._drawCalls;
  8321. },
  8322. enumerable: true,
  8323. configurable: true
  8324. });
  8325. Engine.prototype.getDepthFunction = function () {
  8326. return this._depthCullingState.depthFunc;
  8327. };
  8328. Engine.prototype.setDepthFunction = function (depthFunc) {
  8329. this._depthCullingState.depthFunc = depthFunc;
  8330. };
  8331. Engine.prototype.setDepthFunctionToGreater = function () {
  8332. this._depthCullingState.depthFunc = this._gl.GREATER;
  8333. };
  8334. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8335. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8336. };
  8337. Engine.prototype.setDepthFunctionToLess = function () {
  8338. this._depthCullingState.depthFunc = this._gl.LESS;
  8339. };
  8340. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8341. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8342. };
  8343. Engine.prototype.getStencilBuffer = function () {
  8344. return this._stencilState.stencilTest;
  8345. };
  8346. Engine.prototype.setStencilBuffer = function (enable) {
  8347. this._stencilState.stencilTest = enable;
  8348. };
  8349. Engine.prototype.getStencilMask = function () {
  8350. return this._stencilState.stencilMask;
  8351. };
  8352. Engine.prototype.setStencilMask = function (mask) {
  8353. this._stencilState.stencilMask = mask;
  8354. };
  8355. Engine.prototype.getStencilFunction = function () {
  8356. return this._stencilState.stencilFunc;
  8357. };
  8358. Engine.prototype.getStencilFunctionReference = function () {
  8359. return this._stencilState.stencilFuncRef;
  8360. };
  8361. Engine.prototype.getStencilFunctionMask = function () {
  8362. return this._stencilState.stencilFuncMask;
  8363. };
  8364. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8365. this._stencilState.stencilFunc = stencilFunc;
  8366. };
  8367. Engine.prototype.setStencilFunctionReference = function (reference) {
  8368. this._stencilState.stencilFuncRef = reference;
  8369. };
  8370. Engine.prototype.setStencilFunctionMask = function (mask) {
  8371. this._stencilState.stencilFuncMask = mask;
  8372. };
  8373. Engine.prototype.getStencilOperationFail = function () {
  8374. return this._stencilState.stencilOpStencilFail;
  8375. };
  8376. Engine.prototype.getStencilOperationDepthFail = function () {
  8377. return this._stencilState.stencilOpDepthFail;
  8378. };
  8379. Engine.prototype.getStencilOperationPass = function () {
  8380. return this._stencilState.stencilOpStencilDepthPass;
  8381. };
  8382. Engine.prototype.setStencilOperationFail = function (operation) {
  8383. this._stencilState.stencilOpStencilFail = operation;
  8384. };
  8385. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8386. this._stencilState.stencilOpDepthFail = operation;
  8387. };
  8388. Engine.prototype.setStencilOperationPass = function (operation) {
  8389. this._stencilState.stencilOpStencilDepthPass = operation;
  8390. };
  8391. Engine.prototype.setDitheringState = function (value) {
  8392. if (value) {
  8393. this._gl.enable(this._gl.DITHER);
  8394. }
  8395. else {
  8396. this._gl.disable(this._gl.DITHER);
  8397. }
  8398. };
  8399. /**
  8400. * stop executing a render loop function and remove it from the execution array
  8401. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8402. */
  8403. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8404. if (!renderFunction) {
  8405. this._activeRenderLoops = [];
  8406. return;
  8407. }
  8408. var index = this._activeRenderLoops.indexOf(renderFunction);
  8409. if (index >= 0) {
  8410. this._activeRenderLoops.splice(index, 1);
  8411. }
  8412. };
  8413. Engine.prototype._renderLoop = function () {
  8414. if (!this._contextWasLost) {
  8415. var shouldRender = true;
  8416. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8417. shouldRender = false;
  8418. }
  8419. if (shouldRender) {
  8420. // Start new frame
  8421. this.beginFrame();
  8422. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8423. var renderFunction = this._activeRenderLoops[index];
  8424. renderFunction();
  8425. }
  8426. // Present
  8427. this.endFrame();
  8428. }
  8429. }
  8430. if (this._activeRenderLoops.length > 0) {
  8431. // Register new frame
  8432. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8433. }
  8434. else {
  8435. this._renderingQueueLaunched = false;
  8436. }
  8437. };
  8438. /**
  8439. * Register and execute a render loop. The engine can have more than one render function.
  8440. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8441. * @example
  8442. * engine.runRenderLoop(function () {
  8443. * scene.render()
  8444. * })
  8445. */
  8446. Engine.prototype.runRenderLoop = function (renderFunction) {
  8447. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8448. return;
  8449. }
  8450. this._activeRenderLoops.push(renderFunction);
  8451. if (!this._renderingQueueLaunched) {
  8452. this._renderingQueueLaunched = true;
  8453. this._bindedRenderFunction = this._renderLoop.bind(this);
  8454. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8455. }
  8456. };
  8457. /**
  8458. * Toggle full screen mode.
  8459. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8460. * @param {any} options - an options object to be sent to the requestFullscreen function
  8461. */
  8462. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8463. if (this.isFullscreen) {
  8464. BABYLON.Tools.ExitFullscreen();
  8465. }
  8466. else {
  8467. this._pointerLockRequested = requestPointerLock;
  8468. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8469. }
  8470. };
  8471. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8472. if (stencil === void 0) { stencil = false; }
  8473. this.applyStates();
  8474. var mode = 0;
  8475. if (backBuffer && color) {
  8476. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8477. mode |= this._gl.COLOR_BUFFER_BIT;
  8478. }
  8479. if (depth) {
  8480. this._gl.clearDepth(1.0);
  8481. mode |= this._gl.DEPTH_BUFFER_BIT;
  8482. }
  8483. if (stencil) {
  8484. this._gl.clearStencil(0);
  8485. mode |= this._gl.STENCIL_BUFFER_BIT;
  8486. }
  8487. this._gl.clear(mode);
  8488. };
  8489. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8490. var gl = this._gl;
  8491. // Save state
  8492. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8493. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8494. // Change state
  8495. gl.enable(gl.SCISSOR_TEST);
  8496. gl.scissor(x, y, width, height);
  8497. // Clear
  8498. this.clear(clearColor, true, true, true);
  8499. // Restore state
  8500. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8501. if (curScissor === true) {
  8502. gl.enable(gl.SCISSOR_TEST);
  8503. }
  8504. else {
  8505. gl.disable(gl.SCISSOR_TEST);
  8506. }
  8507. };
  8508. /**
  8509. * Set the WebGL's viewport
  8510. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8511. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8512. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8513. */
  8514. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8515. var width = requiredWidth || this.getRenderWidth();
  8516. var height = requiredHeight || this.getRenderHeight();
  8517. var x = viewport.x || 0;
  8518. var y = viewport.y || 0;
  8519. this._cachedViewport = viewport;
  8520. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8521. };
  8522. /**
  8523. * Directly set the WebGL Viewport
  8524. * The x, y, width & height are directly passed to the WebGL call
  8525. * @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.
  8526. */
  8527. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8528. var currentViewport = this._cachedViewport;
  8529. this._cachedViewport = null;
  8530. this._gl.viewport(x, y, width, height);
  8531. return currentViewport;
  8532. };
  8533. Engine.prototype.beginFrame = function () {
  8534. this._measureFps();
  8535. };
  8536. Engine.prototype.endFrame = function () {
  8537. //force a flush in case we are using a bad OS.
  8538. if (this._badOS) {
  8539. this.flushFramebuffer();
  8540. }
  8541. //submit frame to the vr device, if enabled
  8542. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8543. this._vrDisplayEnabled.submitFrame();
  8544. }
  8545. };
  8546. /**
  8547. * resize the view according to the canvas' size.
  8548. * @example
  8549. * window.addEventListener("resize", function () {
  8550. * engine.resize();
  8551. * });
  8552. */
  8553. Engine.prototype.resize = function () {
  8554. // We're not resizing the size of the canvas while in VR mode & presenting
  8555. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8556. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8557. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8558. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8559. }
  8560. };
  8561. /**
  8562. * force a specific size of the canvas
  8563. * @param {number} width - the new canvas' width
  8564. * @param {number} height - the new canvas' height
  8565. */
  8566. Engine.prototype.setSize = function (width, height) {
  8567. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8568. return;
  8569. }
  8570. this._renderingCanvas.width = width;
  8571. this._renderingCanvas.height = height;
  8572. for (var index = 0; index < this.scenes.length; index++) {
  8573. var scene = this.scenes[index];
  8574. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8575. var cam = scene.cameras[camIndex];
  8576. cam._currentRenderId = 0;
  8577. }
  8578. }
  8579. if (this.onResizeObservable.hasObservers) {
  8580. this.onResizeObservable.notifyObservers(this);
  8581. }
  8582. };
  8583. //WebVR functions
  8584. Engine.prototype.isVRDevicePresent = function (callback) {
  8585. this.getVRDevice(null, function (device) {
  8586. callback(device !== null);
  8587. });
  8588. };
  8589. Engine.prototype.getVRDevice = function (name, callback) {
  8590. if (!this.vrDisplaysPromise) {
  8591. callback(null);
  8592. return;
  8593. }
  8594. this.vrDisplaysPromise.then(function (devices) {
  8595. if (devices.length > 0) {
  8596. if (name) {
  8597. var found = devices.some(function (device) {
  8598. if (device.displayName === name) {
  8599. callback(device);
  8600. return true;
  8601. }
  8602. else {
  8603. return false;
  8604. }
  8605. });
  8606. if (!found) {
  8607. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8608. callback(devices[0]);
  8609. }
  8610. }
  8611. else {
  8612. //choose the first one
  8613. callback(devices[0]);
  8614. }
  8615. }
  8616. else {
  8617. BABYLON.Tools.Error("No WebVR devices found!");
  8618. callback(null);
  8619. }
  8620. });
  8621. };
  8622. Engine.prototype.initWebVR = function () {
  8623. if (!this.vrDisplaysPromise) {
  8624. this._getVRDisplays();
  8625. }
  8626. };
  8627. Engine.prototype.enableVR = function (vrDevice) {
  8628. this._vrDisplayEnabled = vrDevice;
  8629. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8630. };
  8631. Engine.prototype.disableVR = function () {
  8632. if (this._vrDisplayEnabled) {
  8633. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8634. }
  8635. };
  8636. Engine.prototype._getVRDisplays = function () {
  8637. var _this = this;
  8638. var getWebVRDevices = function (devices) {
  8639. _this._vrDisplays = devices.filter(function (device) {
  8640. return device instanceof VRDisplay;
  8641. });
  8642. return _this._vrDisplays;
  8643. };
  8644. if (navigator.getVRDisplays) {
  8645. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8646. }
  8647. };
  8648. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8649. if (this._currentRenderTarget) {
  8650. this.unBindFramebuffer(this._currentRenderTarget);
  8651. }
  8652. this._currentRenderTarget = texture;
  8653. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8654. var gl = this._gl;
  8655. if (texture.isCube) {
  8656. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8657. }
  8658. if (this._cachedViewport && !forceFullscreenViewport) {
  8659. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8660. }
  8661. else {
  8662. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8663. }
  8664. this.wipeCaches();
  8665. };
  8666. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8667. if (this._currentFramebuffer !== framebuffer) {
  8668. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8669. this._currentFramebuffer = framebuffer;
  8670. }
  8671. };
  8672. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8673. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8674. this._currentRenderTarget = null;
  8675. // If MSAA, we need to bitblt back to main texture
  8676. var gl = this._gl;
  8677. if (texture._MSAAFramebuffer) {
  8678. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8679. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8680. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8681. }
  8682. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8683. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8684. gl.generateMipmap(gl.TEXTURE_2D);
  8685. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8686. }
  8687. if (onBeforeUnbind) {
  8688. if (texture._MSAAFramebuffer) {
  8689. // Bind the correct framebuffer
  8690. this.bindUnboundFramebuffer(texture._framebuffer);
  8691. }
  8692. onBeforeUnbind();
  8693. }
  8694. this.bindUnboundFramebuffer(null);
  8695. };
  8696. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8697. if (texture.generateMipMaps) {
  8698. var gl = this._gl;
  8699. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8700. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8701. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8702. }
  8703. };
  8704. Engine.prototype.flushFramebuffer = function () {
  8705. this._gl.flush();
  8706. };
  8707. Engine.prototype.restoreDefaultFramebuffer = function () {
  8708. if (this._currentRenderTarget) {
  8709. this.unBindFramebuffer(this._currentRenderTarget);
  8710. }
  8711. else {
  8712. this.bindUnboundFramebuffer(null);
  8713. }
  8714. if (this._cachedViewport) {
  8715. this.setViewport(this._cachedViewport);
  8716. }
  8717. this.wipeCaches();
  8718. };
  8719. // UBOs
  8720. Engine.prototype.createUniformBuffer = function (elements) {
  8721. var ubo = this._gl.createBuffer();
  8722. this.bindUniformBuffer(ubo);
  8723. if (elements instanceof Float32Array) {
  8724. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8725. }
  8726. else {
  8727. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8728. }
  8729. this.bindUniformBuffer(null);
  8730. ubo.references = 1;
  8731. return ubo;
  8732. };
  8733. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8734. var ubo = this._gl.createBuffer();
  8735. this.bindUniformBuffer(ubo);
  8736. if (elements instanceof Float32Array) {
  8737. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8738. }
  8739. else {
  8740. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8741. }
  8742. this.bindUniformBuffer(null);
  8743. ubo.references = 1;
  8744. return ubo;
  8745. };
  8746. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8747. this.bindUniformBuffer(uniformBuffer);
  8748. if (offset === undefined) {
  8749. offset = 0;
  8750. }
  8751. if (count === undefined) {
  8752. if (elements instanceof Float32Array) {
  8753. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8754. }
  8755. else {
  8756. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8757. }
  8758. }
  8759. else {
  8760. if (elements instanceof Float32Array) {
  8761. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8762. }
  8763. else {
  8764. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8765. }
  8766. }
  8767. this.bindUniformBuffer(null);
  8768. };
  8769. // VBOs
  8770. Engine.prototype._resetVertexBufferBinding = function () {
  8771. this.bindArrayBuffer(null);
  8772. this._cachedVertexBuffers = null;
  8773. };
  8774. Engine.prototype.createVertexBuffer = function (vertices) {
  8775. var vbo = this._gl.createBuffer();
  8776. this.bindArrayBuffer(vbo);
  8777. if (vertices instanceof Float32Array) {
  8778. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8779. }
  8780. else {
  8781. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8782. }
  8783. this._resetVertexBufferBinding();
  8784. vbo.references = 1;
  8785. return vbo;
  8786. };
  8787. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8788. var vbo = this._gl.createBuffer();
  8789. this.bindArrayBuffer(vbo);
  8790. if (vertices instanceof Float32Array) {
  8791. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8792. }
  8793. else {
  8794. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8795. }
  8796. this._resetVertexBufferBinding();
  8797. vbo.references = 1;
  8798. return vbo;
  8799. };
  8800. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8801. this.bindArrayBuffer(vertexBuffer);
  8802. if (offset === undefined) {
  8803. offset = 0;
  8804. }
  8805. if (count === undefined) {
  8806. if (vertices instanceof Float32Array) {
  8807. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8808. }
  8809. else {
  8810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8811. }
  8812. }
  8813. else {
  8814. if (vertices instanceof Float32Array) {
  8815. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8816. }
  8817. else {
  8818. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8819. }
  8820. }
  8821. this._resetVertexBufferBinding();
  8822. };
  8823. Engine.prototype._resetIndexBufferBinding = function () {
  8824. this.bindIndexBuffer(null);
  8825. this._cachedIndexBuffer = null;
  8826. };
  8827. Engine.prototype.createIndexBuffer = function (indices) {
  8828. var vbo = this._gl.createBuffer();
  8829. this.bindIndexBuffer(vbo);
  8830. // Check for 32 bits indices
  8831. var arrayBuffer;
  8832. var need32Bits = false;
  8833. if (indices instanceof Uint16Array) {
  8834. arrayBuffer = indices;
  8835. }
  8836. else {
  8837. //check 32 bit support
  8838. if (this._caps.uintIndices) {
  8839. if (indices instanceof Uint32Array) {
  8840. arrayBuffer = indices;
  8841. need32Bits = true;
  8842. }
  8843. else {
  8844. //number[] or Int32Array, check if 32 bit is necessary
  8845. for (var index = 0; index < indices.length; index++) {
  8846. if (indices[index] > 65535) {
  8847. need32Bits = true;
  8848. break;
  8849. }
  8850. }
  8851. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8852. }
  8853. }
  8854. else {
  8855. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8856. arrayBuffer = new Uint16Array(indices);
  8857. }
  8858. }
  8859. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8860. this._resetIndexBufferBinding();
  8861. vbo.references = 1;
  8862. vbo.is32Bits = need32Bits;
  8863. return vbo;
  8864. };
  8865. Engine.prototype.bindArrayBuffer = function (buffer) {
  8866. if (!this._vaoRecordInProgress) {
  8867. this._unbindVertexArrayObject();
  8868. }
  8869. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8870. };
  8871. Engine.prototype.bindUniformBuffer = function (buffer) {
  8872. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8873. };
  8874. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8875. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8876. };
  8877. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8878. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8879. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8880. };
  8881. ;
  8882. Engine.prototype.bindIndexBuffer = function (buffer) {
  8883. if (!this._vaoRecordInProgress) {
  8884. this._unbindVertexArrayObject();
  8885. }
  8886. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8887. };
  8888. Engine.prototype.bindBuffer = function (buffer, target) {
  8889. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8890. this._gl.bindBuffer(target, buffer);
  8891. this._currentBoundBuffer[target] = buffer;
  8892. }
  8893. };
  8894. Engine.prototype.updateArrayBuffer = function (data) {
  8895. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8896. };
  8897. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8898. var pointer = this._currentBufferPointers[indx];
  8899. var changed = false;
  8900. if (!pointer.active) {
  8901. changed = true;
  8902. pointer.active = true;
  8903. pointer.index = indx;
  8904. pointer.size = size;
  8905. pointer.type = type;
  8906. pointer.normalized = normalized;
  8907. pointer.stride = stride;
  8908. pointer.offset = offset;
  8909. pointer.buffer = buffer;
  8910. }
  8911. else {
  8912. if (pointer.buffer !== buffer) {
  8913. pointer.buffer = buffer;
  8914. changed = true;
  8915. }
  8916. if (pointer.size !== size) {
  8917. pointer.size = size;
  8918. changed = true;
  8919. }
  8920. if (pointer.type !== type) {
  8921. pointer.type = type;
  8922. changed = true;
  8923. }
  8924. if (pointer.normalized !== normalized) {
  8925. pointer.normalized = normalized;
  8926. changed = true;
  8927. }
  8928. if (pointer.stride !== stride) {
  8929. pointer.stride = stride;
  8930. changed = true;
  8931. }
  8932. if (pointer.offset !== offset) {
  8933. pointer.offset = offset;
  8934. changed = true;
  8935. }
  8936. }
  8937. if (changed || this._vaoRecordInProgress) {
  8938. this.bindArrayBuffer(buffer);
  8939. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8940. }
  8941. };
  8942. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8943. if (indexBuffer == null) {
  8944. return;
  8945. }
  8946. if (this._cachedIndexBuffer !== indexBuffer) {
  8947. this._cachedIndexBuffer = indexBuffer;
  8948. this.bindIndexBuffer(indexBuffer);
  8949. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8950. }
  8951. };
  8952. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8953. var attributes = effect.getAttributesNames();
  8954. if (!this._vaoRecordInProgress) {
  8955. this._unbindVertexArrayObject();
  8956. }
  8957. this.unbindAllAttributes();
  8958. for (var index = 0; index < attributes.length; index++) {
  8959. var order = effect.getAttributeLocation(index);
  8960. if (order >= 0) {
  8961. var vertexBuffer = vertexBuffers[attributes[index]];
  8962. if (!vertexBuffer) {
  8963. continue;
  8964. }
  8965. this._gl.enableVertexAttribArray(order);
  8966. if (!this._vaoRecordInProgress) {
  8967. this._vertexAttribArraysEnabled[order] = true;
  8968. }
  8969. var buffer = vertexBuffer.getBuffer();
  8970. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8971. if (vertexBuffer.getIsInstanced()) {
  8972. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8973. if (!this._vaoRecordInProgress) {
  8974. this._currentInstanceLocations.push(order);
  8975. this._currentInstanceBuffers.push(buffer);
  8976. }
  8977. }
  8978. }
  8979. }
  8980. };
  8981. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8982. var vao = this._gl.createVertexArray();
  8983. this._vaoRecordInProgress = true;
  8984. this._gl.bindVertexArray(vao);
  8985. this._mustWipeVertexAttributes = true;
  8986. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8987. this.bindIndexBuffer(indexBuffer);
  8988. this._vaoRecordInProgress = false;
  8989. this._gl.bindVertexArray(null);
  8990. return vao;
  8991. };
  8992. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8993. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8994. this._cachedVertexArrayObject = vertexArrayObject;
  8995. this._gl.bindVertexArray(vertexArrayObject);
  8996. this._cachedVertexBuffers = null;
  8997. this._cachedIndexBuffer = null;
  8998. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8999. this._mustWipeVertexAttributes = true;
  9000. }
  9001. };
  9002. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9003. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9004. this._cachedVertexBuffers = vertexBuffer;
  9005. this._cachedEffectForVertexBuffers = effect;
  9006. var attributesCount = effect.getAttributesCount();
  9007. this._unbindVertexArrayObject();
  9008. this.unbindAllAttributes();
  9009. var offset = 0;
  9010. for (var index = 0; index < attributesCount; index++) {
  9011. if (index < vertexDeclaration.length) {
  9012. var order = effect.getAttributeLocation(index);
  9013. if (order >= 0) {
  9014. this._gl.enableVertexAttribArray(order);
  9015. this._vertexAttribArraysEnabled[order] = true;
  9016. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9017. }
  9018. offset += vertexDeclaration[index] * 4;
  9019. }
  9020. }
  9021. }
  9022. this._bindIndexBufferWithCache(indexBuffer);
  9023. };
  9024. Engine.prototype._unbindVertexArrayObject = function () {
  9025. if (!this._cachedVertexArrayObject) {
  9026. return;
  9027. }
  9028. this._cachedVertexArrayObject = null;
  9029. this._gl.bindVertexArray(null);
  9030. };
  9031. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9032. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9033. this._cachedVertexBuffers = vertexBuffers;
  9034. this._cachedEffectForVertexBuffers = effect;
  9035. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9036. }
  9037. this._bindIndexBufferWithCache(indexBuffer);
  9038. };
  9039. Engine.prototype.unbindInstanceAttributes = function () {
  9040. var boundBuffer;
  9041. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9042. var instancesBuffer = this._currentInstanceBuffers[i];
  9043. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9044. boundBuffer = instancesBuffer;
  9045. this.bindArrayBuffer(instancesBuffer);
  9046. }
  9047. var offsetLocation = this._currentInstanceLocations[i];
  9048. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9049. }
  9050. this._currentInstanceBuffers.length = 0;
  9051. this._currentInstanceLocations.length = 0;
  9052. };
  9053. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9054. this._gl.deleteVertexArray(vao);
  9055. };
  9056. Engine.prototype._releaseBuffer = function (buffer) {
  9057. buffer.references--;
  9058. if (buffer.references === 0) {
  9059. this._gl.deleteBuffer(buffer);
  9060. return true;
  9061. }
  9062. return false;
  9063. };
  9064. Engine.prototype.createInstancesBuffer = function (capacity) {
  9065. var buffer = this._gl.createBuffer();
  9066. buffer.capacity = capacity;
  9067. this.bindArrayBuffer(buffer);
  9068. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9069. return buffer;
  9070. };
  9071. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9072. this._gl.deleteBuffer(buffer);
  9073. };
  9074. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9075. this.bindArrayBuffer(instancesBuffer);
  9076. if (data) {
  9077. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9078. }
  9079. if (offsetLocations[0].index !== undefined) {
  9080. var stride = 0;
  9081. for (var i = 0; i < offsetLocations.length; i++) {
  9082. var ai = offsetLocations[i];
  9083. stride += ai.attributeSize * 4;
  9084. }
  9085. for (var i = 0; i < offsetLocations.length; i++) {
  9086. var ai = offsetLocations[i];
  9087. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9088. this._gl.enableVertexAttribArray(ai.index);
  9089. this._vertexAttribArraysEnabled[ai.index] = true;
  9090. }
  9091. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9092. this._gl.vertexAttribDivisor(ai.index, 1);
  9093. this._currentInstanceLocations.push(ai.index);
  9094. this._currentInstanceBuffers.push(instancesBuffer);
  9095. }
  9096. }
  9097. else {
  9098. for (var index = 0; index < 4; index++) {
  9099. var offsetLocation = offsetLocations[index];
  9100. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9101. this._gl.enableVertexAttribArray(offsetLocation);
  9102. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9103. }
  9104. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9105. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9106. this._currentInstanceLocations.push(offsetLocation);
  9107. this._currentInstanceBuffers.push(instancesBuffer);
  9108. }
  9109. }
  9110. };
  9111. Engine.prototype.applyStates = function () {
  9112. this._depthCullingState.apply(this._gl);
  9113. this._stencilState.apply(this._gl);
  9114. this._alphaState.apply(this._gl);
  9115. };
  9116. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9117. // Apply states
  9118. this.applyStates();
  9119. this._drawCalls.addCount(1, false);
  9120. // Render
  9121. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9122. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9123. if (instancesCount) {
  9124. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9125. return;
  9126. }
  9127. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9128. };
  9129. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9130. // Apply states
  9131. this.applyStates();
  9132. this._drawCalls.addCount(1, false);
  9133. if (instancesCount) {
  9134. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9135. return;
  9136. }
  9137. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9138. };
  9139. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9140. // Apply states
  9141. this.applyStates();
  9142. this._drawCalls.addCount(1, false);
  9143. if (instancesCount) {
  9144. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9145. return;
  9146. }
  9147. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9148. };
  9149. // Shaders
  9150. Engine.prototype._releaseEffect = function (effect) {
  9151. if (this._compiledEffects[effect._key]) {
  9152. delete this._compiledEffects[effect._key];
  9153. if (effect.getProgram()) {
  9154. this._gl.deleteProgram(effect.getProgram());
  9155. }
  9156. }
  9157. };
  9158. /**
  9159. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9160. * @param samplers An array of string used to represent textures
  9161. */
  9162. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9165. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9166. if (this._compiledEffects[name]) {
  9167. var compiledEffect = this._compiledEffects[name];
  9168. if (onCompiled && compiledEffect.isReady()) {
  9169. onCompiled(compiledEffect);
  9170. }
  9171. return compiledEffect;
  9172. }
  9173. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9174. effect._key = name;
  9175. this._compiledEffects[name] = effect;
  9176. return effect;
  9177. };
  9178. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9179. if (uniformsNames === void 0) { uniformsNames = []; }
  9180. if (samplers === void 0) { samplers = []; }
  9181. if (defines === void 0) { defines = ""; }
  9182. return this.createEffect({
  9183. vertex: "particles",
  9184. fragmentElement: fragmentName
  9185. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9186. };
  9187. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9188. context = context || this._gl;
  9189. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9190. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9191. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9192. var shaderProgram = context.createProgram();
  9193. context.attachShader(shaderProgram, vertexShader);
  9194. context.attachShader(shaderProgram, fragmentShader);
  9195. context.linkProgram(shaderProgram);
  9196. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9197. if (!linked) {
  9198. context.validateProgram(shaderProgram);
  9199. var error = context.getProgramInfoLog(shaderProgram);
  9200. if (error) {
  9201. throw new Error(error);
  9202. }
  9203. }
  9204. context.deleteShader(vertexShader);
  9205. context.deleteShader(fragmentShader);
  9206. return shaderProgram;
  9207. };
  9208. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9209. var results = [];
  9210. for (var index = 0; index < uniformsNames.length; index++) {
  9211. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9212. }
  9213. return results;
  9214. };
  9215. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9216. var results = [];
  9217. for (var index = 0; index < attributesNames.length; index++) {
  9218. try {
  9219. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9220. }
  9221. catch (e) {
  9222. results.push(-1);
  9223. }
  9224. }
  9225. return results;
  9226. };
  9227. Engine.prototype.enableEffect = function (effect) {
  9228. // Use program
  9229. this.setProgram(effect.getProgram());
  9230. this._currentEffect = effect;
  9231. if (effect.onBind) {
  9232. effect.onBind(effect);
  9233. }
  9234. effect.onBindObservable.notifyObservers(effect);
  9235. };
  9236. Engine.prototype.setIntArray = function (uniform, array) {
  9237. if (!uniform)
  9238. return;
  9239. this._gl.uniform1iv(uniform, array);
  9240. };
  9241. Engine.prototype.setIntArray2 = function (uniform, array) {
  9242. if (!uniform || array.length % 2 !== 0)
  9243. return;
  9244. this._gl.uniform2iv(uniform, array);
  9245. };
  9246. Engine.prototype.setIntArray3 = function (uniform, array) {
  9247. if (!uniform || array.length % 3 !== 0)
  9248. return;
  9249. this._gl.uniform3iv(uniform, array);
  9250. };
  9251. Engine.prototype.setIntArray4 = function (uniform, array) {
  9252. if (!uniform || array.length % 4 !== 0)
  9253. return;
  9254. this._gl.uniform4iv(uniform, array);
  9255. };
  9256. Engine.prototype.setFloatArray = function (uniform, array) {
  9257. if (!uniform)
  9258. return;
  9259. this._gl.uniform1fv(uniform, array);
  9260. };
  9261. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9262. if (!uniform || array.length % 2 !== 0)
  9263. return;
  9264. this._gl.uniform2fv(uniform, array);
  9265. };
  9266. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9267. if (!uniform || array.length % 3 !== 0)
  9268. return;
  9269. this._gl.uniform3fv(uniform, array);
  9270. };
  9271. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9272. if (!uniform || array.length % 4 !== 0)
  9273. return;
  9274. this._gl.uniform4fv(uniform, array);
  9275. };
  9276. Engine.prototype.setArray = function (uniform, array) {
  9277. if (!uniform)
  9278. return;
  9279. this._gl.uniform1fv(uniform, array);
  9280. };
  9281. Engine.prototype.setArray2 = function (uniform, array) {
  9282. if (!uniform || array.length % 2 !== 0)
  9283. return;
  9284. this._gl.uniform2fv(uniform, array);
  9285. };
  9286. Engine.prototype.setArray3 = function (uniform, array) {
  9287. if (!uniform || array.length % 3 !== 0)
  9288. return;
  9289. this._gl.uniform3fv(uniform, array);
  9290. };
  9291. Engine.prototype.setArray4 = function (uniform, array) {
  9292. if (!uniform || array.length % 4 !== 0)
  9293. return;
  9294. this._gl.uniform4fv(uniform, array);
  9295. };
  9296. Engine.prototype.setMatrices = function (uniform, matrices) {
  9297. if (!uniform)
  9298. return;
  9299. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9300. };
  9301. Engine.prototype.setMatrix = function (uniform, matrix) {
  9302. if (!uniform)
  9303. return;
  9304. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9305. };
  9306. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9307. if (!uniform)
  9308. return;
  9309. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9310. };
  9311. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9312. if (!uniform)
  9313. return;
  9314. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9315. };
  9316. Engine.prototype.setFloat = function (uniform, value) {
  9317. if (!uniform)
  9318. return;
  9319. this._gl.uniform1f(uniform, value);
  9320. };
  9321. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9322. if (!uniform)
  9323. return;
  9324. this._gl.uniform2f(uniform, x, y);
  9325. };
  9326. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9327. if (!uniform)
  9328. return;
  9329. this._gl.uniform3f(uniform, x, y, z);
  9330. };
  9331. Engine.prototype.setBool = function (uniform, bool) {
  9332. if (!uniform)
  9333. return;
  9334. this._gl.uniform1i(uniform, bool);
  9335. };
  9336. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9337. if (!uniform)
  9338. return;
  9339. this._gl.uniform4f(uniform, x, y, z, w);
  9340. };
  9341. Engine.prototype.setColor3 = function (uniform, color3) {
  9342. if (!uniform)
  9343. return;
  9344. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9345. };
  9346. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9347. if (!uniform)
  9348. return;
  9349. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9350. };
  9351. // States
  9352. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9353. if (zOffset === void 0) { zOffset = 0; }
  9354. if (reverseSide === void 0) { reverseSide = false; }
  9355. // Culling
  9356. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9357. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9358. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9359. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9360. if (culling) {
  9361. this._depthCullingState.cullFace = cullFace;
  9362. this._depthCullingState.cull = true;
  9363. }
  9364. else {
  9365. this._depthCullingState.cull = false;
  9366. }
  9367. }
  9368. // Z offset
  9369. this.setZOffset(zOffset);
  9370. };
  9371. Engine.prototype.setZOffset = function (value) {
  9372. this._depthCullingState.zOffset = value;
  9373. };
  9374. Engine.prototype.getZOffset = function () {
  9375. return this._depthCullingState.zOffset;
  9376. };
  9377. Engine.prototype.setDepthBuffer = function (enable) {
  9378. this._depthCullingState.depthTest = enable;
  9379. };
  9380. Engine.prototype.getDepthWrite = function () {
  9381. return this._depthCullingState.depthMask;
  9382. };
  9383. Engine.prototype.setDepthWrite = function (enable) {
  9384. this._depthCullingState.depthMask = enable;
  9385. };
  9386. Engine.prototype.setColorWrite = function (enable) {
  9387. this._gl.colorMask(enable, enable, enable, enable);
  9388. };
  9389. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9390. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9391. };
  9392. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9393. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9394. if (this._alphaMode === mode) {
  9395. return;
  9396. }
  9397. switch (mode) {
  9398. case Engine.ALPHA_DISABLE:
  9399. this._alphaState.alphaBlend = false;
  9400. break;
  9401. case Engine.ALPHA_PREMULTIPLIED:
  9402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9403. this._alphaState.alphaBlend = true;
  9404. break;
  9405. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9407. this._alphaState.alphaBlend = true;
  9408. break;
  9409. case Engine.ALPHA_COMBINE:
  9410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9411. this._alphaState.alphaBlend = true;
  9412. break;
  9413. case Engine.ALPHA_ONEONE:
  9414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9415. this._alphaState.alphaBlend = true;
  9416. break;
  9417. case Engine.ALPHA_ADD:
  9418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9419. this._alphaState.alphaBlend = true;
  9420. break;
  9421. case Engine.ALPHA_SUBTRACT:
  9422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9423. this._alphaState.alphaBlend = true;
  9424. break;
  9425. case Engine.ALPHA_MULTIPLY:
  9426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9427. this._alphaState.alphaBlend = true;
  9428. break;
  9429. case Engine.ALPHA_MAXIMIZED:
  9430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9431. this._alphaState.alphaBlend = true;
  9432. break;
  9433. case Engine.ALPHA_INTERPOLATE:
  9434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9435. this._alphaState.alphaBlend = true;
  9436. break;
  9437. case Engine.ALPHA_SCREENMODE:
  9438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9439. this._alphaState.alphaBlend = true;
  9440. break;
  9441. }
  9442. if (!noDepthWriteChange) {
  9443. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9444. }
  9445. this._alphaMode = mode;
  9446. };
  9447. Engine.prototype.getAlphaMode = function () {
  9448. return this._alphaMode;
  9449. };
  9450. Engine.prototype.setAlphaTesting = function (enable) {
  9451. this._alphaTest = enable;
  9452. };
  9453. Engine.prototype.getAlphaTesting = function () {
  9454. return !!this._alphaTest;
  9455. };
  9456. // Textures
  9457. Engine.prototype.wipeCaches = function (bruteForce) {
  9458. if (this.preventCacheWipeBetweenFrames) {
  9459. return;
  9460. }
  9461. this.resetTextureCache();
  9462. this._currentEffect = null;
  9463. // 6/8/2017: deltakosh: Should not be required anymore.
  9464. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9465. if (bruteForce) {
  9466. this._currentProgram = null;
  9467. this._stencilState.reset();
  9468. this._depthCullingState.reset();
  9469. this.setDepthFunctionToLessOrEqual();
  9470. this._alphaState.reset();
  9471. }
  9472. this._cachedVertexBuffers = null;
  9473. this._cachedIndexBuffer = null;
  9474. this._cachedEffectForVertexBuffers = null;
  9475. this._unbindVertexArrayObject();
  9476. this.bindIndexBuffer(null);
  9477. this.bindArrayBuffer(null);
  9478. };
  9479. /**
  9480. * Set the compressed texture format to use, based on the formats you have, and the formats
  9481. * supported by the hardware / browser.
  9482. *
  9483. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9484. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9485. * to API arguments needed to compressed textures. This puts the burden on the container
  9486. * generator to house the arcane code for determining these for current & future formats.
  9487. *
  9488. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9489. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9490. *
  9491. * Note: The result of this call is not taken into account when a texture is base64.
  9492. *
  9493. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9494. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9495. *
  9496. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9497. * @returns The extension selected.
  9498. */
  9499. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9500. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9501. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9502. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9503. return this._textureFormatInUse = this._texturesSupported[i];
  9504. }
  9505. }
  9506. }
  9507. // actively set format to nothing, to allow this to be called more than once
  9508. // and possibly fail the 2nd time
  9509. return this._textureFormatInUse = null;
  9510. };
  9511. Engine.prototype._createTexture = function () {
  9512. return this._gl.createTexture();
  9513. };
  9514. /**
  9515. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9516. * @param {string} urlArg- This contains one of the following:
  9517. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9518. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9519. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9520. *
  9521. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9522. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9523. * @param {Scene} scene- Needed for loading to the correct scene.
  9524. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9525. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9526. * @param {callback} onError- Optional callback to be called upon failure.
  9527. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9528. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9529. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9530. *
  9531. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9532. */
  9533. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9534. var _this = this;
  9535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9536. if (onLoad === void 0) { onLoad = null; }
  9537. if (onError === void 0) { onError = null; }
  9538. if (buffer === void 0) { buffer = null; }
  9539. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9540. var fromData = url.substr(0, 5) === "data:";
  9541. var fromBlob = url.substr(0, 5) === "blob:";
  9542. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9543. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9544. // establish the file extension, if possible
  9545. var lastDot = url.lastIndexOf('.');
  9546. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9547. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9548. var isTGA = (extension === ".tga");
  9549. // determine if a ktx file should be substituted
  9550. var isKTX = false;
  9551. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9552. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9553. isKTX = true;
  9554. }
  9555. if (scene) {
  9556. scene._addPendingData(texture);
  9557. }
  9558. texture.url = url;
  9559. texture.generateMipMaps = !noMipmap;
  9560. texture.samplingMode = samplingMode;
  9561. texture.invertY = invertY;
  9562. if (!this._doNotHandleContextLost) {
  9563. // Keep a link to the buffer only if we plan to handle context lost
  9564. texture._buffer = buffer;
  9565. }
  9566. if (onLoad) {
  9567. texture.onLoadedObservable.add(onLoad);
  9568. }
  9569. if (!fallBack)
  9570. this._internalTexturesCache.push(texture);
  9571. var onerror = function () {
  9572. if (scene) {
  9573. scene._removePendingData(texture);
  9574. }
  9575. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9576. if (isKTX) {
  9577. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9578. }
  9579. else if (onError) {
  9580. onError();
  9581. }
  9582. };
  9583. var callback;
  9584. // processing for non-image formats
  9585. if (isKTX || isTGA || isDDS) {
  9586. if (isKTX) {
  9587. callback = function (data) {
  9588. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9589. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9590. ktx.uploadLevels(_this._gl, !noMipmap);
  9591. return false;
  9592. }, samplingMode);
  9593. };
  9594. }
  9595. else if (isTGA) {
  9596. callback = function (arrayBuffer) {
  9597. var data = new Uint8Array(arrayBuffer);
  9598. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9599. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9600. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9601. return false;
  9602. }, samplingMode);
  9603. };
  9604. }
  9605. else if (isDDS) {
  9606. callback = function (data) {
  9607. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9608. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9609. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9610. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9611. return false;
  9612. }, samplingMode);
  9613. };
  9614. }
  9615. if (!buffer) {
  9616. BABYLON.Tools.LoadFile(url, function (data) {
  9617. callback(data);
  9618. }, null, scene ? scene.database : null, true, onerror);
  9619. }
  9620. else {
  9621. callback(buffer);
  9622. }
  9623. // image format processing
  9624. }
  9625. else {
  9626. var onload = function (img) {
  9627. if (fromBlob && !_this._doNotHandleContextLost) {
  9628. // We need to store the image if we need to rebuild the texture
  9629. // in case of a webgl context lost
  9630. texture._buffer = img;
  9631. }
  9632. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9633. var gl = _this._gl;
  9634. var isPot = (img.width === potWidth && img.height === potHeight);
  9635. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9636. if (isPot) {
  9637. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9638. return false;
  9639. }
  9640. // Using shaders to rescale because canvas.drawImage is lossy
  9641. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9642. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9643. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9648. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9649. _this._releaseTexture(source);
  9650. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9651. continuationCallback();
  9652. });
  9653. return true;
  9654. }, samplingMode);
  9655. };
  9656. if (!fromData || isBase64)
  9657. if (buffer instanceof HTMLImageElement) {
  9658. onload(buffer);
  9659. }
  9660. else {
  9661. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9662. }
  9663. else if (buffer instanceof Array || typeof buffer === "string")
  9664. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9665. else
  9666. onload(buffer);
  9667. }
  9668. return texture;
  9669. };
  9670. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9671. var _this = this;
  9672. var rtt = this.createRenderTargetTexture({
  9673. width: destination.width,
  9674. height: destination.height,
  9675. }, {
  9676. generateMipMaps: false,
  9677. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9678. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9679. generateDepthBuffer: false,
  9680. generateStencilBuffer: false
  9681. });
  9682. if (!this._rescalePostProcess) {
  9683. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9684. }
  9685. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9686. _this._rescalePostProcess.onApply = function (effect) {
  9687. effect._bindTexture("textureSampler", source);
  9688. };
  9689. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9690. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9691. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9692. _this.unBindFramebuffer(rtt);
  9693. _this._releaseTexture(rtt);
  9694. if (onComplete) {
  9695. onComplete();
  9696. }
  9697. });
  9698. };
  9699. Engine.prototype._getInternalFormat = function (format) {
  9700. var internalFormat = this._gl.RGBA;
  9701. switch (format) {
  9702. case Engine.TEXTUREFORMAT_ALPHA:
  9703. internalFormat = this._gl.ALPHA;
  9704. break;
  9705. case Engine.TEXTUREFORMAT_LUMINANCE:
  9706. internalFormat = this._gl.LUMINANCE;
  9707. break;
  9708. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9709. internalFormat = this._gl.LUMINANCE_ALPHA;
  9710. break;
  9711. case Engine.TEXTUREFORMAT_RGB:
  9712. internalFormat = this._gl.RGB;
  9713. break;
  9714. case Engine.TEXTUREFORMAT_RGBA:
  9715. internalFormat = this._gl.RGBA;
  9716. break;
  9717. }
  9718. return internalFormat;
  9719. };
  9720. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9721. if (compression === void 0) { compression = null; }
  9722. var internalFormat = this._getInternalFormat(format);
  9723. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9724. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9725. if (!this._doNotHandleContextLost) {
  9726. texture._bufferView = data;
  9727. texture.format = format;
  9728. texture.invertY = invertY;
  9729. texture._compression = compression;
  9730. }
  9731. if (texture.width % 4 !== 0) {
  9732. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9733. }
  9734. if (compression) {
  9735. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9736. }
  9737. else {
  9738. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9739. }
  9740. if (texture.generateMipMaps) {
  9741. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9742. }
  9743. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9744. this.resetTextureCache();
  9745. texture.isReady = true;
  9746. };
  9747. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9748. if (compression === void 0) { compression = null; }
  9749. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9750. texture.baseWidth = width;
  9751. texture.baseHeight = height;
  9752. texture.width = width;
  9753. texture.height = height;
  9754. texture.format = format;
  9755. texture.generateMipMaps = generateMipMaps;
  9756. texture.samplingMode = samplingMode;
  9757. texture.invertY = invertY;
  9758. texture._compression = compression;
  9759. if (!this._doNotHandleContextLost) {
  9760. texture._bufferView = data;
  9761. }
  9762. this.updateRawTexture(texture, data, format, invertY, compression);
  9763. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9764. // Filters
  9765. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9766. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9767. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9768. if (generateMipMaps) {
  9769. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9770. }
  9771. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9772. this._internalTexturesCache.push(texture);
  9773. return texture;
  9774. };
  9775. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9776. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9777. texture.baseWidth = width;
  9778. texture.baseHeight = height;
  9779. if (generateMipMaps) {
  9780. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9781. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9782. }
  9783. this.resetTextureCache();
  9784. texture.width = width;
  9785. texture.height = height;
  9786. texture.isReady = false;
  9787. texture.generateMipMaps = generateMipMaps;
  9788. texture.samplingMode = samplingMode;
  9789. this.updateTextureSamplingMode(samplingMode, texture);
  9790. this._internalTexturesCache.push(texture);
  9791. return texture;
  9792. };
  9793. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9794. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9795. if (texture.isCube) {
  9796. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9797. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9798. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9799. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9800. }
  9801. else {
  9802. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9803. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9804. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9805. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9806. }
  9807. texture.samplingMode = samplingMode;
  9808. };
  9809. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9810. if (premulAlpha === void 0) { premulAlpha = false; }
  9811. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9812. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9813. if (premulAlpha) {
  9814. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9815. }
  9816. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9817. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9818. if (texture.generateMipMaps) {
  9819. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9820. }
  9821. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9822. if (premulAlpha) {
  9823. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9824. }
  9825. this.resetTextureCache();
  9826. texture.isReady = true;
  9827. };
  9828. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9829. if (texture._isDisabled) {
  9830. return;
  9831. }
  9832. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9833. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9834. try {
  9835. // Testing video texture support
  9836. if (this._videoTextureSupported === undefined) {
  9837. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9838. if (this._gl.getError() !== 0) {
  9839. this._videoTextureSupported = false;
  9840. }
  9841. else {
  9842. this._videoTextureSupported = true;
  9843. }
  9844. }
  9845. // Copy video through the current working canvas if video texture is not supported
  9846. if (!this._videoTextureSupported) {
  9847. if (!texture._workingCanvas) {
  9848. texture._workingCanvas = document.createElement("canvas");
  9849. texture._workingContext = texture._workingCanvas.getContext("2d");
  9850. texture._workingCanvas.width = texture.width;
  9851. texture._workingCanvas.height = texture.height;
  9852. }
  9853. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  9854. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9855. }
  9856. else {
  9857. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9858. }
  9859. if (texture.generateMipMaps) {
  9860. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9861. }
  9862. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9863. this.resetTextureCache();
  9864. texture.isReady = true;
  9865. }
  9866. catch (ex) {
  9867. // Something unexpected
  9868. // Let's disable the texture
  9869. texture._isDisabled = true;
  9870. }
  9871. };
  9872. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9873. var fullOptions = new RenderTargetCreationOptions();
  9874. if (options !== undefined && typeof options === "object") {
  9875. fullOptions.generateMipMaps = options.generateMipMaps;
  9876. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9877. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  9878. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  9879. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  9880. }
  9881. else {
  9882. fullOptions.generateMipMaps = options;
  9883. fullOptions.generateDepthBuffer = true;
  9884. fullOptions.generateStencilBuffer = false;
  9885. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9886. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9887. }
  9888. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9889. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9890. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9891. }
  9892. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9893. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9894. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9895. }
  9896. var gl = this._gl;
  9897. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  9898. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9899. var width = size.width || size;
  9900. var height = size.height || size;
  9901. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  9902. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9903. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9904. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9905. }
  9906. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9907. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9909. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9910. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  9911. // Create the framebuffer
  9912. var framebuffer = gl.createFramebuffer();
  9913. this.bindUnboundFramebuffer(framebuffer);
  9914. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9915. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  9916. if (fullOptions.generateMipMaps) {
  9917. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9918. }
  9919. // Unbind
  9920. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9921. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9922. this.bindUnboundFramebuffer(null);
  9923. texture._framebuffer = framebuffer;
  9924. texture.baseWidth = width;
  9925. texture.baseHeight = height;
  9926. texture.width = width;
  9927. texture.height = height;
  9928. texture.isReady = true;
  9929. texture.samples = 1;
  9930. texture.generateMipMaps = fullOptions.generateMipMaps;
  9931. texture.samplingMode = fullOptions.samplingMode;
  9932. texture.type = fullOptions.type;
  9933. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  9934. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  9935. this.resetTextureCache();
  9936. this._internalTexturesCache.push(texture);
  9937. return texture;
  9938. };
  9939. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9940. var generateMipMaps = false;
  9941. var generateDepthBuffer = true;
  9942. var generateStencilBuffer = false;
  9943. var generateDepthTexture = false;
  9944. var textureCount = 1;
  9945. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9946. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9947. var types = [], samplingModes = [];
  9948. if (options !== undefined) {
  9949. generateMipMaps = options.generateMipMaps;
  9950. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9951. generateStencilBuffer = options.generateStencilBuffer;
  9952. generateDepthTexture = options.generateDepthTexture;
  9953. textureCount = options.textureCount || 1;
  9954. if (options.types) {
  9955. types = options.types;
  9956. }
  9957. if (options.samplingModes) {
  9958. samplingModes = options.samplingModes;
  9959. }
  9960. }
  9961. var gl = this._gl;
  9962. // Create the framebuffer
  9963. var framebuffer = gl.createFramebuffer();
  9964. this.bindUnboundFramebuffer(framebuffer);
  9965. var width = size.width || size;
  9966. var height = size.height || size;
  9967. var textures = [];
  9968. var attachments = [];
  9969. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9970. for (var i = 0; i < textureCount; i++) {
  9971. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9972. var type = types[i] || defaultType;
  9973. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9974. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9975. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9976. }
  9977. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9978. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9979. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9980. }
  9981. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9982. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9983. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9984. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9985. }
  9986. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9987. var attachment = gl["COLOR_ATTACHMENT" + i];
  9988. textures.push(texture);
  9989. attachments.push(attachment);
  9990. gl.activeTexture(gl["TEXTURE" + i]);
  9991. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  9992. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9993. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9994. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9996. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9997. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9998. if (generateMipMaps) {
  9999. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10000. }
  10001. // Unbind
  10002. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10003. texture._framebuffer = framebuffer;
  10004. texture._depthStencilBuffer = depthStencilBuffer;
  10005. texture.baseWidth = width;
  10006. texture.baseHeight = height;
  10007. texture.width = width;
  10008. texture.height = height;
  10009. texture.isReady = true;
  10010. texture.samples = 1;
  10011. texture.generateMipMaps = generateMipMaps;
  10012. texture.samplingMode = samplingMode;
  10013. texture.type = type;
  10014. texture._generateDepthBuffer = generateDepthBuffer;
  10015. texture._generateStencilBuffer = generateStencilBuffer;
  10016. this._internalTexturesCache.push(texture);
  10017. }
  10018. if (generateDepthTexture) {
  10019. // Depth texture
  10020. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10021. gl.activeTexture(gl.TEXTURE0);
  10022. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10023. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10024. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10025. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10026. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10027. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10028. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10029. depthTexture._framebuffer = framebuffer;
  10030. depthTexture.baseWidth = width;
  10031. depthTexture.baseHeight = height;
  10032. depthTexture.width = width;
  10033. depthTexture.height = height;
  10034. depthTexture.isReady = true;
  10035. depthTexture.samples = 1;
  10036. depthTexture.generateMipMaps = generateMipMaps;
  10037. depthTexture.samplingMode = gl.NEAREST;
  10038. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10039. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10040. textures.push(depthTexture);
  10041. this._internalTexturesCache.push(depthTexture);
  10042. }
  10043. gl.drawBuffers(attachments);
  10044. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10045. this.bindUnboundFramebuffer(null);
  10046. this.resetTextureCache();
  10047. return textures;
  10048. };
  10049. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10050. if (samples === void 0) { samples = 1; }
  10051. var depthStencilBuffer = null;
  10052. var gl = this._gl;
  10053. // Create the depth/stencil buffer
  10054. if (generateStencilBuffer) {
  10055. depthStencilBuffer = gl.createRenderbuffer();
  10056. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10057. if (samples > 1) {
  10058. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10059. }
  10060. else {
  10061. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10062. }
  10063. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10064. }
  10065. else if (generateDepthBuffer) {
  10066. depthStencilBuffer = gl.createRenderbuffer();
  10067. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10068. if (samples > 1) {
  10069. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10070. }
  10071. else {
  10072. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10073. }
  10074. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10075. }
  10076. return depthStencilBuffer;
  10077. };
  10078. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10079. if (this.webGLVersion < 2) {
  10080. return 1;
  10081. }
  10082. if (texture.samples === samples) {
  10083. return samples;
  10084. }
  10085. var gl = this._gl;
  10086. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10087. // Dispose previous render buffers
  10088. if (texture._depthStencilBuffer) {
  10089. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10090. }
  10091. if (texture._MSAAFramebuffer) {
  10092. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10093. }
  10094. if (texture._MSAARenderBuffer) {
  10095. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10096. }
  10097. if (samples > 1) {
  10098. texture._MSAAFramebuffer = gl.createFramebuffer();
  10099. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10100. var colorRenderbuffer = gl.createRenderbuffer();
  10101. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10102. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10103. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10104. texture._MSAARenderBuffer = colorRenderbuffer;
  10105. }
  10106. else {
  10107. this.bindUnboundFramebuffer(texture._framebuffer);
  10108. }
  10109. texture.samples = samples;
  10110. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10111. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10112. this.bindUnboundFramebuffer(null);
  10113. return samples;
  10114. };
  10115. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10116. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10117. };
  10118. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10119. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10120. };
  10121. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10122. var gl = this._gl;
  10123. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10124. var generateMipMaps = true;
  10125. var generateDepthBuffer = true;
  10126. var generateStencilBuffer = false;
  10127. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10128. if (options !== undefined) {
  10129. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10130. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10131. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10132. if (options.samplingMode !== undefined) {
  10133. samplingMode = options.samplingMode;
  10134. }
  10135. }
  10136. texture.isCube = true;
  10137. texture.generateMipMaps = generateMipMaps;
  10138. texture.samples = 1;
  10139. texture.samplingMode = samplingMode;
  10140. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10141. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10142. for (var face = 0; face < 6; face++) {
  10143. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10144. }
  10145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10146. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10147. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10149. // Create the framebuffer
  10150. var framebuffer = gl.createFramebuffer();
  10151. this.bindUnboundFramebuffer(framebuffer);
  10152. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10153. // Mipmaps
  10154. if (texture.generateMipMaps) {
  10155. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10156. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10157. }
  10158. // Unbind
  10159. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10160. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10161. this.bindUnboundFramebuffer(null);
  10162. texture._framebuffer = framebuffer;
  10163. texture.width = size;
  10164. texture.height = size;
  10165. texture.isReady = true;
  10166. this.resetTextureCache();
  10167. this._internalTexturesCache.push(texture);
  10168. return texture;
  10169. };
  10170. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10171. var _this = this;
  10172. if (onError === void 0) { onError = null; }
  10173. if (forcedExtension === void 0) { forcedExtension = null; }
  10174. var callback = function (loadData) {
  10175. if (!loadData) {
  10176. if (onLoad) {
  10177. onLoad(null);
  10178. }
  10179. return;
  10180. }
  10181. var texture = loadData.texture;
  10182. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10183. texture._lodGenerationScale = scale;
  10184. texture._lodGenerationOffset = offset;
  10185. if (_this._caps.textureLOD) {
  10186. // Do not add extra process if texture lod is supported.
  10187. if (onLoad) {
  10188. onLoad(texture);
  10189. }
  10190. return;
  10191. }
  10192. var mipSlices = 3;
  10193. var gl = _this._gl;
  10194. var width = loadData.width;
  10195. if (!width) {
  10196. return;
  10197. }
  10198. var textures = [];
  10199. for (var i = 0; i < mipSlices; i++) {
  10200. //compute LOD from even spacing in smoothness (matching shader calculation)
  10201. var smoothness = i / (mipSlices - 1);
  10202. var roughness = 1 - smoothness;
  10203. var minLODIndex = offset; // roughness = 0
  10204. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10205. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10206. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10207. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10208. glTextureFromLod.isCube = true;
  10209. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10214. if (loadData.isDDS) {
  10215. var info = loadData.info;
  10216. var data = loadData.data;
  10217. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10218. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10219. }
  10220. else {
  10221. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10222. }
  10223. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10224. // Wrap in a base texture for easy binding.
  10225. var lodTexture = new BABYLON.BaseTexture(scene);
  10226. lodTexture.isCube = true;
  10227. lodTexture._texture = glTextureFromLod;
  10228. glTextureFromLod.isReady = true;
  10229. textures.push(lodTexture);
  10230. }
  10231. texture._lodTextureHigh = textures[2];
  10232. texture._lodTextureMid = textures[1];
  10233. texture._lodTextureLow = textures[0];
  10234. if (onLoad) {
  10235. onLoad(texture);
  10236. }
  10237. };
  10238. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10239. };
  10240. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10241. var _this = this;
  10242. if (onLoad === void 0) { onLoad = null; }
  10243. if (onError === void 0) { onError = null; }
  10244. if (forcedExtension === void 0) { forcedExtension = null; }
  10245. var gl = this._gl;
  10246. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10247. texture.isCube = true;
  10248. texture.url = rootUrl;
  10249. texture.generateMipMaps = !noMipmap;
  10250. if (!this._doNotHandleContextLost) {
  10251. texture._extension = forcedExtension;
  10252. texture._files = files;
  10253. }
  10254. var isKTX = false;
  10255. var isDDS = false;
  10256. var lastDot = rootUrl.lastIndexOf('.');
  10257. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10258. if (this._textureFormatInUse) {
  10259. extension = this._textureFormatInUse;
  10260. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10261. isKTX = true;
  10262. }
  10263. else {
  10264. isDDS = (extension === ".dds");
  10265. }
  10266. if (isKTX) {
  10267. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10268. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10269. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10270. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10271. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10272. ktx.uploadLevels(_this._gl, !noMipmap);
  10273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10274. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10275. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10276. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10277. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10278. _this.resetTextureCache();
  10279. texture.width = ktx.pixelWidth;
  10280. texture.height = ktx.pixelHeight;
  10281. texture.isReady = true;
  10282. }, null, null, true, onError);
  10283. }
  10284. else if (isDDS) {
  10285. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10286. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10287. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10288. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10289. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10290. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10291. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10292. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10293. }
  10294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10298. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10299. _this.resetTextureCache();
  10300. texture.width = info.width;
  10301. texture.height = info.height;
  10302. texture.isReady = true;
  10303. texture.type = info.textureType;
  10304. if (onLoad) {
  10305. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10306. }
  10307. }, null, null, true, onError);
  10308. }
  10309. else {
  10310. cascadeLoad(rootUrl, scene, function (imgs) {
  10311. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10312. var height = width;
  10313. _this._prepareWorkingCanvas();
  10314. _this._workingCanvas.width = width;
  10315. _this._workingCanvas.height = height;
  10316. var faces = [
  10317. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10318. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10319. ];
  10320. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10321. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10322. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10323. for (var index = 0; index < faces.length; index++) {
  10324. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10325. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10326. }
  10327. if (!noMipmap) {
  10328. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10329. }
  10330. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10331. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10332. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10334. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10335. _this.resetTextureCache();
  10336. texture.width = width;
  10337. texture.height = height;
  10338. texture.isReady = true;
  10339. texture.format = format;
  10340. texture.onLoadedObservable.notifyObservers(texture);
  10341. texture.onLoadedObservable.clear();
  10342. if (onLoad) {
  10343. onLoad();
  10344. }
  10345. }, files, onError);
  10346. }
  10347. this._internalTexturesCache.push(texture);
  10348. return texture;
  10349. };
  10350. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10351. if (compression === void 0) { compression = null; }
  10352. if (level === void 0) { level = 0; }
  10353. texture._bufferViewArray = data;
  10354. texture.format = format;
  10355. texture.type = type;
  10356. texture.invertY = invertY;
  10357. texture._compression = compression;
  10358. var gl = this._gl;
  10359. var textureType = this._getWebGLTextureType(type);
  10360. var internalFormat = this._getInternalFormat(format);
  10361. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10362. var needConversion = false;
  10363. if (internalFormat === gl.RGB) {
  10364. internalFormat = gl.RGBA;
  10365. needConversion = true;
  10366. }
  10367. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10368. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10369. if (texture.width % 4 !== 0) {
  10370. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10371. }
  10372. // Data are known to be in +X +Y +Z -X -Y -Z
  10373. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10374. var faceData = data[faceIndex];
  10375. if (compression) {
  10376. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10377. }
  10378. else {
  10379. if (needConversion) {
  10380. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10381. }
  10382. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10383. }
  10384. }
  10385. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10386. if (isPot && texture.generateMipMaps && level === 0) {
  10387. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10388. }
  10389. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10390. this.resetTextureCache();
  10391. texture.isReady = true;
  10392. };
  10393. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10394. if (compression === void 0) { compression = null; }
  10395. var gl = this._gl;
  10396. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10397. texture.isCube = true;
  10398. texture.generateMipMaps = generateMipMaps;
  10399. texture.format = format;
  10400. texture.type = type;
  10401. if (!this._doNotHandleContextLost) {
  10402. texture._bufferViewArray = data;
  10403. }
  10404. var textureType = this._getWebGLTextureType(type);
  10405. var internalFormat = this._getInternalFormat(format);
  10406. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10407. var needConversion = false;
  10408. if (internalFormat === gl.RGB) {
  10409. internalFormat = gl.RGBA;
  10410. needConversion = true;
  10411. }
  10412. var width = size;
  10413. var height = width;
  10414. texture.width = width;
  10415. texture.height = height;
  10416. // Double check on POT to generate Mips.
  10417. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10418. if (!isPot) {
  10419. generateMipMaps = false;
  10420. }
  10421. // Upload data if needed. The texture won't be ready until then.
  10422. if (data) {
  10423. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10424. }
  10425. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10426. // Filters
  10427. if (data && generateMipMaps) {
  10428. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10429. }
  10430. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10433. }
  10434. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10437. }
  10438. else {
  10439. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10442. }
  10443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10445. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10446. return texture;
  10447. };
  10448. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10449. var _this = this;
  10450. if (onLoad === void 0) { onLoad = null; }
  10451. if (onError === void 0) { onError = null; }
  10452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10453. if (invertY === void 0) { invertY = false; }
  10454. var gl = this._gl;
  10455. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10456. scene._addPendingData(texture);
  10457. texture.url = url;
  10458. this._internalTexturesCache.push(texture);
  10459. var onerror = function () {
  10460. scene._removePendingData(texture);
  10461. if (onError) {
  10462. onError();
  10463. }
  10464. };
  10465. var internalCallback = function (data) {
  10466. var width = texture.width;
  10467. var height = texture.height;
  10468. var faceDataArrays = callback(data);
  10469. if (mipmmapGenerator) {
  10470. var textureType = _this._getWebGLTextureType(type);
  10471. var internalFormat = _this._getInternalFormat(format);
  10472. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10473. var needConversion = false;
  10474. if (internalFormat === gl.RGB) {
  10475. internalFormat = gl.RGBA;
  10476. needConversion = true;
  10477. }
  10478. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10479. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10480. var mipData = mipmmapGenerator(faceDataArrays);
  10481. for (var level = 0; level < mipData.length; level++) {
  10482. var mipSize = width >> level;
  10483. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10484. var mipFaceData = mipData[level][faceIndex];
  10485. if (needConversion) {
  10486. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10487. }
  10488. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10489. }
  10490. }
  10491. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10492. }
  10493. else {
  10494. texture.generateMipMaps = !noMipmap;
  10495. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10496. }
  10497. texture.isReady = true;
  10498. _this.resetTextureCache();
  10499. scene._removePendingData(texture);
  10500. if (onLoad) {
  10501. onLoad();
  10502. }
  10503. };
  10504. BABYLON.Tools.LoadFile(url, function (data) {
  10505. internalCallback(data);
  10506. }, onerror, scene.database, true);
  10507. return texture;
  10508. };
  10509. ;
  10510. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10511. var gl = this._gl;
  10512. if (!gl) {
  10513. return;
  10514. }
  10515. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10516. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10518. if (!noMipmap && !isCompressed) {
  10519. gl.generateMipmap(gl.TEXTURE_2D);
  10520. }
  10521. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10522. this.resetTextureCache();
  10523. if (scene) {
  10524. scene._removePendingData(texture);
  10525. }
  10526. texture.onLoadedObservable.notifyObservers(texture);
  10527. texture.onLoadedObservable.clear();
  10528. };
  10529. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10530. var _this = this;
  10531. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10532. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10533. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10534. var gl = this._gl;
  10535. if (!gl) {
  10536. return;
  10537. }
  10538. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10539. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10540. texture.baseWidth = width;
  10541. texture.baseHeight = height;
  10542. texture.width = potWidth;
  10543. texture.height = potHeight;
  10544. texture.isReady = true;
  10545. if (processFunction(potWidth, potHeight, function () {
  10546. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10547. })) {
  10548. // Returning as texture needs extra async steps
  10549. return;
  10550. }
  10551. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10552. };
  10553. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10554. // Create new RGBA data container.
  10555. var rgbaData;
  10556. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10557. rgbaData = new Float32Array(width * height * 4);
  10558. }
  10559. else {
  10560. rgbaData = new Uint32Array(width * height * 4);
  10561. }
  10562. // Convert each pixel.
  10563. for (var x = 0; x < width; x++) {
  10564. for (var y = 0; y < height; y++) {
  10565. var index = (y * width + x) * 3;
  10566. var newIndex = (y * width + x) * 4;
  10567. // Map Old Value to new value.
  10568. rgbaData[newIndex + 0] = rgbData[index + 0];
  10569. rgbaData[newIndex + 1] = rgbData[index + 1];
  10570. rgbaData[newIndex + 2] = rgbData[index + 2];
  10571. // Add fully opaque alpha channel.
  10572. rgbaData[newIndex + 3] = 1;
  10573. }
  10574. }
  10575. return rgbaData;
  10576. };
  10577. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10578. var gl = this._gl;
  10579. if (texture._framebuffer) {
  10580. gl.deleteFramebuffer(texture._framebuffer);
  10581. texture._framebuffer = null;
  10582. }
  10583. if (texture._depthStencilBuffer) {
  10584. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10585. texture._depthStencilBuffer = null;
  10586. }
  10587. if (texture._MSAAFramebuffer) {
  10588. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10589. texture._MSAAFramebuffer = null;
  10590. }
  10591. if (texture._MSAARenderBuffer) {
  10592. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10593. texture._MSAARenderBuffer = null;
  10594. }
  10595. };
  10596. Engine.prototype._releaseTexture = function (texture) {
  10597. var gl = this._gl;
  10598. this._releaseFramebufferObjects(texture);
  10599. gl.deleteTexture(texture._webGLTexture);
  10600. // Unbind channels
  10601. this.unbindAllTextures();
  10602. var index = this._internalTexturesCache.indexOf(texture);
  10603. if (index !== -1) {
  10604. this._internalTexturesCache.splice(index, 1);
  10605. }
  10606. // Integrated fixed lod samplers.
  10607. if (texture._lodTextureHigh) {
  10608. texture._lodTextureHigh.dispose();
  10609. }
  10610. if (texture._lodTextureMid) {
  10611. texture._lodTextureMid.dispose();
  10612. }
  10613. if (texture._lodTextureLow) {
  10614. texture._lodTextureLow.dispose();
  10615. }
  10616. };
  10617. Engine.prototype.setProgram = function (program) {
  10618. if (this._currentProgram !== program) {
  10619. this._gl.useProgram(program);
  10620. this._currentProgram = program;
  10621. }
  10622. };
  10623. Engine.prototype.bindSamplers = function (effect) {
  10624. this.setProgram(effect.getProgram());
  10625. var samplers = effect.getSamplers();
  10626. for (var index = 0; index < samplers.length; index++) {
  10627. var uniform = effect.getUniform(samplers[index]);
  10628. this._gl.uniform1i(uniform, index);
  10629. }
  10630. this._currentEffect = null;
  10631. };
  10632. Engine.prototype.activateTexture = function (texture) {
  10633. if (this._activeTexture !== texture) {
  10634. this._gl.activeTexture(texture);
  10635. this._activeTexture = texture;
  10636. }
  10637. };
  10638. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10639. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10640. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10641. this._activeTexturesCache[this._activeTexture] = texture;
  10642. }
  10643. };
  10644. Engine.prototype._bindTexture = function (channel, texture) {
  10645. if (channel < 0) {
  10646. return;
  10647. }
  10648. this.activateTexture(this._gl.TEXTURE0 + channel);
  10649. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10650. };
  10651. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10652. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10653. };
  10654. Engine.prototype.unbindAllTextures = function () {
  10655. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10656. this.activateTexture(this._gl["TEXTURE" + channel]);
  10657. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10659. }
  10660. };
  10661. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10662. if (channel < 0) {
  10663. return;
  10664. }
  10665. this._gl.uniform1i(uniform, channel);
  10666. this._setTexture(channel, texture);
  10667. };
  10668. Engine.prototype._setTexture = function (channel, texture) {
  10669. // Not ready?
  10670. if (!texture) {
  10671. if (this._activeTexturesCache[channel] != null) {
  10672. this.activateTexture(this._gl["TEXTURE" + channel]);
  10673. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10674. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10675. }
  10676. return;
  10677. }
  10678. // Video
  10679. var alreadyActivated = false;
  10680. if (texture.video) {
  10681. this.activateTexture(this._gl["TEXTURE" + channel]);
  10682. alreadyActivated = true;
  10683. texture.update();
  10684. }
  10685. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10686. texture.delayLoad();
  10687. return;
  10688. }
  10689. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10690. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10691. if (this._activeTexturesCache[channel] === internalTexture) {
  10692. return;
  10693. }
  10694. if (!alreadyActivated) {
  10695. this.activateTexture(this._gl["TEXTURE" + channel]);
  10696. }
  10697. if (internalTexture.isCube) {
  10698. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10699. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10700. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10701. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10702. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10703. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10704. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10705. }
  10706. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10707. }
  10708. else {
  10709. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10710. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10711. internalTexture._cachedWrapU = texture.wrapU;
  10712. switch (texture.wrapU) {
  10713. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10714. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10715. break;
  10716. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10717. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10718. break;
  10719. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10720. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10721. break;
  10722. }
  10723. }
  10724. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10725. internalTexture._cachedWrapV = texture.wrapV;
  10726. switch (texture.wrapV) {
  10727. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10728. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10729. break;
  10730. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10731. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10732. break;
  10733. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10734. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10735. break;
  10736. }
  10737. }
  10738. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10739. }
  10740. };
  10741. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10742. if (channel < 0) {
  10743. return;
  10744. }
  10745. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10746. this._textureUnits = new Int32Array(textures.length);
  10747. }
  10748. for (var i = 0; i < textures.length; i++) {
  10749. this._textureUnits[i] = channel + i;
  10750. }
  10751. this._gl.uniform1iv(uniform, this._textureUnits);
  10752. for (var index = 0; index < textures.length; index++) {
  10753. this._setTexture(channel + index, textures[index]);
  10754. }
  10755. };
  10756. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10757. var internalTexture = texture.getInternalTexture();
  10758. if (!internalTexture) {
  10759. return;
  10760. }
  10761. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10762. var value = texture.anisotropicFilteringLevel;
  10763. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10764. value = 1;
  10765. }
  10766. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10767. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10768. internalTexture._cachedAnisotropicFilteringLevel = value;
  10769. }
  10770. };
  10771. Engine.prototype.readPixels = function (x, y, width, height) {
  10772. var data = new Uint8Array(height * width * 4);
  10773. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10774. return data;
  10775. };
  10776. /**
  10777. * Add an externaly attached data from its key.
  10778. * This method call will fail and return false, if such key already exists.
  10779. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10780. * @param key the unique key that identifies the data
  10781. * @param data the data object to associate to the key for this Engine instance
  10782. * @return true if no such key were already present and the data was added successfully, false otherwise
  10783. */
  10784. Engine.prototype.addExternalData = function (key, data) {
  10785. if (!this._externalData) {
  10786. this._externalData = new BABYLON.StringDictionary();
  10787. }
  10788. return this._externalData.add(key, data);
  10789. };
  10790. /**
  10791. * Get an externaly attached data from its key
  10792. * @param key the unique key that identifies the data
  10793. * @return the associated data, if present (can be null), or undefined if not present
  10794. */
  10795. Engine.prototype.getExternalData = function (key) {
  10796. if (!this._externalData) {
  10797. this._externalData = new BABYLON.StringDictionary();
  10798. }
  10799. return this._externalData.get(key);
  10800. };
  10801. /**
  10802. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10803. * @param key the unique key that identifies the data
  10804. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10805. * @return the associated data, can be null if the factory returned null.
  10806. */
  10807. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10808. if (!this._externalData) {
  10809. this._externalData = new BABYLON.StringDictionary();
  10810. }
  10811. return this._externalData.getOrAddWithFactory(key, factory);
  10812. };
  10813. /**
  10814. * Remove an externaly attached data from the Engine instance
  10815. * @param key the unique key that identifies the data
  10816. * @return true if the data was successfully removed, false if it doesn't exist
  10817. */
  10818. Engine.prototype.removeExternalData = function (key) {
  10819. if (!this._externalData) {
  10820. this._externalData = new BABYLON.StringDictionary();
  10821. }
  10822. return this._externalData.remove(key);
  10823. };
  10824. Engine.prototype.unbindAllAttributes = function () {
  10825. if (this._mustWipeVertexAttributes) {
  10826. this._mustWipeVertexAttributes = false;
  10827. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10828. this._gl.disableVertexAttribArray(i);
  10829. this._vertexAttribArraysEnabled[i] = false;
  10830. this._currentBufferPointers[i].active = false;
  10831. }
  10832. return;
  10833. }
  10834. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10835. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10836. continue;
  10837. }
  10838. this._gl.disableVertexAttribArray(i);
  10839. this._vertexAttribArraysEnabled[i] = false;
  10840. this._currentBufferPointers[i].active = false;
  10841. }
  10842. };
  10843. Engine.prototype.releaseEffects = function () {
  10844. for (var name in this._compiledEffects) {
  10845. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10846. }
  10847. this._compiledEffects = {};
  10848. };
  10849. // Dispose
  10850. Engine.prototype.dispose = function () {
  10851. this.hideLoadingUI();
  10852. this.stopRenderLoop();
  10853. // Release postProcesses
  10854. while (this.postProcesses.length) {
  10855. this.postProcesses[0].dispose();
  10856. }
  10857. // Empty texture
  10858. if (this._emptyTexture) {
  10859. this._releaseTexture(this._emptyTexture);
  10860. this._emptyTexture = null;
  10861. }
  10862. if (this._emptyCubeTexture) {
  10863. this._releaseTexture(this._emptyCubeTexture);
  10864. this._emptyCubeTexture = null;
  10865. }
  10866. // Rescale PP
  10867. if (this._rescalePostProcess) {
  10868. this._rescalePostProcess.dispose();
  10869. }
  10870. // Release scenes
  10871. while (this.scenes.length) {
  10872. this.scenes[0].dispose();
  10873. }
  10874. // Release audio engine
  10875. if (Engine.audioEngine) {
  10876. Engine.audioEngine.dispose();
  10877. }
  10878. // Release effects
  10879. this.releaseEffects();
  10880. // Unbind
  10881. this.unbindAllAttributes();
  10882. if (this._dummyFramebuffer) {
  10883. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10884. }
  10885. this._gl = null;
  10886. //WebVR
  10887. this.disableVR();
  10888. // Events
  10889. window.removeEventListener("blur", this._onBlur);
  10890. window.removeEventListener("focus", this._onFocus);
  10891. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  10892. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  10893. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10894. if (!this._doNotHandleContextLost) {
  10895. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  10896. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  10897. }
  10898. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10899. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10900. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10901. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10902. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10903. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10904. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10905. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10906. // Remove from Instances
  10907. var index = Engine.Instances.indexOf(this);
  10908. if (index >= 0) {
  10909. Engine.Instances.splice(index, 1);
  10910. }
  10911. this._workingCanvas = null;
  10912. this._workingContext = null;
  10913. this._currentBufferPointers = null;
  10914. this._renderingCanvas = null;
  10915. this._currentProgram = null;
  10916. this.onResizeObservable.clear();
  10917. this.onCanvasBlurObservable.clear();
  10918. BABYLON.Effect.ResetCache();
  10919. };
  10920. // Loading screen
  10921. Engine.prototype.displayLoadingUI = function () {
  10922. var loadingScreen = this.loadingScreen;
  10923. if (loadingScreen) {
  10924. loadingScreen.displayLoadingUI();
  10925. }
  10926. };
  10927. Engine.prototype.hideLoadingUI = function () {
  10928. var loadingScreen = this.loadingScreen;
  10929. if (loadingScreen) {
  10930. loadingScreen.hideLoadingUI();
  10931. }
  10932. };
  10933. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10934. get: function () {
  10935. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10936. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10937. return this._loadingScreen;
  10938. },
  10939. set: function (loadingScreen) {
  10940. this._loadingScreen = loadingScreen;
  10941. },
  10942. enumerable: true,
  10943. configurable: true
  10944. });
  10945. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10946. set: function (text) {
  10947. this.loadingScreen.loadingUIText = text;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10953. set: function (color) {
  10954. this.loadingScreen.loadingUIBackgroundColor = color;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Engine.prototype.attachContextLostEvent = function (callback) {
  10960. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10961. };
  10962. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10963. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10964. };
  10965. Engine.prototype.getVertexShaderSource = function (program) {
  10966. var shaders = this._gl.getAttachedShaders(program);
  10967. return this._gl.getShaderSource(shaders[0]);
  10968. };
  10969. Engine.prototype.getFragmentShaderSource = function (program) {
  10970. var shaders = this._gl.getAttachedShaders(program);
  10971. return this._gl.getShaderSource(shaders[1]);
  10972. };
  10973. Engine.prototype.getError = function () {
  10974. return this._gl.getError();
  10975. };
  10976. // FPS
  10977. Engine.prototype.getFps = function () {
  10978. return this._fps;
  10979. };
  10980. Engine.prototype.getDeltaTime = function () {
  10981. return this._deltaTime;
  10982. };
  10983. Engine.prototype._measureFps = function () {
  10984. this._performanceMonitor.sampleFrame();
  10985. this._fps = this._performanceMonitor.averageFPS;
  10986. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10987. };
  10988. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10989. if (faceIndex === void 0) { faceIndex = -1; }
  10990. var gl = this._gl;
  10991. if (!this._dummyFramebuffer) {
  10992. this._dummyFramebuffer = gl.createFramebuffer();
  10993. }
  10994. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10995. if (faceIndex > -1) {
  10996. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10997. }
  10998. else {
  10999. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11000. }
  11001. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11002. var buffer;
  11003. switch (readType) {
  11004. case gl.UNSIGNED_BYTE:
  11005. buffer = new Uint8Array(4 * width * height);
  11006. readType = gl.UNSIGNED_BYTE;
  11007. break;
  11008. default:
  11009. buffer = new Float32Array(4 * width * height);
  11010. readType = gl.FLOAT;
  11011. break;
  11012. }
  11013. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11014. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11015. return buffer;
  11016. };
  11017. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11018. if (this._webGLVersion > 1) {
  11019. return this._caps.colorBufferFloat;
  11020. }
  11021. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11022. };
  11023. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11024. if (this._webGLVersion > 1) {
  11025. return this._caps.colorBufferFloat;
  11026. }
  11027. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11028. };
  11029. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11030. Engine.prototype._canRenderToFramebuffer = function (type) {
  11031. var gl = this._gl;
  11032. //clear existing errors
  11033. while (gl.getError() !== gl.NO_ERROR) { }
  11034. var successful = true;
  11035. var texture = gl.createTexture();
  11036. gl.bindTexture(gl.TEXTURE_2D, texture);
  11037. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11038. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11039. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11040. var fb = gl.createFramebuffer();
  11041. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11042. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11043. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11044. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11045. successful = successful && (gl.getError() === gl.NO_ERROR);
  11046. //try render by clearing frame buffer's color buffer
  11047. if (successful) {
  11048. gl.clear(gl.COLOR_BUFFER_BIT);
  11049. successful = successful && (gl.getError() === gl.NO_ERROR);
  11050. }
  11051. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11052. if (successful) {
  11053. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11054. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11055. var readFormat = gl.RGBA;
  11056. var readType = gl.UNSIGNED_BYTE;
  11057. var buffer = new Uint8Array(4);
  11058. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11059. successful = successful && (gl.getError() === gl.NO_ERROR);
  11060. }
  11061. //clean up
  11062. gl.deleteTexture(texture);
  11063. gl.deleteFramebuffer(fb);
  11064. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11065. //clear accumulated errors
  11066. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11067. return successful;
  11068. };
  11069. Engine.prototype._getWebGLTextureType = function (type) {
  11070. if (type === Engine.TEXTURETYPE_FLOAT) {
  11071. return this._gl.FLOAT;
  11072. }
  11073. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11074. // Add Half Float Constant.
  11075. return this._gl.HALF_FLOAT_OES;
  11076. }
  11077. return this._gl.UNSIGNED_BYTE;
  11078. };
  11079. ;
  11080. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11081. if (this._webGLVersion === 1) {
  11082. return this._gl.RGBA;
  11083. }
  11084. if (type === Engine.TEXTURETYPE_FLOAT) {
  11085. return this._gl.RGBA32F;
  11086. }
  11087. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11088. return this._gl.RGBA16F;
  11089. }
  11090. return this._gl.RGBA;
  11091. };
  11092. ;
  11093. Engine.prototype.createQuery = function () {
  11094. return this._gl.createQuery();
  11095. };
  11096. Engine.prototype.deleteQuery = function (query) {
  11097. this._gl.deleteQuery(query);
  11098. return this;
  11099. };
  11100. Engine.prototype.isQueryResultAvailable = function (query) {
  11101. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11102. };
  11103. Engine.prototype.getQueryResult = function (query) {
  11104. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11105. };
  11106. Engine.prototype.beginQuery = function (algorithmType, query) {
  11107. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11108. this._gl.beginQuery(glAlgorithm, query);
  11109. };
  11110. Engine.prototype.endQuery = function (algorithmType) {
  11111. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11112. this._gl.endQuery(glAlgorithm);
  11113. return this;
  11114. };
  11115. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11116. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11117. };
  11118. // Statics
  11119. Engine.isSupported = function () {
  11120. try {
  11121. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11122. if (navigator.isCocoonJS) {
  11123. return true;
  11124. }
  11125. var tempcanvas = document.createElement("canvas");
  11126. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11127. return gl != null && !!window.WebGLRenderingContext;
  11128. }
  11129. catch (e) {
  11130. return false;
  11131. }
  11132. };
  11133. Engine.Instances = new Array();
  11134. // Const statics
  11135. Engine._ALPHA_DISABLE = 0;
  11136. Engine._ALPHA_ADD = 1;
  11137. Engine._ALPHA_COMBINE = 2;
  11138. Engine._ALPHA_SUBTRACT = 3;
  11139. Engine._ALPHA_MULTIPLY = 4;
  11140. Engine._ALPHA_MAXIMIZED = 5;
  11141. Engine._ALPHA_ONEONE = 6;
  11142. Engine._ALPHA_PREMULTIPLIED = 7;
  11143. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11144. Engine._ALPHA_INTERPOLATE = 9;
  11145. Engine._ALPHA_SCREENMODE = 10;
  11146. Engine._DELAYLOADSTATE_NONE = 0;
  11147. Engine._DELAYLOADSTATE_LOADED = 1;
  11148. Engine._DELAYLOADSTATE_LOADING = 2;
  11149. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11150. Engine._TEXTUREFORMAT_ALPHA = 0;
  11151. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11152. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11153. Engine._TEXTUREFORMAT_RGB = 4;
  11154. Engine._TEXTUREFORMAT_RGBA = 5;
  11155. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11156. Engine._TEXTURETYPE_FLOAT = 1;
  11157. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11158. // Depht or Stencil test Constants.
  11159. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11160. 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.
  11161. 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.
  11162. 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.
  11163. 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.
  11164. 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.
  11165. 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.
  11166. 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.
  11167. // Stencil Actions Constants.
  11168. Engine._KEEP = 0x1E00;
  11169. Engine._REPLACE = 0x1E01;
  11170. Engine._INCR = 0x1E02;
  11171. Engine._DECR = 0x1E03;
  11172. Engine._INVERT = 0x150A;
  11173. Engine._INCR_WRAP = 0x8507;
  11174. Engine._DECR_WRAP = 0x8508;
  11175. // Texture rescaling mode
  11176. Engine._SCALEMODE_FLOOR = 1;
  11177. Engine._SCALEMODE_NEAREST = 2;
  11178. Engine._SCALEMODE_CEILING = 3;
  11179. // Updatable statics so stick with vars here
  11180. Engine.CollisionsEpsilon = 0.001;
  11181. Engine.CodeRepository = "src/";
  11182. Engine.ShadersRepository = "src/Shaders/";
  11183. return Engine;
  11184. }());
  11185. BABYLON.Engine = Engine;
  11186. })(BABYLON || (BABYLON = {}));
  11187. //# sourceMappingURL=babylon.engine.js.map
  11188. /// <reference path="Tools\babylon.decorators.ts" />
  11189. var BABYLON;
  11190. (function (BABYLON) {
  11191. /**
  11192. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11193. */
  11194. var Node = (function () {
  11195. /**
  11196. * @constructor
  11197. * @param {string} name - the name and id to be given to this node
  11198. * @param {BABYLON.Scene} the scene this node will be added to
  11199. */
  11200. function Node(name, scene) {
  11201. this.state = "";
  11202. this.metadata = null;
  11203. this.doNotSerialize = false;
  11204. this.animations = new Array();
  11205. this._ranges = {};
  11206. this._childrenFlag = -1;
  11207. this._isEnabled = true;
  11208. this._isReady = true;
  11209. this._currentRenderId = -1;
  11210. this._parentRenderId = -1;
  11211. /**
  11212. * An event triggered when the mesh is disposed.
  11213. * @type {BABYLON.Observable}
  11214. */
  11215. this.onDisposeObservable = new BABYLON.Observable();
  11216. // Behaviors
  11217. this._behaviors = new Array();
  11218. this.name = name;
  11219. this.id = name;
  11220. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11221. this._initCache();
  11222. }
  11223. Object.defineProperty(Node.prototype, "parent", {
  11224. get: function () {
  11225. return this._parentNode;
  11226. },
  11227. set: function (parent) {
  11228. if (this._parentNode === parent) {
  11229. return;
  11230. }
  11231. if (this._parentNode) {
  11232. var index = this._parentNode._children.indexOf(this);
  11233. if (index !== -1) {
  11234. this._parentNode._children.splice(index, 1);
  11235. }
  11236. }
  11237. this._parentNode = parent;
  11238. if (this._parentNode) {
  11239. if (!this._parentNode._children) {
  11240. this._parentNode._children = new Array();
  11241. }
  11242. this._parentNode._children.push(this);
  11243. }
  11244. },
  11245. enumerable: true,
  11246. configurable: true
  11247. });
  11248. Node.prototype.getClassName = function () {
  11249. return "Node";
  11250. };
  11251. Object.defineProperty(Node.prototype, "onDispose", {
  11252. set: function (callback) {
  11253. if (this._onDisposeObserver) {
  11254. this.onDisposeObservable.remove(this._onDisposeObserver);
  11255. }
  11256. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Node.prototype.getScene = function () {
  11262. return this._scene;
  11263. };
  11264. Node.prototype.getEngine = function () {
  11265. return this._scene.getEngine();
  11266. };
  11267. Node.prototype.addBehavior = function (behavior) {
  11268. var index = this._behaviors.indexOf(behavior);
  11269. if (index !== -1) {
  11270. return;
  11271. }
  11272. behavior.attach(this);
  11273. this._behaviors.push(behavior);
  11274. return this;
  11275. };
  11276. Node.prototype.removeBehavior = function (behavior) {
  11277. var index = this._behaviors.indexOf(behavior);
  11278. if (index === -1) {
  11279. return;
  11280. }
  11281. this._behaviors[index].detach();
  11282. this._behaviors.splice(index, 1);
  11283. return this;
  11284. };
  11285. Object.defineProperty(Node.prototype, "behaviors", {
  11286. get: function () {
  11287. return this._behaviors;
  11288. },
  11289. enumerable: true,
  11290. configurable: true
  11291. });
  11292. Node.prototype.getBehaviorByName = function (name) {
  11293. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11294. var behavior = _a[_i];
  11295. if (behavior.name === name) {
  11296. return behavior;
  11297. }
  11298. }
  11299. return null;
  11300. };
  11301. // override it in derived class
  11302. Node.prototype.getWorldMatrix = function () {
  11303. return BABYLON.Matrix.Identity();
  11304. };
  11305. // override it in derived class if you add new variables to the cache
  11306. // and call the parent class method
  11307. Node.prototype._initCache = function () {
  11308. this._cache = {};
  11309. this._cache.parent = undefined;
  11310. };
  11311. Node.prototype.updateCache = function (force) {
  11312. if (!force && this.isSynchronized())
  11313. return;
  11314. this._cache.parent = this.parent;
  11315. this._updateCache();
  11316. };
  11317. // override it in derived class if you add new variables to the cache
  11318. // and call the parent class method if !ignoreParentClass
  11319. Node.prototype._updateCache = function (ignoreParentClass) {
  11320. };
  11321. // override it in derived class if you add new variables to the cache
  11322. Node.prototype._isSynchronized = function () {
  11323. return true;
  11324. };
  11325. Node.prototype._markSyncedWithParent = function () {
  11326. this._parentRenderId = this.parent._currentRenderId;
  11327. };
  11328. Node.prototype.isSynchronizedWithParent = function () {
  11329. if (!this.parent) {
  11330. return true;
  11331. }
  11332. if (this._parentRenderId !== this.parent._currentRenderId) {
  11333. return false;
  11334. }
  11335. return this.parent.isSynchronized();
  11336. };
  11337. Node.prototype.isSynchronized = function (updateCache) {
  11338. var check = this.hasNewParent();
  11339. check = check || !this.isSynchronizedWithParent();
  11340. check = check || !this._isSynchronized();
  11341. if (updateCache)
  11342. this.updateCache(true);
  11343. return !check;
  11344. };
  11345. Node.prototype.hasNewParent = function (update) {
  11346. if (this._cache.parent === this.parent)
  11347. return false;
  11348. if (update)
  11349. this._cache.parent = this.parent;
  11350. return true;
  11351. };
  11352. /**
  11353. * Is this node ready to be used/rendered
  11354. * @return {boolean} is it ready
  11355. */
  11356. Node.prototype.isReady = function () {
  11357. return this._isReady;
  11358. };
  11359. /**
  11360. * Is this node enabled.
  11361. * If the node has a parent and is enabled, the parent will be inspected as well.
  11362. * @return {boolean} whether this node (and its parent) is enabled.
  11363. * @see setEnabled
  11364. */
  11365. Node.prototype.isEnabled = function () {
  11366. if (!this._isEnabled) {
  11367. return false;
  11368. }
  11369. if (this.parent) {
  11370. return this.parent.isEnabled();
  11371. }
  11372. return true;
  11373. };
  11374. /**
  11375. * Set the enabled state of this node.
  11376. * @param {boolean} value - the new enabled state
  11377. * @see isEnabled
  11378. */
  11379. Node.prototype.setEnabled = function (value) {
  11380. this._isEnabled = value;
  11381. };
  11382. /**
  11383. * Is this node a descendant of the given node.
  11384. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11385. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11386. * @see parent
  11387. */
  11388. Node.prototype.isDescendantOf = function (ancestor) {
  11389. if (this.parent) {
  11390. if (this.parent === ancestor) {
  11391. return true;
  11392. }
  11393. return this.parent.isDescendantOf(ancestor);
  11394. }
  11395. return false;
  11396. };
  11397. /**
  11398. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11399. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11400. * @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.
  11401. * @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.
  11402. */
  11403. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11404. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11405. if (!this._children) {
  11406. return;
  11407. }
  11408. for (var index = 0; index < this._children.length; index++) {
  11409. var item = this._children[index];
  11410. if (!predicate || predicate(item)) {
  11411. results.push(item);
  11412. }
  11413. if (!directDescendantsOnly) {
  11414. item._getDescendants(results, false, predicate);
  11415. }
  11416. }
  11417. };
  11418. /**
  11419. * Will return all nodes that have this node as ascendant.
  11420. * @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.
  11421. * @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.
  11422. * @return {BABYLON.Node[]} all children nodes of all types.
  11423. */
  11424. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11425. var results = [];
  11426. this._getDescendants(results, directDescendantsOnly, predicate);
  11427. return results;
  11428. };
  11429. /**
  11430. * Get all child-meshes of this node.
  11431. */
  11432. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11433. var results = [];
  11434. this._getDescendants(results, directDecendantsOnly, function (node) {
  11435. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11436. });
  11437. return results;
  11438. };
  11439. /**
  11440. * Get all direct children of this node.
  11441. */
  11442. Node.prototype.getChildren = function (predicate) {
  11443. return this.getDescendants(true, predicate);
  11444. };
  11445. Node.prototype._setReady = function (state) {
  11446. if (state === this._isReady) {
  11447. return;
  11448. }
  11449. if (!state) {
  11450. this._isReady = false;
  11451. return;
  11452. }
  11453. this._isReady = true;
  11454. if (this.onReady) {
  11455. this.onReady(this);
  11456. }
  11457. };
  11458. Node.prototype.getAnimationByName = function (name) {
  11459. for (var i = 0; i < this.animations.length; i++) {
  11460. var animation = this.animations[i];
  11461. if (animation.name === name) {
  11462. return animation;
  11463. }
  11464. }
  11465. return null;
  11466. };
  11467. Node.prototype.createAnimationRange = function (name, from, to) {
  11468. // check name not already in use
  11469. if (!this._ranges[name]) {
  11470. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11471. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11472. if (this.animations[i]) {
  11473. this.animations[i].createRange(name, from, to);
  11474. }
  11475. }
  11476. }
  11477. };
  11478. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11479. if (deleteFrames === void 0) { deleteFrames = true; }
  11480. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11481. if (this.animations[i]) {
  11482. this.animations[i].deleteRange(name, deleteFrames);
  11483. }
  11484. }
  11485. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11486. };
  11487. Node.prototype.getAnimationRange = function (name) {
  11488. return this._ranges[name];
  11489. };
  11490. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11491. var range = this.getAnimationRange(name);
  11492. if (!range) {
  11493. return null;
  11494. }
  11495. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11496. };
  11497. Node.prototype.serializeAnimationRanges = function () {
  11498. var serializationRanges = [];
  11499. for (var name in this._ranges) {
  11500. var range = {};
  11501. range.name = name;
  11502. range.from = this._ranges[name].from;
  11503. range.to = this._ranges[name].to;
  11504. serializationRanges.push(range);
  11505. }
  11506. return serializationRanges;
  11507. };
  11508. Node.prototype.dispose = function () {
  11509. this.parent = null;
  11510. // Callback
  11511. this.onDisposeObservable.notifyObservers(this);
  11512. this.onDisposeObservable.clear();
  11513. // Behaviors
  11514. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11515. var behavior = _a[_i];
  11516. behavior.detach();
  11517. }
  11518. this._behaviors = [];
  11519. };
  11520. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11521. if (parsedNode.ranges) {
  11522. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11523. var data = parsedNode.ranges[index];
  11524. node.createAnimationRange(data.name, data.from, data.to);
  11525. }
  11526. }
  11527. };
  11528. __decorate([
  11529. BABYLON.serialize()
  11530. ], Node.prototype, "name", void 0);
  11531. __decorate([
  11532. BABYLON.serialize()
  11533. ], Node.prototype, "id", void 0);
  11534. __decorate([
  11535. BABYLON.serialize()
  11536. ], Node.prototype, "uniqueId", void 0);
  11537. __decorate([
  11538. BABYLON.serialize()
  11539. ], Node.prototype, "state", void 0);
  11540. __decorate([
  11541. BABYLON.serialize()
  11542. ], Node.prototype, "metadata", void 0);
  11543. return Node;
  11544. }());
  11545. BABYLON.Node = Node;
  11546. })(BABYLON || (BABYLON = {}));
  11547. //# sourceMappingURL=babylon.node.js.map
  11548. var BABYLON;
  11549. (function (BABYLON) {
  11550. var BoundingSphere = (function () {
  11551. function BoundingSphere(minimum, maximum) {
  11552. this.minimum = minimum;
  11553. this.maximum = maximum;
  11554. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11555. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11556. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11557. this.radius = distance * 0.5;
  11558. this.centerWorld = BABYLON.Vector3.Zero();
  11559. this._update(BABYLON.Matrix.Identity());
  11560. }
  11561. // Methods
  11562. BoundingSphere.prototype._update = function (world) {
  11563. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11564. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11565. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11566. };
  11567. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11568. for (var i = 0; i < 6; i++) {
  11569. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11570. return false;
  11571. }
  11572. return true;
  11573. };
  11574. BoundingSphere.prototype.intersectsPoint = function (point) {
  11575. var x = this.centerWorld.x - point.x;
  11576. var y = this.centerWorld.y - point.y;
  11577. var z = this.centerWorld.z - point.z;
  11578. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11579. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11580. return false;
  11581. return true;
  11582. };
  11583. // Statics
  11584. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11585. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11586. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11587. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11588. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11589. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11590. return false;
  11591. return true;
  11592. };
  11593. return BoundingSphere;
  11594. }());
  11595. BABYLON.BoundingSphere = BoundingSphere;
  11596. })(BABYLON || (BABYLON = {}));
  11597. //# sourceMappingURL=babylon.boundingSphere.js.map
  11598. var BABYLON;
  11599. (function (BABYLON) {
  11600. var BoundingBox = (function () {
  11601. function BoundingBox(minimum, maximum) {
  11602. this.minimum = minimum;
  11603. this.maximum = maximum;
  11604. this.vectors = new Array();
  11605. this.vectorsWorld = new Array();
  11606. // Bounding vectors
  11607. this.vectors.push(this.minimum.clone());
  11608. this.vectors.push(this.maximum.clone());
  11609. this.vectors.push(this.minimum.clone());
  11610. this.vectors[2].x = this.maximum.x;
  11611. this.vectors.push(this.minimum.clone());
  11612. this.vectors[3].y = this.maximum.y;
  11613. this.vectors.push(this.minimum.clone());
  11614. this.vectors[4].z = this.maximum.z;
  11615. this.vectors.push(this.maximum.clone());
  11616. this.vectors[5].z = this.minimum.z;
  11617. this.vectors.push(this.maximum.clone());
  11618. this.vectors[6].x = this.minimum.x;
  11619. this.vectors.push(this.maximum.clone());
  11620. this.vectors[7].y = this.minimum.y;
  11621. // OBB
  11622. this.center = this.maximum.add(this.minimum).scale(0.5);
  11623. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11624. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11625. // World
  11626. for (var index = 0; index < this.vectors.length; index++) {
  11627. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11628. }
  11629. this.minimumWorld = BABYLON.Vector3.Zero();
  11630. this.maximumWorld = BABYLON.Vector3.Zero();
  11631. this.centerWorld = BABYLON.Vector3.Zero();
  11632. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11633. this._update(BABYLON.Matrix.Identity());
  11634. }
  11635. // Methods
  11636. BoundingBox.prototype.getWorldMatrix = function () {
  11637. return this._worldMatrix;
  11638. };
  11639. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11640. this._worldMatrix.copyFrom(matrix);
  11641. return this;
  11642. };
  11643. BoundingBox.prototype._update = function (world) {
  11644. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11645. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11646. for (var index = 0; index < this.vectors.length; index++) {
  11647. var v = this.vectorsWorld[index];
  11648. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11649. if (v.x < this.minimumWorld.x)
  11650. this.minimumWorld.x = v.x;
  11651. if (v.y < this.minimumWorld.y)
  11652. this.minimumWorld.y = v.y;
  11653. if (v.z < this.minimumWorld.z)
  11654. this.minimumWorld.z = v.z;
  11655. if (v.x > this.maximumWorld.x)
  11656. this.maximumWorld.x = v.x;
  11657. if (v.y > this.maximumWorld.y)
  11658. this.maximumWorld.y = v.y;
  11659. if (v.z > this.maximumWorld.z)
  11660. this.maximumWorld.z = v.z;
  11661. }
  11662. // Extend
  11663. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11664. this.extendSizeWorld.scaleInPlace(0.5);
  11665. // OBB
  11666. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11667. this.centerWorld.scaleInPlace(0.5);
  11668. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11669. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11670. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11671. this._worldMatrix = world;
  11672. };
  11673. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11674. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11675. };
  11676. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11677. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11678. };
  11679. BoundingBox.prototype.intersectsPoint = function (point) {
  11680. var delta = -BABYLON.Epsilon;
  11681. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11682. return false;
  11683. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11684. return false;
  11685. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11686. return false;
  11687. return true;
  11688. };
  11689. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11690. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11691. };
  11692. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11693. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11694. return false;
  11695. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11696. return false;
  11697. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11698. return false;
  11699. return true;
  11700. };
  11701. // Statics
  11702. BoundingBox.Intersects = function (box0, box1) {
  11703. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11704. return false;
  11705. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11706. return false;
  11707. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11708. return false;
  11709. return true;
  11710. };
  11711. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11712. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11713. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11714. return (num <= (sphereRadius * sphereRadius));
  11715. };
  11716. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11717. for (var p = 0; p < 6; p++) {
  11718. for (var i = 0; i < 8; i++) {
  11719. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11720. return false;
  11721. }
  11722. }
  11723. }
  11724. return true;
  11725. };
  11726. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11727. for (var p = 0; p < 6; p++) {
  11728. var inCount = 8;
  11729. for (var i = 0; i < 8; i++) {
  11730. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11731. --inCount;
  11732. }
  11733. else {
  11734. break;
  11735. }
  11736. }
  11737. if (inCount === 0)
  11738. return false;
  11739. }
  11740. return true;
  11741. };
  11742. return BoundingBox;
  11743. }());
  11744. BABYLON.BoundingBox = BoundingBox;
  11745. })(BABYLON || (BABYLON = {}));
  11746. //# sourceMappingURL=babylon.boundingBox.js.map
  11747. var BABYLON;
  11748. (function (BABYLON) {
  11749. var computeBoxExtents = function (axis, box) {
  11750. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11751. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11752. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11753. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11754. var r = r0 + r1 + r2;
  11755. return {
  11756. min: p - r,
  11757. max: p + r
  11758. };
  11759. };
  11760. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11761. var axisOverlap = function (axis, box0, box1) {
  11762. var result0 = computeBoxExtents(axis, box0);
  11763. var result1 = computeBoxExtents(axis, box1);
  11764. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11765. };
  11766. var BoundingInfo = (function () {
  11767. function BoundingInfo(minimum, maximum) {
  11768. this.minimum = minimum;
  11769. this.maximum = maximum;
  11770. this._isLocked = false;
  11771. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11772. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11773. }
  11774. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11775. get: function () {
  11776. return this._isLocked;
  11777. },
  11778. set: function (value) {
  11779. this._isLocked = value;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. // Methods
  11785. BoundingInfo.prototype.update = function (world) {
  11786. if (this._isLocked) {
  11787. return;
  11788. }
  11789. this.boundingBox._update(world);
  11790. this.boundingSphere._update(world);
  11791. };
  11792. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11793. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11794. return false;
  11795. return this.boundingBox.isInFrustum(frustumPlanes);
  11796. };
  11797. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11798. /**
  11799. * Gets the world distance between the min and max points of the bounding box
  11800. */
  11801. get: function () {
  11802. var boundingBox = this.boundingBox;
  11803. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11804. return size.length();
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11810. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11811. };
  11812. BoundingInfo.prototype._checkCollision = function (collider) {
  11813. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11814. };
  11815. BoundingInfo.prototype.intersectsPoint = function (point) {
  11816. if (!this.boundingSphere.centerWorld) {
  11817. return false;
  11818. }
  11819. if (!this.boundingSphere.intersectsPoint(point)) {
  11820. return false;
  11821. }
  11822. if (!this.boundingBox.intersectsPoint(point)) {
  11823. return false;
  11824. }
  11825. return true;
  11826. };
  11827. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11828. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11829. return false;
  11830. }
  11831. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11832. return false;
  11833. }
  11834. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11835. return false;
  11836. }
  11837. if (!precise) {
  11838. return true;
  11839. }
  11840. var box0 = this.boundingBox;
  11841. var box1 = boundingInfo.boundingBox;
  11842. if (!axisOverlap(box0.directions[0], box0, box1))
  11843. return false;
  11844. if (!axisOverlap(box0.directions[1], box0, box1))
  11845. return false;
  11846. if (!axisOverlap(box0.directions[2], box0, box1))
  11847. return false;
  11848. if (!axisOverlap(box1.directions[0], box0, box1))
  11849. return false;
  11850. if (!axisOverlap(box1.directions[1], box0, box1))
  11851. return false;
  11852. if (!axisOverlap(box1.directions[2], box0, box1))
  11853. return false;
  11854. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11855. return false;
  11856. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11857. return false;
  11858. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11859. return false;
  11860. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11861. return false;
  11862. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11863. return false;
  11864. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11865. return false;
  11866. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11867. return false;
  11868. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11869. return false;
  11870. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11871. return false;
  11872. return true;
  11873. };
  11874. return BoundingInfo;
  11875. }());
  11876. BABYLON.BoundingInfo = BoundingInfo;
  11877. })(BABYLON || (BABYLON = {}));
  11878. //# sourceMappingURL=babylon.boundingInfo.js.map
  11879. var BABYLON;
  11880. (function (BABYLON) {
  11881. var AbstractMesh = (function (_super) {
  11882. __extends(AbstractMesh, _super);
  11883. // Constructor
  11884. function AbstractMesh(name, scene) {
  11885. var _this = _super.call(this, name, scene) || this;
  11886. _this._facetNb = 0; // facet number
  11887. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11888. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11889. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11890. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11891. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11892. _this._subDiv = {
  11893. max: 1,
  11894. X: 1,
  11895. Y: 1,
  11896. Z: 1
  11897. };
  11898. // Events
  11899. /**
  11900. * An event triggered when this mesh collides with another one
  11901. * @type {BABYLON.Observable}
  11902. */
  11903. _this.onCollideObservable = new BABYLON.Observable();
  11904. /**
  11905. * An event triggered when the collision's position changes
  11906. * @type {BABYLON.Observable}
  11907. */
  11908. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11909. /**
  11910. * An event triggered after the world matrix is updated
  11911. * @type {BABYLON.Observable}
  11912. */
  11913. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11914. /**
  11915. * An event triggered when material is changed
  11916. * @type {BABYLON.Observable}
  11917. */
  11918. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11919. // Properties
  11920. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11921. _this.position = BABYLON.Vector3.Zero();
  11922. /**
  11923. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  11924. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  11925. * or
  11926. * 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.
  11927. * for more info check WebGl documentations
  11928. */
  11929. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11930. /**
  11931. * 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:
  11932. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  11933. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  11934. * 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.
  11935. */
  11936. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11937. /**
  11938. * 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.
  11939. * The default value is -1 which means don't break the query and wait till the result.
  11940. */
  11941. _this.occlusionRetryCount = -1;
  11942. _this._occlusionInternalRetryCounter = 0;
  11943. _this._isOccluded = false;
  11944. _this._isOcclusionQueryInProgress = false;
  11945. _this._rotation = BABYLON.Vector3.Zero();
  11946. _this._scaling = BABYLON.Vector3.One();
  11947. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11948. _this.visibility = 1.0;
  11949. _this.alphaIndex = Number.MAX_VALUE;
  11950. _this.infiniteDistance = false;
  11951. _this.isVisible = true;
  11952. _this.isPickable = true;
  11953. _this.showBoundingBox = false;
  11954. _this.showSubMeshesBoundingBox = false;
  11955. _this.isBlocker = false;
  11956. _this.enablePointerMoveEvents = false;
  11957. _this.renderingGroupId = 0;
  11958. _this._receiveShadows = false;
  11959. _this.renderOutline = false;
  11960. _this.outlineColor = BABYLON.Color3.Red();
  11961. _this.outlineWidth = 0.02;
  11962. _this.renderOverlay = false;
  11963. _this.overlayColor = BABYLON.Color3.Red();
  11964. _this.overlayAlpha = 0.5;
  11965. _this._hasVertexAlpha = false;
  11966. _this._useVertexColors = true;
  11967. _this._computeBonesUsingShaders = true;
  11968. _this._numBoneInfluencers = 4;
  11969. _this._applyFog = true;
  11970. _this.scalingDeterminant = 1;
  11971. _this.useOctreeForRenderingSelection = true;
  11972. _this.useOctreeForPicking = true;
  11973. _this.useOctreeForCollisions = true;
  11974. _this._layerMask = 0x0FFFFFFF;
  11975. /**
  11976. * True if the mesh must be rendered in any case.
  11977. */
  11978. _this.alwaysSelectAsActiveMesh = false;
  11979. // Collisions
  11980. _this._checkCollisions = false;
  11981. _this._collisionMask = -1;
  11982. _this._collisionGroup = -1;
  11983. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11984. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11985. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11986. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11987. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11988. // Edges
  11989. _this.edgesWidth = 1;
  11990. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11991. // Cache
  11992. _this._localWorld = BABYLON.Matrix.Zero();
  11993. _this._worldMatrix = BABYLON.Matrix.Zero();
  11994. _this._absolutePosition = BABYLON.Vector3.Zero();
  11995. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11996. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11997. _this._isDirty = false;
  11998. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11999. _this._isDisposed = false;
  12000. _this._renderId = 0;
  12001. _this._intersectionsInProgress = new Array();
  12002. _this._isWorldMatrixFrozen = false;
  12003. _this._unIndexed = false;
  12004. _this._lightSources = new Array();
  12005. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12006. if (collidedMesh === void 0) { collidedMesh = null; }
  12007. //TODO move this to the collision coordinator!
  12008. if (_this.getScene().workerCollisions)
  12009. newPosition.multiplyInPlace(_this._collider.radius);
  12010. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12011. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12012. _this.position.addInPlace(_this._diffPositionForCollisions);
  12013. }
  12014. if (collidedMesh) {
  12015. _this.onCollideObservable.notifyObservers(collidedMesh);
  12016. }
  12017. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12018. };
  12019. _this.getScene().addMesh(_this);
  12020. _this._resyncLightSources();
  12021. return _this;
  12022. }
  12023. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12024. get: function () {
  12025. return AbstractMesh._BILLBOARDMODE_NONE;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12031. get: function () {
  12032. return AbstractMesh._BILLBOARDMODE_X;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12038. get: function () {
  12039. return AbstractMesh._BILLBOARDMODE_Y;
  12040. },
  12041. enumerable: true,
  12042. configurable: true
  12043. });
  12044. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12045. get: function () {
  12046. return AbstractMesh._BILLBOARDMODE_Z;
  12047. },
  12048. enumerable: true,
  12049. configurable: true
  12050. });
  12051. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12052. get: function () {
  12053. return AbstractMesh._BILLBOARDMODE_ALL;
  12054. },
  12055. enumerable: true,
  12056. configurable: true
  12057. });
  12058. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12059. /**
  12060. * Read-only : the number of facets in the mesh
  12061. */
  12062. get: function () {
  12063. return this._facetNb;
  12064. },
  12065. enumerable: true,
  12066. configurable: true
  12067. });
  12068. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12069. /**
  12070. * The number (integer) of subdivisions per axis in the partioning space
  12071. */
  12072. get: function () {
  12073. return this._partitioningSubdivisions;
  12074. },
  12075. set: function (nb) {
  12076. this._partitioningSubdivisions = nb;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12082. /**
  12083. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12084. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12085. */
  12086. get: function () {
  12087. return this._partitioningBBoxRatio;
  12088. },
  12089. set: function (ratio) {
  12090. this._partitioningBBoxRatio = ratio;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12096. /**
  12097. * Read-only boolean : is the feature facetData enabled ?
  12098. */
  12099. get: function () {
  12100. return this._facetDataEnabled;
  12101. },
  12102. enumerable: true,
  12103. configurable: true
  12104. });
  12105. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12106. set: function (callback) {
  12107. if (this._onCollideObserver) {
  12108. this.onCollideObservable.remove(this._onCollideObserver);
  12109. }
  12110. this._onCollideObserver = this.onCollideObservable.add(callback);
  12111. },
  12112. enumerable: true,
  12113. configurable: true
  12114. });
  12115. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12116. set: function (callback) {
  12117. if (this._onCollisionPositionChangeObserver) {
  12118. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12119. }
  12120. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12121. },
  12122. enumerable: true,
  12123. configurable: true
  12124. });
  12125. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12126. /**
  12127. * 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.
  12128. */
  12129. get: function () {
  12130. return this._isOccluded;
  12131. },
  12132. set: function (value) {
  12133. this._isOccluded = value;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12139. /**
  12140. * Flag to check the progress status of the query
  12141. */
  12142. get: function () {
  12143. return this._isOcclusionQueryInProgress;
  12144. },
  12145. enumerable: true,
  12146. configurable: true
  12147. });
  12148. Object.defineProperty(AbstractMesh.prototype, "material", {
  12149. get: function () {
  12150. return this._material;
  12151. },
  12152. set: function (value) {
  12153. if (this._material === value) {
  12154. return;
  12155. }
  12156. this._material = value;
  12157. if (this.onMaterialChangedObservable.hasObservers) {
  12158. this.onMaterialChangedObservable.notifyObservers(this);
  12159. }
  12160. if (!this.subMeshes) {
  12161. return;
  12162. }
  12163. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12164. var subMesh = _a[_i];
  12165. subMesh.setEffect(null);
  12166. }
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12172. get: function () {
  12173. return this._receiveShadows;
  12174. },
  12175. set: function (value) {
  12176. if (this._receiveShadows === value) {
  12177. return;
  12178. }
  12179. this._receiveShadows = value;
  12180. this._markSubMeshesAsLightDirty();
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12186. get: function () {
  12187. return this._hasVertexAlpha;
  12188. },
  12189. set: function (value) {
  12190. if (this._hasVertexAlpha === value) {
  12191. return;
  12192. }
  12193. this._hasVertexAlpha = value;
  12194. this._markSubMeshesAsAttributesDirty();
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12200. get: function () {
  12201. return this._useVertexColors;
  12202. },
  12203. set: function (value) {
  12204. if (this._useVertexColors === value) {
  12205. return;
  12206. }
  12207. this._useVertexColors = value;
  12208. this._markSubMeshesAsAttributesDirty();
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12214. get: function () {
  12215. return this._computeBonesUsingShaders;
  12216. },
  12217. set: function (value) {
  12218. if (this._computeBonesUsingShaders === value) {
  12219. return;
  12220. }
  12221. this._computeBonesUsingShaders = value;
  12222. this._markSubMeshesAsAttributesDirty();
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12228. get: function () {
  12229. return this._numBoneInfluencers;
  12230. },
  12231. set: function (value) {
  12232. if (this._numBoneInfluencers === value) {
  12233. return;
  12234. }
  12235. this._numBoneInfluencers = value;
  12236. this._markSubMeshesAsAttributesDirty();
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12242. get: function () {
  12243. return this._applyFog;
  12244. },
  12245. set: function (value) {
  12246. if (this._applyFog === value) {
  12247. return;
  12248. }
  12249. this._applyFog = value;
  12250. this._markSubMeshesAsMiscDirty();
  12251. },
  12252. enumerable: true,
  12253. configurable: true
  12254. });
  12255. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12256. get: function () {
  12257. return this._layerMask;
  12258. },
  12259. set: function (value) {
  12260. if (value === this._layerMask) {
  12261. return;
  12262. }
  12263. this._layerMask = value;
  12264. this._resyncLightSources();
  12265. },
  12266. enumerable: true,
  12267. configurable: true
  12268. });
  12269. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12270. get: function () {
  12271. return this._collisionMask;
  12272. },
  12273. set: function (mask) {
  12274. this._collisionMask = !isNaN(mask) ? mask : -1;
  12275. },
  12276. enumerable: true,
  12277. configurable: true
  12278. });
  12279. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12280. get: function () {
  12281. return this._collisionGroup;
  12282. },
  12283. set: function (mask) {
  12284. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12285. },
  12286. enumerable: true,
  12287. configurable: true
  12288. });
  12289. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12290. get: function () {
  12291. return null;
  12292. },
  12293. enumerable: true,
  12294. configurable: true
  12295. });
  12296. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12297. get: function () {
  12298. return this._skeleton;
  12299. },
  12300. set: function (value) {
  12301. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12302. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12303. }
  12304. if (value && value.needInitialSkinMatrix) {
  12305. value._registerMeshWithPoseMatrix(this);
  12306. }
  12307. this._skeleton = value;
  12308. if (!this._skeleton) {
  12309. this._bonesTransformMatrices = null;
  12310. }
  12311. this._markSubMeshesAsAttributesDirty();
  12312. },
  12313. enumerable: true,
  12314. configurable: true
  12315. });
  12316. /**
  12317. * Boolean : true if the mesh has been disposed.
  12318. */
  12319. AbstractMesh.prototype.isDisposed = function () {
  12320. return this._isDisposed;
  12321. };
  12322. /**
  12323. * Returns the string "AbstractMesh"
  12324. */
  12325. AbstractMesh.prototype.getClassName = function () {
  12326. return "AbstractMesh";
  12327. };
  12328. /**
  12329. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12330. */
  12331. AbstractMesh.prototype.toString = function (fullDetails) {
  12332. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12333. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12334. if (this._skeleton) {
  12335. ret += ", skeleton: " + this._skeleton.name;
  12336. }
  12337. if (fullDetails) {
  12338. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12339. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12340. }
  12341. return ret;
  12342. };
  12343. AbstractMesh.prototype._rebuild = function () {
  12344. if (this._occlusionQuery) {
  12345. this._occlusionQuery = null;
  12346. }
  12347. if (this._edgesRenderer) {
  12348. this._edgesRenderer._rebuild();
  12349. }
  12350. if (!this.subMeshes) {
  12351. return;
  12352. }
  12353. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12354. var subMesh = _a[_i];
  12355. subMesh._rebuild();
  12356. }
  12357. };
  12358. AbstractMesh.prototype._resyncLightSources = function () {
  12359. this._lightSources.length = 0;
  12360. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12361. var light = _a[_i];
  12362. if (!light.isEnabled()) {
  12363. continue;
  12364. }
  12365. if (light.canAffectMesh(this)) {
  12366. this._lightSources.push(light);
  12367. }
  12368. }
  12369. this._markSubMeshesAsLightDirty();
  12370. };
  12371. AbstractMesh.prototype._resyncLighSource = function (light) {
  12372. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12373. var index = this._lightSources.indexOf(light);
  12374. if (index === -1) {
  12375. if (!isIn) {
  12376. return;
  12377. }
  12378. this._lightSources.push(light);
  12379. }
  12380. else {
  12381. if (isIn) {
  12382. return;
  12383. }
  12384. this._lightSources.splice(index, 1);
  12385. }
  12386. this._markSubMeshesAsLightDirty();
  12387. };
  12388. AbstractMesh.prototype._removeLightSource = function (light) {
  12389. var index = this._lightSources.indexOf(light);
  12390. if (index === -1) {
  12391. return;
  12392. }
  12393. this._lightSources.splice(index, 1);
  12394. };
  12395. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12396. if (!this.subMeshes) {
  12397. return;
  12398. }
  12399. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12400. var subMesh = _a[_i];
  12401. if (subMesh._materialDefines) {
  12402. func(subMesh._materialDefines);
  12403. }
  12404. }
  12405. };
  12406. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12407. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12408. };
  12409. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12410. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12411. };
  12412. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12413. if (!this.subMeshes) {
  12414. return;
  12415. }
  12416. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12417. var subMesh = _a[_i];
  12418. var material = subMesh.getMaterial();
  12419. if (material) {
  12420. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12421. }
  12422. }
  12423. };
  12424. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12425. /**
  12426. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12427. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12428. * Default : (0.0, 0.0, 0.0)
  12429. */
  12430. get: function () {
  12431. return this._rotation;
  12432. },
  12433. set: function (newRotation) {
  12434. this._rotation = newRotation;
  12435. },
  12436. enumerable: true,
  12437. configurable: true
  12438. });
  12439. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12440. /**
  12441. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12442. * Default : (1.0, 1.0, 1.0)
  12443. */
  12444. get: function () {
  12445. return this._scaling;
  12446. },
  12447. set: function (newScaling) {
  12448. this._scaling = newScaling;
  12449. if (this.physicsImpostor) {
  12450. this.physicsImpostor.forceUpdate();
  12451. }
  12452. },
  12453. enumerable: true,
  12454. configurable: true
  12455. });
  12456. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12457. /**
  12458. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12459. * It's null by default.
  12460. * 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)
  12461. */
  12462. get: function () {
  12463. return this._rotationQuaternion;
  12464. },
  12465. set: function (quaternion) {
  12466. this._rotationQuaternion = quaternion;
  12467. //reset the rotation vector.
  12468. if (quaternion && this.rotation.length()) {
  12469. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12470. }
  12471. },
  12472. enumerable: true,
  12473. configurable: true
  12474. });
  12475. // Methods
  12476. /**
  12477. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12478. * Returns the AbstractMesh.
  12479. */
  12480. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12481. this._poseMatrix.copyFrom(matrix);
  12482. return this;
  12483. };
  12484. /**
  12485. * Returns the mesh Pose matrix.
  12486. * Returned object : Matrix
  12487. */
  12488. AbstractMesh.prototype.getPoseMatrix = function () {
  12489. return this._poseMatrix;
  12490. };
  12491. /**
  12492. * Disables the mesh edger rendering mode.
  12493. * Returns the AbstractMesh.
  12494. */
  12495. AbstractMesh.prototype.disableEdgesRendering = function () {
  12496. if (this._edgesRenderer !== undefined) {
  12497. this._edgesRenderer.dispose();
  12498. this._edgesRenderer = undefined;
  12499. }
  12500. return this;
  12501. };
  12502. /**
  12503. * Enables the edge rendering mode on the mesh.
  12504. * This mode makes the mesh edges visible.
  12505. * Returns the AbstractMesh.
  12506. */
  12507. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12508. if (epsilon === void 0) { epsilon = 0.95; }
  12509. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12510. this.disableEdgesRendering();
  12511. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12512. return this;
  12513. };
  12514. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12515. /**
  12516. * Returns true if the mesh is blocked. Used by the class Mesh.
  12517. * Returns the boolean `false` by default.
  12518. */
  12519. get: function () {
  12520. return false;
  12521. },
  12522. enumerable: true,
  12523. configurable: true
  12524. });
  12525. /**
  12526. * Returns the mesh itself by default, used by the class Mesh.
  12527. * Returned type : AbstractMesh
  12528. */
  12529. AbstractMesh.prototype.getLOD = function (camera) {
  12530. return this;
  12531. };
  12532. /**
  12533. * Returns 0 by default, used by the class Mesh.
  12534. * Returns an integer.
  12535. */
  12536. AbstractMesh.prototype.getTotalVertices = function () {
  12537. return 0;
  12538. };
  12539. /**
  12540. * Returns null by default, used by the class Mesh.
  12541. * Returned type : integer array
  12542. */
  12543. AbstractMesh.prototype.getIndices = function () {
  12544. return null;
  12545. };
  12546. /**
  12547. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12548. * Returned type : float array or Float32Array
  12549. */
  12550. AbstractMesh.prototype.getVerticesData = function (kind) {
  12551. return null;
  12552. };
  12553. /**
  12554. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12555. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12556. * The `data` are either a numeric array either a Float32Array.
  12557. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12558. * 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).
  12559. * Note that a new underlying VertexBuffer object is created each call.
  12560. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12561. *
  12562. * Possible `kind` values :
  12563. * - BABYLON.VertexBuffer.PositionKind
  12564. * - BABYLON.VertexBuffer.UVKind
  12565. * - BABYLON.VertexBuffer.UV2Kind
  12566. * - BABYLON.VertexBuffer.UV3Kind
  12567. * - BABYLON.VertexBuffer.UV4Kind
  12568. * - BABYLON.VertexBuffer.UV5Kind
  12569. * - BABYLON.VertexBuffer.UV6Kind
  12570. * - BABYLON.VertexBuffer.ColorKind
  12571. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12572. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12573. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12574. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12575. *
  12576. * Returns the Mesh.
  12577. */
  12578. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12579. return null;
  12580. };
  12581. /**
  12582. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12583. * If the mesh has no geometry, it is simply returned as it is.
  12584. * The `data` are either a numeric array either a Float32Array.
  12585. * No new underlying VertexBuffer object is created.
  12586. * 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.
  12587. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12588. *
  12589. * Possible `kind` values :
  12590. * - BABYLON.VertexBuffer.PositionKind
  12591. * - BABYLON.VertexBuffer.UVKind
  12592. * - BABYLON.VertexBuffer.UV2Kind
  12593. * - BABYLON.VertexBuffer.UV3Kind
  12594. * - BABYLON.VertexBuffer.UV4Kind
  12595. * - BABYLON.VertexBuffer.UV5Kind
  12596. * - BABYLON.VertexBuffer.UV6Kind
  12597. * - BABYLON.VertexBuffer.ColorKind
  12598. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12599. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12600. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12601. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12602. *
  12603. * Returns the Mesh.
  12604. */
  12605. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12606. return null;
  12607. };
  12608. /**
  12609. * Sets the mesh indices.
  12610. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12611. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12612. * This method creates a new index buffer each call.
  12613. * Returns the Mesh.
  12614. */
  12615. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12616. return null;
  12617. };
  12618. /** Returns false by default, used by the class Mesh.
  12619. * Returns a boolean
  12620. */
  12621. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12622. return false;
  12623. };
  12624. /**
  12625. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12626. * Returns a BoundingInfo
  12627. */
  12628. AbstractMesh.prototype.getBoundingInfo = function () {
  12629. if (this._masterMesh) {
  12630. return this._masterMesh.getBoundingInfo();
  12631. }
  12632. if (!this._boundingInfo) {
  12633. this._updateBoundingInfo();
  12634. }
  12635. return this._boundingInfo;
  12636. };
  12637. /**
  12638. * Sets a mesh new object BoundingInfo.
  12639. * Returns the AbstractMesh.
  12640. */
  12641. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12642. this._boundingInfo = boundingInfo;
  12643. return this;
  12644. };
  12645. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12646. get: function () {
  12647. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. AbstractMesh.prototype._preActivate = function () {
  12653. };
  12654. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12655. };
  12656. AbstractMesh.prototype._activate = function (renderId) {
  12657. this._renderId = renderId;
  12658. };
  12659. /**
  12660. * Returns the last update of the World matrix
  12661. * Returns a Matrix.
  12662. */
  12663. AbstractMesh.prototype.getWorldMatrix = function () {
  12664. if (this._masterMesh) {
  12665. return this._masterMesh.getWorldMatrix();
  12666. }
  12667. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12668. this.computeWorldMatrix();
  12669. }
  12670. return this._worldMatrix;
  12671. };
  12672. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12673. /**
  12674. * Returns directly the last state of the mesh World matrix.
  12675. * A Matrix is returned.
  12676. */
  12677. get: function () {
  12678. return this._worldMatrix;
  12679. },
  12680. enumerable: true,
  12681. configurable: true
  12682. });
  12683. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12684. /**
  12685. * Returns the current mesh absolute position.
  12686. * Retuns a Vector3.
  12687. */
  12688. get: function () {
  12689. return this._absolutePosition;
  12690. },
  12691. enumerable: true,
  12692. configurable: true
  12693. });
  12694. /**
  12695. * Prevents the World matrix to be computed any longer.
  12696. * Returns the AbstractMesh.
  12697. */
  12698. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12699. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12700. this.computeWorldMatrix(true);
  12701. this._isWorldMatrixFrozen = true;
  12702. return this;
  12703. };
  12704. /**
  12705. * Allows back the World matrix computation.
  12706. * Returns the AbstractMesh.
  12707. */
  12708. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12709. this._isWorldMatrixFrozen = false;
  12710. this.computeWorldMatrix(true);
  12711. return this;
  12712. };
  12713. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12714. /**
  12715. * True if the World matrix has been frozen.
  12716. * Returns a boolean.
  12717. */
  12718. get: function () {
  12719. return this._isWorldMatrixFrozen;
  12720. },
  12721. enumerable: true,
  12722. configurable: true
  12723. });
  12724. /**
  12725. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12726. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12727. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12728. * The passed axis is also normalized.
  12729. * Returns the AbstractMesh.
  12730. */
  12731. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12732. axis.normalize();
  12733. if (!this.rotationQuaternion) {
  12734. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12735. this.rotation = BABYLON.Vector3.Zero();
  12736. }
  12737. var rotationQuaternion;
  12738. if (!space || space === BABYLON.Space.LOCAL) {
  12739. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12740. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12741. }
  12742. else {
  12743. if (this.parent) {
  12744. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12745. invertParentWorldMatrix.invert();
  12746. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12747. }
  12748. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12749. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12750. }
  12751. return this;
  12752. };
  12753. /**
  12754. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12755. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12756. * The passed axis is also normalized.
  12757. * Returns the AbstractMesh.
  12758. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12759. */
  12760. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12761. axis.normalize();
  12762. if (!this.rotationQuaternion) {
  12763. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12764. this.rotation.copyFromFloats(0, 0, 0);
  12765. }
  12766. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12767. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12768. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12769. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12770. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12771. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12772. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12773. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12774. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12775. return this;
  12776. };
  12777. /**
  12778. * Translates the mesh along the axis vector for the passed distance in the given space.
  12779. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12780. * Returns the AbstractMesh.
  12781. */
  12782. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12783. var displacementVector = axis.scale(distance);
  12784. if (!space || space === BABYLON.Space.LOCAL) {
  12785. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12786. this.setPositionWithLocalVector(tempV3);
  12787. }
  12788. else {
  12789. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12790. }
  12791. return this;
  12792. };
  12793. /**
  12794. * Adds a rotation step to the mesh current rotation.
  12795. * x, y, z are Euler angles expressed in radians.
  12796. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12797. * This means this rotation is made in the mesh local space only.
  12798. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12799. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12800. * ```javascript
  12801. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12802. * ```
  12803. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12804. * 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.
  12805. * Returns the AbstractMesh.
  12806. */
  12807. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12808. var rotationQuaternion;
  12809. if (this.rotationQuaternion) {
  12810. rotationQuaternion = this.rotationQuaternion;
  12811. }
  12812. else {
  12813. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12814. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12815. }
  12816. var accumulation = BABYLON.Tmp.Quaternion[0];
  12817. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12818. rotationQuaternion.multiplyInPlace(accumulation);
  12819. if (!this.rotationQuaternion) {
  12820. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12821. }
  12822. return this;
  12823. };
  12824. /**
  12825. * Retuns the mesh absolute position in the World.
  12826. * Returns a Vector3.
  12827. */
  12828. AbstractMesh.prototype.getAbsolutePosition = function () {
  12829. this.computeWorldMatrix();
  12830. return this._absolutePosition;
  12831. };
  12832. /**
  12833. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12834. * Returns the AbstractMesh.
  12835. */
  12836. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12837. if (!absolutePosition) {
  12838. return;
  12839. }
  12840. var absolutePositionX;
  12841. var absolutePositionY;
  12842. var absolutePositionZ;
  12843. if (absolutePosition.x === undefined) {
  12844. if (arguments.length < 3) {
  12845. return;
  12846. }
  12847. absolutePositionX = arguments[0];
  12848. absolutePositionY = arguments[1];
  12849. absolutePositionZ = arguments[2];
  12850. }
  12851. else {
  12852. absolutePositionX = absolutePosition.x;
  12853. absolutePositionY = absolutePosition.y;
  12854. absolutePositionZ = absolutePosition.z;
  12855. }
  12856. if (this.parent) {
  12857. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12858. invertParentWorldMatrix.invert();
  12859. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12860. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12861. }
  12862. else {
  12863. this.position.x = absolutePositionX;
  12864. this.position.y = absolutePositionY;
  12865. this.position.z = absolutePositionZ;
  12866. }
  12867. return this;
  12868. };
  12869. // ================================== Point of View Movement =================================
  12870. /**
  12871. * Perform relative position change from the point of view of behind the front of the mesh.
  12872. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12873. * Supports definition of mesh facing forward or backward.
  12874. * @param {number} amountRight
  12875. * @param {number} amountUp
  12876. * @param {number} amountForward
  12877. *
  12878. * Returns the AbstractMesh.
  12879. */
  12880. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12881. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12882. return this;
  12883. };
  12884. /**
  12885. * Calculate relative position change from the point of view of behind the front of the mesh.
  12886. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12887. * Supports definition of mesh facing forward or backward.
  12888. * @param {number} amountRight
  12889. * @param {number} amountUp
  12890. * @param {number} amountForward
  12891. *
  12892. * Returns a new Vector3.
  12893. */
  12894. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12895. var rotMatrix = new BABYLON.Matrix();
  12896. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12897. rotQuaternion.toRotationMatrix(rotMatrix);
  12898. var translationDelta = BABYLON.Vector3.Zero();
  12899. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12900. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12901. return translationDelta;
  12902. };
  12903. // ================================== Point of View Rotation =================================
  12904. /**
  12905. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12906. * Supports definition of mesh facing forward or backward.
  12907. * @param {number} flipBack
  12908. * @param {number} twirlClockwise
  12909. * @param {number} tiltRight
  12910. *
  12911. * Returns the AbstractMesh.
  12912. */
  12913. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12914. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12915. return this;
  12916. };
  12917. /**
  12918. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12919. * Supports definition of mesh facing forward or backward.
  12920. * @param {number} flipBack
  12921. * @param {number} twirlClockwise
  12922. * @param {number} tiltRight
  12923. *
  12924. * Returns a new Vector3.
  12925. */
  12926. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12927. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12928. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12929. };
  12930. /**
  12931. * Sets a new pivot matrix to the mesh.
  12932. * Returns the AbstractMesh.
  12933. */
  12934. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12935. this._pivotMatrix = matrix;
  12936. this._cache.pivotMatrixUpdated = true;
  12937. return this;
  12938. };
  12939. /**
  12940. * Returns the mesh pivot matrix.
  12941. * Default : Identity.
  12942. * A Matrix is returned.
  12943. */
  12944. AbstractMesh.prototype.getPivotMatrix = function () {
  12945. return this._pivotMatrix;
  12946. };
  12947. AbstractMesh.prototype._isSynchronized = function () {
  12948. if (this._isDirty) {
  12949. return false;
  12950. }
  12951. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12952. return false;
  12953. if (this._cache.pivotMatrixUpdated) {
  12954. return false;
  12955. }
  12956. if (this.infiniteDistance) {
  12957. return false;
  12958. }
  12959. if (!this._cache.position.equals(this.position))
  12960. return false;
  12961. if (this.rotationQuaternion) {
  12962. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12963. return false;
  12964. }
  12965. if (!this._cache.rotation.equals(this.rotation))
  12966. return false;
  12967. if (!this._cache.scaling.equals(this.scaling))
  12968. return false;
  12969. return true;
  12970. };
  12971. AbstractMesh.prototype._initCache = function () {
  12972. _super.prototype._initCache.call(this);
  12973. this._cache.localMatrixUpdated = false;
  12974. this._cache.position = BABYLON.Vector3.Zero();
  12975. this._cache.scaling = BABYLON.Vector3.Zero();
  12976. this._cache.rotation = BABYLON.Vector3.Zero();
  12977. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12978. this._cache.billboardMode = -1;
  12979. };
  12980. AbstractMesh.prototype.markAsDirty = function (property) {
  12981. if (property === "rotation") {
  12982. this.rotationQuaternion = null;
  12983. }
  12984. this._currentRenderId = Number.MAX_VALUE;
  12985. this._isDirty = true;
  12986. return this;
  12987. };
  12988. /**
  12989. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12990. * Returns the AbstractMesh.
  12991. */
  12992. AbstractMesh.prototype._updateBoundingInfo = function () {
  12993. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12994. this._boundingInfo.update(this.worldMatrixFromCache);
  12995. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12996. return this;
  12997. };
  12998. /**
  12999. * Update a mesh's children BoundingInfo objects only.
  13000. * Returns the AbstractMesh.
  13001. */
  13002. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13003. if (!this.subMeshes) {
  13004. return;
  13005. }
  13006. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13007. var subMesh = this.subMeshes[subIndex];
  13008. if (!subMesh.IsGlobal) {
  13009. subMesh.updateBoundingInfo(matrix);
  13010. }
  13011. }
  13012. return this;
  13013. };
  13014. /**
  13015. * Computes the mesh World matrix and returns it.
  13016. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13017. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13018. * If the parameter `force`is set to `true`, the actual computation is done.
  13019. * Returns the mesh World Matrix.
  13020. */
  13021. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13022. if (this._isWorldMatrixFrozen) {
  13023. return this._worldMatrix;
  13024. }
  13025. if (!force && this.isSynchronized(true)) {
  13026. this._currentRenderId = this.getScene().getRenderId();
  13027. return this._worldMatrix;
  13028. }
  13029. this._cache.position.copyFrom(this.position);
  13030. this._cache.scaling.copyFrom(this.scaling);
  13031. this._cache.pivotMatrixUpdated = false;
  13032. this._cache.billboardMode = this.billboardMode;
  13033. this._currentRenderId = this.getScene().getRenderId();
  13034. this._isDirty = false;
  13035. // Scaling
  13036. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13037. // Rotation
  13038. //rotate, if quaternion is set and rotation was used
  13039. if (this.rotationQuaternion) {
  13040. var len = this.rotation.length();
  13041. if (len) {
  13042. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13043. this.rotation.copyFromFloats(0, 0, 0);
  13044. }
  13045. }
  13046. if (this.rotationQuaternion) {
  13047. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13048. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13049. }
  13050. else {
  13051. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13052. this._cache.rotation.copyFrom(this.rotation);
  13053. }
  13054. // Translation
  13055. if (this.infiniteDistance && !this.parent) {
  13056. var camera = this.getScene().activeCamera;
  13057. if (camera) {
  13058. var cameraWorldMatrix = camera.getWorldMatrix();
  13059. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13060. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13061. }
  13062. }
  13063. else {
  13064. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13065. }
  13066. // Composing transformations
  13067. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13068. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13069. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13070. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13071. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13072. // Need to decompose each rotation here
  13073. var currentPosition = BABYLON.Tmp.Vector3[3];
  13074. if (this.parent && this.parent.getWorldMatrix) {
  13075. if (this._meshToBoneReferal) {
  13076. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13077. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13078. }
  13079. else {
  13080. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13081. }
  13082. }
  13083. else {
  13084. currentPosition.copyFrom(this.position);
  13085. }
  13086. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13087. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13088. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13089. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13090. }
  13091. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13092. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13093. }
  13094. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13095. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13096. }
  13097. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13098. }
  13099. else {
  13100. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13101. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13102. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13103. }
  13104. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13105. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13106. }
  13107. // Local world
  13108. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13109. // Parent
  13110. if (this.parent && this.parent.getWorldMatrix) {
  13111. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13112. if (this._meshToBoneReferal) {
  13113. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13114. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13115. }
  13116. else {
  13117. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13118. }
  13119. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13120. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13121. this._worldMatrix.copyFrom(this._localWorld);
  13122. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13123. }
  13124. else {
  13125. if (this._meshToBoneReferal) {
  13126. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13127. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13128. }
  13129. else {
  13130. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13131. }
  13132. }
  13133. this._markSyncedWithParent();
  13134. }
  13135. else {
  13136. this._worldMatrix.copyFrom(this._localWorld);
  13137. }
  13138. // Bounding info
  13139. this._updateBoundingInfo();
  13140. // Absolute position
  13141. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13142. // Callbacks
  13143. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13144. if (!this._poseMatrix) {
  13145. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13146. }
  13147. return this._worldMatrix;
  13148. };
  13149. /**
  13150. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13151. * @param func: callback function to add
  13152. *
  13153. * Returns the AbstractMesh.
  13154. */
  13155. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13156. this.onAfterWorldMatrixUpdateObservable.add(func);
  13157. return this;
  13158. };
  13159. /**
  13160. * Removes a registered callback function.
  13161. * Returns the AbstractMesh.
  13162. */
  13163. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13164. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13165. return this;
  13166. };
  13167. /**
  13168. * Sets the mesh position in its local space.
  13169. * Returns the AbstractMesh.
  13170. */
  13171. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13172. this.computeWorldMatrix();
  13173. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13174. return this;
  13175. };
  13176. /**
  13177. * Returns the mesh position in the local space from the current World matrix values.
  13178. * Returns a new Vector3.
  13179. */
  13180. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13181. this.computeWorldMatrix();
  13182. var invLocalWorldMatrix = this._localWorld.clone();
  13183. invLocalWorldMatrix.invert();
  13184. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13185. };
  13186. /**
  13187. * Translates the mesh along the passed Vector3 in its local space.
  13188. * Returns the AbstractMesh.
  13189. */
  13190. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13191. this.computeWorldMatrix(true);
  13192. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13193. return this;
  13194. };
  13195. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13196. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13197. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13198. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13199. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13200. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13201. /// <returns>Mesh oriented towards targetMesh</returns>
  13202. if (yawCor === void 0) { yawCor = 0; }
  13203. if (pitchCor === void 0) { pitchCor = 0; }
  13204. if (rollCor === void 0) { rollCor = 0; }
  13205. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13206. var dv = AbstractMesh._lookAtVectorCache;
  13207. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13208. targetPoint.subtractToRef(pos, dv);
  13209. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13210. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13211. var pitch = Math.atan2(dv.y, len);
  13212. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13213. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13214. return this;
  13215. };
  13216. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13217. this._meshToBoneReferal = affectedMesh;
  13218. this.parent = bone;
  13219. if (bone.getWorldMatrix().determinant() < 0) {
  13220. this.scalingDeterminant *= -1;
  13221. }
  13222. return this;
  13223. };
  13224. AbstractMesh.prototype.detachFromBone = function () {
  13225. if (this.parent.getWorldMatrix().determinant() < 0) {
  13226. this.scalingDeterminant *= -1;
  13227. }
  13228. this._meshToBoneReferal = null;
  13229. this.parent = null;
  13230. return this;
  13231. };
  13232. /**
  13233. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13234. * A mesh is in the frustum if its bounding box intersects the frustum.
  13235. * Boolean returned.
  13236. */
  13237. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13238. return this._boundingInfo.isInFrustum(frustumPlanes);
  13239. };
  13240. /**
  13241. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13242. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13243. * Boolean returned.
  13244. */
  13245. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13246. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13247. ;
  13248. };
  13249. /**
  13250. * True if the mesh intersects another mesh or a SolidParticle object.
  13251. * 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)
  13252. * Returns a boolean.
  13253. */
  13254. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13255. if (!this._boundingInfo || !mesh._boundingInfo) {
  13256. return false;
  13257. }
  13258. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13259. };
  13260. /**
  13261. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13262. * Returns a boolean.
  13263. */
  13264. AbstractMesh.prototype.intersectsPoint = function (point) {
  13265. if (!this._boundingInfo) {
  13266. return false;
  13267. }
  13268. return this._boundingInfo.intersectsPoint(point);
  13269. };
  13270. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13271. return this.physicsImpostor;
  13272. };
  13273. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13274. if (!camera) {
  13275. camera = this.getScene().activeCamera;
  13276. }
  13277. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13278. };
  13279. /**
  13280. * Returns the distance from the mesh to the active camera.
  13281. * Returns a float.
  13282. */
  13283. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13284. if (!camera) {
  13285. camera = this.getScene().activeCamera;
  13286. }
  13287. return this.absolutePosition.subtract(camera.position).length();
  13288. };
  13289. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13290. if (!this.physicsImpostor) {
  13291. return;
  13292. }
  13293. this.physicsImpostor.applyImpulse(force, contactPoint);
  13294. return this;
  13295. };
  13296. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13297. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13298. return;
  13299. }
  13300. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13301. mainPivot: pivot1,
  13302. connectedPivot: pivot2,
  13303. nativeParams: options
  13304. });
  13305. return this;
  13306. };
  13307. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13308. // Collisions
  13309. /**
  13310. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13311. * Default `false`.
  13312. */
  13313. get: function () {
  13314. return this._checkCollisions;
  13315. },
  13316. set: function (collisionEnabled) {
  13317. this._checkCollisions = collisionEnabled;
  13318. if (this.getScene().workerCollisions) {
  13319. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13320. }
  13321. },
  13322. enumerable: true,
  13323. configurable: true
  13324. });
  13325. AbstractMesh.prototype.moveWithCollisions = function (direction) {
  13326. var globalPosition = this.getAbsolutePosition();
  13327. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13328. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13329. if (!this._collider) {
  13330. this._collider = new BABYLON.Collider();
  13331. }
  13332. this._collider.radius = this.ellipsoid;
  13333. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, direction, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13334. return this;
  13335. };
  13336. // Submeshes octree
  13337. /**
  13338. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13339. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13340. * Returns an Octree of submeshes.
  13341. */
  13342. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13343. if (maxCapacity === void 0) { maxCapacity = 64; }
  13344. if (maxDepth === void 0) { maxDepth = 2; }
  13345. if (!this._submeshesOctree) {
  13346. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13347. }
  13348. this.computeWorldMatrix(true);
  13349. // Update octree
  13350. var bbox = this.getBoundingInfo().boundingBox;
  13351. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13352. return this._submeshesOctree;
  13353. };
  13354. // Collisions
  13355. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13356. this._generatePointsArray();
  13357. // Transformation
  13358. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13359. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13360. subMesh._lastColliderWorldVertices = [];
  13361. subMesh._trianglePlanes = [];
  13362. var start = subMesh.verticesStart;
  13363. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13364. for (var i = start; i < end; i++) {
  13365. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13366. }
  13367. }
  13368. // Collide
  13369. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13370. if (collider.collisionFound) {
  13371. collider.collidedMesh = this;
  13372. }
  13373. return this;
  13374. };
  13375. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13376. var subMeshes;
  13377. var len;
  13378. // Octrees
  13379. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13380. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13381. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13382. len = intersections.length;
  13383. subMeshes = intersections.data;
  13384. }
  13385. else {
  13386. subMeshes = this.subMeshes;
  13387. len = subMeshes.length;
  13388. }
  13389. for (var index = 0; index < len; index++) {
  13390. var subMesh = subMeshes[index];
  13391. // Bounding test
  13392. if (len > 1 && !subMesh._checkCollision(collider))
  13393. continue;
  13394. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13395. }
  13396. return this;
  13397. };
  13398. AbstractMesh.prototype._checkCollision = function (collider) {
  13399. // Bounding box test
  13400. if (!this._boundingInfo._checkCollision(collider))
  13401. return this;
  13402. // Transformation matrix
  13403. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13404. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13405. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13406. return this;
  13407. };
  13408. // Picking
  13409. AbstractMesh.prototype._generatePointsArray = function () {
  13410. return false;
  13411. };
  13412. /**
  13413. * Checks if the passed Ray intersects with the mesh.
  13414. * Returns an object PickingInfo.
  13415. */
  13416. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13417. var pickingInfo = new BABYLON.PickingInfo();
  13418. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13419. return pickingInfo;
  13420. }
  13421. if (!this._generatePointsArray()) {
  13422. return pickingInfo;
  13423. }
  13424. var intersectInfo = null;
  13425. // Octrees
  13426. var subMeshes;
  13427. var len;
  13428. if (this._submeshesOctree && this.useOctreeForPicking) {
  13429. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13430. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13431. len = intersections.length;
  13432. subMeshes = intersections.data;
  13433. }
  13434. else {
  13435. subMeshes = this.subMeshes;
  13436. len = subMeshes.length;
  13437. }
  13438. for (var index = 0; index < len; index++) {
  13439. var subMesh = subMeshes[index];
  13440. // Bounding test
  13441. if (len > 1 && !subMesh.canIntersects(ray))
  13442. continue;
  13443. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13444. if (currentIntersectInfo) {
  13445. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13446. intersectInfo = currentIntersectInfo;
  13447. intersectInfo.subMeshId = index;
  13448. if (fastCheck) {
  13449. break;
  13450. }
  13451. }
  13452. }
  13453. }
  13454. if (intersectInfo) {
  13455. // Get picked point
  13456. var world = this.getWorldMatrix();
  13457. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13458. var direction = ray.direction.clone();
  13459. direction = direction.scale(intersectInfo.distance);
  13460. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13461. var pickedPoint = worldOrigin.add(worldDirection);
  13462. // Return result
  13463. pickingInfo.hit = true;
  13464. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13465. pickingInfo.pickedPoint = pickedPoint;
  13466. pickingInfo.pickedMesh = this;
  13467. pickingInfo.bu = intersectInfo.bu;
  13468. pickingInfo.bv = intersectInfo.bv;
  13469. pickingInfo.faceId = intersectInfo.faceId;
  13470. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13471. return pickingInfo;
  13472. }
  13473. return pickingInfo;
  13474. };
  13475. /**
  13476. * Clones the mesh, used by the class Mesh.
  13477. * Just returns `null` for an AbstractMesh.
  13478. */
  13479. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13480. return null;
  13481. };
  13482. /**
  13483. * Disposes all the mesh submeshes.
  13484. * Returns the AbstractMesh.
  13485. */
  13486. AbstractMesh.prototype.releaseSubMeshes = function () {
  13487. if (this.subMeshes) {
  13488. while (this.subMeshes.length) {
  13489. this.subMeshes[0].dispose();
  13490. }
  13491. }
  13492. else {
  13493. this.subMeshes = new Array();
  13494. }
  13495. return this;
  13496. };
  13497. /**
  13498. * Disposes the AbstractMesh.
  13499. * Some internal references are kept for further use.
  13500. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13501. * Returns nothing.
  13502. */
  13503. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13504. var _this = this;
  13505. var index;
  13506. // Action manager
  13507. if (this.actionManager) {
  13508. this.actionManager.dispose();
  13509. this.actionManager = null;
  13510. }
  13511. // Skeleton
  13512. this.skeleton = null;
  13513. // Animations
  13514. this.getScene().stopAnimation(this);
  13515. // Physics
  13516. if (this.physicsImpostor) {
  13517. this.physicsImpostor.dispose();
  13518. }
  13519. // Intersections in progress
  13520. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13521. var other = this._intersectionsInProgress[index];
  13522. var pos = other._intersectionsInProgress.indexOf(this);
  13523. other._intersectionsInProgress.splice(pos, 1);
  13524. }
  13525. this._intersectionsInProgress = [];
  13526. // Lights
  13527. var lights = this.getScene().lights;
  13528. lights.forEach(function (light) {
  13529. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13530. if (meshIndex !== -1) {
  13531. light.includedOnlyMeshes.splice(meshIndex, 1);
  13532. }
  13533. meshIndex = light.excludedMeshes.indexOf(_this);
  13534. if (meshIndex !== -1) {
  13535. light.excludedMeshes.splice(meshIndex, 1);
  13536. }
  13537. // Shadow generators
  13538. var generator = light.getShadowGenerator();
  13539. if (generator) {
  13540. var shadowMap = generator.getShadowMap();
  13541. meshIndex = shadowMap.renderList.indexOf(_this);
  13542. if (meshIndex !== -1) {
  13543. shadowMap.renderList.splice(meshIndex, 1);
  13544. }
  13545. }
  13546. });
  13547. // Edges
  13548. if (this._edgesRenderer) {
  13549. this._edgesRenderer.dispose();
  13550. this._edgesRenderer = null;
  13551. }
  13552. // SubMeshes
  13553. if (this.getClassName() !== "InstancedMesh") {
  13554. this.releaseSubMeshes();
  13555. }
  13556. // Octree
  13557. var sceneOctree = this.getScene().selectionOctree;
  13558. if (sceneOctree) {
  13559. var index = sceneOctree.dynamicContent.indexOf(this);
  13560. if (index !== -1) {
  13561. sceneOctree.dynamicContent.splice(index, 1);
  13562. }
  13563. }
  13564. // Query
  13565. var engine = this.getScene().getEngine();
  13566. if (this._occlusionQuery) {
  13567. this._isOcclusionQueryInProgress = false;
  13568. engine.deleteQuery(this._occlusionQuery);
  13569. this._occlusionQuery = null;
  13570. }
  13571. // Engine
  13572. engine.wipeCaches();
  13573. // Remove from scene
  13574. this.getScene().removeMesh(this);
  13575. if (!doNotRecurse) {
  13576. // Particles
  13577. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13578. if (this.getScene().particleSystems[index].emitter === this) {
  13579. this.getScene().particleSystems[index].dispose();
  13580. index--;
  13581. }
  13582. }
  13583. // Children
  13584. var objects = this.getDescendants(true);
  13585. for (index = 0; index < objects.length; index++) {
  13586. objects[index].dispose();
  13587. }
  13588. }
  13589. else {
  13590. var childMeshes = this.getChildMeshes(true);
  13591. for (index = 0; index < childMeshes.length; index++) {
  13592. var child = childMeshes[index];
  13593. child.parent = null;
  13594. child.computeWorldMatrix(true);
  13595. }
  13596. }
  13597. // facet data
  13598. if (this._facetDataEnabled) {
  13599. this.disableFacetData();
  13600. }
  13601. this.onAfterWorldMatrixUpdateObservable.clear();
  13602. this.onCollideObservable.clear();
  13603. this.onCollisionPositionChangeObservable.clear();
  13604. this._isDisposed = true;
  13605. _super.prototype.dispose.call(this);
  13606. };
  13607. /**
  13608. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13609. * This Vector3 is expressed in the World space.
  13610. */
  13611. AbstractMesh.prototype.getDirection = function (localAxis) {
  13612. var result = BABYLON.Vector3.Zero();
  13613. this.getDirectionToRef(localAxis, result);
  13614. return result;
  13615. };
  13616. /**
  13617. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13618. * localAxis is expressed in the mesh local space.
  13619. * result is computed in the Wordl space from the mesh World matrix.
  13620. * Returns the AbstractMesh.
  13621. */
  13622. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13623. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13624. return this;
  13625. };
  13626. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13627. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13628. if (this.getScene().getRenderId() == 0) {
  13629. this.computeWorldMatrix(true);
  13630. }
  13631. var wm = this.getWorldMatrix();
  13632. if (space == BABYLON.Space.WORLD) {
  13633. var tmat = BABYLON.Tmp.Matrix[0];
  13634. wm.invertToRef(tmat);
  13635. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13636. }
  13637. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13638. this._pivotMatrix.m[12] = -point.x;
  13639. this._pivotMatrix.m[13] = -point.y;
  13640. this._pivotMatrix.m[14] = -point.z;
  13641. this._cache.pivotMatrixUpdated = true;
  13642. return this;
  13643. };
  13644. /**
  13645. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13646. */
  13647. AbstractMesh.prototype.getPivotPoint = function () {
  13648. var point = BABYLON.Vector3.Zero();
  13649. this.getPivotPointToRef(point);
  13650. return point;
  13651. };
  13652. /**
  13653. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13654. * Returns the AbstractMesh.
  13655. */
  13656. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13657. result.x = -this._pivotMatrix.m[12];
  13658. result.y = -this._pivotMatrix.m[13];
  13659. result.z = -this._pivotMatrix.m[14];
  13660. return this;
  13661. };
  13662. /**
  13663. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13664. */
  13665. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13666. var point = BABYLON.Vector3.Zero();
  13667. this.getAbsolutePivotPointToRef(point);
  13668. return point;
  13669. };
  13670. /**
  13671. * Defines the passed mesh as the parent of the current mesh.
  13672. * Returns the AbstractMesh.
  13673. */
  13674. AbstractMesh.prototype.setParent = function (mesh) {
  13675. var child = this;
  13676. var parent = mesh;
  13677. if (mesh == null) {
  13678. var rotation = BABYLON.Tmp.Quaternion[0];
  13679. var position = BABYLON.Tmp.Vector3[0];
  13680. var scale = BABYLON.Tmp.Vector3[1];
  13681. child.getWorldMatrix().decompose(scale, rotation, position);
  13682. if (child.rotationQuaternion) {
  13683. child.rotationQuaternion.copyFrom(rotation);
  13684. }
  13685. else {
  13686. rotation.toEulerAnglesToRef(child.rotation);
  13687. }
  13688. child.position.x = position.x;
  13689. child.position.y = position.y;
  13690. child.position.z = position.z;
  13691. }
  13692. else {
  13693. var rotation = BABYLON.Tmp.Quaternion[0];
  13694. var position = BABYLON.Tmp.Vector3[0];
  13695. var scale = BABYLON.Tmp.Vector3[1];
  13696. var m1 = BABYLON.Tmp.Matrix[0];
  13697. var m2 = BABYLON.Tmp.Matrix[1];
  13698. parent.getWorldMatrix().decompose(scale, rotation, position);
  13699. rotation.toRotationMatrix(m1);
  13700. m2.setTranslation(position);
  13701. m2.multiplyToRef(m1, m1);
  13702. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13703. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13704. m.decompose(scale, rotation, position);
  13705. if (child.rotationQuaternion) {
  13706. child.rotationQuaternion.copyFrom(rotation);
  13707. }
  13708. else {
  13709. rotation.toEulerAnglesToRef(child.rotation);
  13710. }
  13711. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13712. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13713. m.decompose(scale, rotation, position);
  13714. child.position.x = position.x;
  13715. child.position.y = position.y;
  13716. child.position.z = position.z;
  13717. }
  13718. child.parent = parent;
  13719. return this;
  13720. };
  13721. /**
  13722. * Adds the passed mesh as a child to the current mesh.
  13723. * Returns the AbstractMesh.
  13724. */
  13725. AbstractMesh.prototype.addChild = function (mesh) {
  13726. mesh.setParent(this);
  13727. return this;
  13728. };
  13729. /**
  13730. * Removes the passed mesh from the current mesh children list.
  13731. * Returns the AbstractMesh.
  13732. */
  13733. AbstractMesh.prototype.removeChild = function (mesh) {
  13734. mesh.setParent(null);
  13735. return this;
  13736. };
  13737. /**
  13738. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13739. * Returns the AbstractMesh.
  13740. */
  13741. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13742. result.x = this._pivotMatrix.m[12];
  13743. result.y = this._pivotMatrix.m[13];
  13744. result.z = this._pivotMatrix.m[14];
  13745. this.getPivotPointToRef(result);
  13746. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13747. return this;
  13748. };
  13749. // Facet data
  13750. /**
  13751. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13752. * Returns the AbstractMesh.
  13753. */
  13754. AbstractMesh.prototype._initFacetData = function () {
  13755. if (!this._facetNormals) {
  13756. this._facetNormals = new Array();
  13757. }
  13758. if (!this._facetPositions) {
  13759. this._facetPositions = new Array();
  13760. }
  13761. if (!this._facetPartitioning) {
  13762. this._facetPartitioning = new Array();
  13763. }
  13764. this._facetNb = this.getIndices().length / 3;
  13765. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13766. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13767. for (var f = 0; f < this._facetNb; f++) {
  13768. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13769. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13770. }
  13771. this._facetDataEnabled = true;
  13772. return this;
  13773. };
  13774. /**
  13775. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13776. * This method can be called within the render loop.
  13777. * 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.
  13778. * Returns the AbstractMesh.
  13779. */
  13780. AbstractMesh.prototype.updateFacetData = function () {
  13781. if (!this._facetDataEnabled) {
  13782. this._initFacetData();
  13783. }
  13784. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13785. var indices = this.getIndices();
  13786. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13787. var bInfo = this.getBoundingInfo();
  13788. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13789. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13790. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13791. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13792. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13793. this._subDiv.max = this._partitioningSubdivisions;
  13794. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13795. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13796. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13797. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13798. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13799. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13800. // set the parameters for ComputeNormals()
  13801. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13802. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13803. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13804. this._facetParameters.bInfo = bInfo;
  13805. this._facetParameters.bbSize = this._bbSize;
  13806. this._facetParameters.subDiv = this._subDiv;
  13807. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13808. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13809. return this;
  13810. };
  13811. /**
  13812. * Returns the facetLocalNormals array.
  13813. * The normals are expressed in the mesh local space.
  13814. */
  13815. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13816. if (!this._facetNormals) {
  13817. this.updateFacetData();
  13818. }
  13819. return this._facetNormals;
  13820. };
  13821. /**
  13822. * Returns the facetLocalPositions array.
  13823. * The facet positions are expressed in the mesh local space.
  13824. */
  13825. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13826. if (!this._facetPositions) {
  13827. this.updateFacetData();
  13828. }
  13829. return this._facetPositions;
  13830. };
  13831. /**
  13832. * Returns the facetLocalPartioning array.
  13833. */
  13834. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13835. if (!this._facetPartitioning) {
  13836. this.updateFacetData();
  13837. }
  13838. return this._facetPartitioning;
  13839. };
  13840. /**
  13841. * Returns the i-th facet position in the world system.
  13842. * This method allocates a new Vector3 per call.
  13843. */
  13844. AbstractMesh.prototype.getFacetPosition = function (i) {
  13845. var pos = BABYLON.Vector3.Zero();
  13846. this.getFacetPositionToRef(i, pos);
  13847. return pos;
  13848. };
  13849. /**
  13850. * Sets the reference Vector3 with the i-th facet position in the world system.
  13851. * Returns the AbstractMesh.
  13852. */
  13853. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13854. var localPos = (this.getFacetLocalPositions())[i];
  13855. var world = this.getWorldMatrix();
  13856. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13857. return this;
  13858. };
  13859. /**
  13860. * Returns the i-th facet normal in the world system.
  13861. * This method allocates a new Vector3 per call.
  13862. */
  13863. AbstractMesh.prototype.getFacetNormal = function (i) {
  13864. var norm = BABYLON.Vector3.Zero();
  13865. this.getFacetNormalToRef(i, norm);
  13866. return norm;
  13867. };
  13868. /**
  13869. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13870. * Returns the AbstractMesh.
  13871. */
  13872. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13873. var localNorm = (this.getFacetLocalNormals())[i];
  13874. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13875. return this;
  13876. };
  13877. /**
  13878. * 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).
  13879. */
  13880. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13881. var bInfo = this.getBoundingInfo();
  13882. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13883. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13884. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13885. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13886. return null;
  13887. }
  13888. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13889. };
  13890. /**
  13891. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13892. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13893. * 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.
  13894. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13895. * 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.
  13896. */
  13897. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13898. if (checkFace === void 0) { checkFace = false; }
  13899. if (facing === void 0) { facing = true; }
  13900. var world = this.getWorldMatrix();
  13901. var invMat = BABYLON.Tmp.Matrix[5];
  13902. world.invertToRef(invMat);
  13903. var invVect = BABYLON.Tmp.Vector3[8];
  13904. var closest = null;
  13905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13906. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13907. if (projected) {
  13908. // tranform the local computed projected vector to world coordinates
  13909. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13910. }
  13911. return closest;
  13912. };
  13913. /**
  13914. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13915. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13916. * 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.
  13917. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13918. * 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.
  13919. */
  13920. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13921. if (checkFace === void 0) { checkFace = false; }
  13922. if (facing === void 0) { facing = true; }
  13923. var closest = null;
  13924. var tmpx = 0.0;
  13925. var tmpy = 0.0;
  13926. var tmpz = 0.0;
  13927. var d = 0.0; // tmp dot facet normal * facet position
  13928. var t0 = 0.0;
  13929. var projx = 0.0;
  13930. var projy = 0.0;
  13931. var projz = 0.0;
  13932. // Get all the facets in the same partitioning block than (x, y, z)
  13933. var facetPositions = this.getFacetLocalPositions();
  13934. var facetNormals = this.getFacetLocalNormals();
  13935. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13936. if (!facetsInBlock) {
  13937. return null;
  13938. }
  13939. // Get the closest facet to (x, y, z)
  13940. var shortest = Number.MAX_VALUE; // init distance vars
  13941. var tmpDistance = shortest;
  13942. var fib; // current facet in the block
  13943. var norm; // current facet normal
  13944. var p0; // current facet barycenter position
  13945. // loop on all the facets in the current partitioning block
  13946. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13947. fib = facetsInBlock[idx];
  13948. norm = facetNormals[fib];
  13949. p0 = facetPositions[fib];
  13950. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13951. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13952. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13953. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13954. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13955. projx = x + norm.x * t0;
  13956. projy = y + norm.y * t0;
  13957. projz = z + norm.z * t0;
  13958. tmpx = projx - x;
  13959. tmpy = projy - y;
  13960. tmpz = projz - z;
  13961. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13962. if (tmpDistance < shortest) {
  13963. shortest = tmpDistance;
  13964. closest = fib;
  13965. if (projected) {
  13966. projected.x = projx;
  13967. projected.y = projy;
  13968. projected.z = projz;
  13969. }
  13970. }
  13971. }
  13972. }
  13973. return closest;
  13974. };
  13975. /**
  13976. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13977. */
  13978. AbstractMesh.prototype.getFacetDataParameters = function () {
  13979. return this._facetParameters;
  13980. };
  13981. /**
  13982. * Disables the feature FacetData and frees the related memory.
  13983. * Returns the AbstractMesh.
  13984. */
  13985. AbstractMesh.prototype.disableFacetData = function () {
  13986. if (this._facetDataEnabled) {
  13987. this._facetDataEnabled = false;
  13988. this._facetPositions = null;
  13989. this._facetNormals = null;
  13990. this._facetPartitioning = null;
  13991. this._facetParameters = null;
  13992. }
  13993. return this;
  13994. };
  13995. /**
  13996. * Creates new normals data for the mesh.
  13997. * @param updatable.
  13998. */
  13999. AbstractMesh.prototype.createNormals = function (updatable) {
  14000. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14001. var indices = this.getIndices();
  14002. var normals;
  14003. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14004. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14005. }
  14006. else {
  14007. normals = [];
  14008. }
  14009. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14010. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14011. };
  14012. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14013. var engine = this.getEngine();
  14014. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14015. this._isOccluded = false;
  14016. return;
  14017. }
  14018. if (this.isOcclusionQueryInProgress) {
  14019. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14020. if (isOcclusionQueryAvailable) {
  14021. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14022. this._isOcclusionQueryInProgress = false;
  14023. this._occlusionInternalRetryCounter = 0;
  14024. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14025. }
  14026. else {
  14027. this._occlusionInternalRetryCounter++;
  14028. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14029. this._isOcclusionQueryInProgress = false;
  14030. this._occlusionInternalRetryCounter = 0;
  14031. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14032. // if strict continue the last state of the object.
  14033. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14034. }
  14035. else {
  14036. return;
  14037. }
  14038. }
  14039. }
  14040. var scene = this.getScene();
  14041. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14042. if (!this._occlusionQuery) {
  14043. this._occlusionQuery = engine.createQuery();
  14044. }
  14045. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14046. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14047. engine.endQuery(this.occlusionQueryAlgorithmType);
  14048. this._isOcclusionQueryInProgress = true;
  14049. };
  14050. // Statics
  14051. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14052. AbstractMesh._BILLBOARDMODE_X = 1;
  14053. AbstractMesh._BILLBOARDMODE_Y = 2;
  14054. AbstractMesh._BILLBOARDMODE_Z = 4;
  14055. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14056. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14057. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14058. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14059. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14060. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14061. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14062. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14063. return AbstractMesh;
  14064. }(BABYLON.Node));
  14065. BABYLON.AbstractMesh = AbstractMesh;
  14066. })(BABYLON || (BABYLON = {}));
  14067. //# sourceMappingURL=babylon.abstractMesh.js.map
  14068. var BABYLON;
  14069. (function (BABYLON) {
  14070. var Light = (function (_super) {
  14071. __extends(Light, _super);
  14072. /**
  14073. * Creates a Light object in the scene.
  14074. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14075. */
  14076. function Light(name, scene) {
  14077. var _this = _super.call(this, name, scene) || this;
  14078. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14079. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14080. _this.intensity = 1.0;
  14081. _this.range = Number.MAX_VALUE;
  14082. /**
  14083. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14084. * of light.
  14085. */
  14086. _this._photometricScale = 1.0;
  14087. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14088. _this._radius = 0.00001;
  14089. _this.renderPriority = 0;
  14090. /**
  14091. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14092. * the current shadow generator.
  14093. */
  14094. _this.shadowEnabled = true;
  14095. _this._excludeWithLayerMask = 0;
  14096. _this._includeOnlyWithLayerMask = 0;
  14097. _this._lightmapMode = 0;
  14098. _this._excludedMeshesIds = new Array();
  14099. _this._includedOnlyMeshesIds = new Array();
  14100. _this.getScene().addLight(_this);
  14101. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14102. _this._buildUniformLayout();
  14103. _this.includedOnlyMeshes = new Array();
  14104. _this.excludedMeshes = new Array();
  14105. _this._resyncMeshes();
  14106. return _this;
  14107. }
  14108. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14109. /**
  14110. * If every light affecting the material is in this lightmapMode,
  14111. * material.lightmapTexture adds or multiplies
  14112. * (depends on material.useLightmapAsShadowmap)
  14113. * after every other light calculations.
  14114. */
  14115. get: function () {
  14116. return Light._LIGHTMAP_DEFAULT;
  14117. },
  14118. enumerable: true,
  14119. configurable: true
  14120. });
  14121. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14122. /**
  14123. * material.lightmapTexture as only diffuse lighting from this light
  14124. * adds pnly specular lighting from this light
  14125. * adds dynamic shadows
  14126. */
  14127. get: function () {
  14128. return Light._LIGHTMAP_SPECULAR;
  14129. },
  14130. enumerable: true,
  14131. configurable: true
  14132. });
  14133. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14134. /**
  14135. * material.lightmapTexture as only lighting
  14136. * no light calculation from this light
  14137. * only adds dynamic shadows from this light
  14138. */
  14139. get: function () {
  14140. return Light._LIGHTMAP_SHADOWSONLY;
  14141. },
  14142. enumerable: true,
  14143. configurable: true
  14144. });
  14145. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14146. /**
  14147. * Each light type uses the default quantity according to its type:
  14148. * point/spot lights use luminous intensity
  14149. * directional lights use illuminance
  14150. */
  14151. get: function () {
  14152. return Light._INTENSITYMODE_AUTOMATIC;
  14153. },
  14154. enumerable: true,
  14155. configurable: true
  14156. });
  14157. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14158. /**
  14159. * lumen (lm)
  14160. */
  14161. get: function () {
  14162. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14163. },
  14164. enumerable: true,
  14165. configurable: true
  14166. });
  14167. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14168. /**
  14169. * candela (lm/sr)
  14170. */
  14171. get: function () {
  14172. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14173. },
  14174. enumerable: true,
  14175. configurable: true
  14176. });
  14177. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14178. /**
  14179. * lux (lm/m^2)
  14180. */
  14181. get: function () {
  14182. return Light._INTENSITYMODE_ILLUMINANCE;
  14183. },
  14184. enumerable: true,
  14185. configurable: true
  14186. });
  14187. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14188. /**
  14189. * nit (cd/m^2)
  14190. */
  14191. get: function () {
  14192. return Light._INTENSITYMODE_LUMINANCE;
  14193. },
  14194. enumerable: true,
  14195. configurable: true
  14196. });
  14197. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14198. /**
  14199. * Light type const id of the point light.
  14200. */
  14201. get: function () {
  14202. return Light._LIGHTTYPEID_POINTLIGHT;
  14203. },
  14204. enumerable: true,
  14205. configurable: true
  14206. });
  14207. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14208. /**
  14209. * Light type const id of the directional light.
  14210. */
  14211. get: function () {
  14212. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14213. },
  14214. enumerable: true,
  14215. configurable: true
  14216. });
  14217. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14218. /**
  14219. * Light type const id of the spot light.
  14220. */
  14221. get: function () {
  14222. return Light._LIGHTTYPEID_SPOTLIGHT;
  14223. },
  14224. enumerable: true,
  14225. configurable: true
  14226. });
  14227. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14228. /**
  14229. * Light type const id of the hemispheric light.
  14230. */
  14231. get: function () {
  14232. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14233. },
  14234. enumerable: true,
  14235. configurable: true
  14236. });
  14237. Object.defineProperty(Light.prototype, "intensityMode", {
  14238. /**
  14239. * Gets the photometric scale used to interpret the intensity.
  14240. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14241. */
  14242. get: function () {
  14243. return this._intensityMode;
  14244. },
  14245. /**
  14246. * Sets the photometric scale used to interpret the intensity.
  14247. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14248. */
  14249. set: function (value) {
  14250. this._intensityMode = value;
  14251. this._computePhotometricScale();
  14252. },
  14253. enumerable: true,
  14254. configurable: true
  14255. });
  14256. ;
  14257. ;
  14258. Object.defineProperty(Light.prototype, "radius", {
  14259. /**
  14260. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14261. */
  14262. get: function () {
  14263. return this._radius;
  14264. },
  14265. /**
  14266. * sets the light radius used by PBR Materials to simulate soft area lights.
  14267. */
  14268. set: function (value) {
  14269. this._radius = value;
  14270. this._computePhotometricScale();
  14271. },
  14272. enumerable: true,
  14273. configurable: true
  14274. });
  14275. ;
  14276. ;
  14277. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14278. get: function () {
  14279. return this._includedOnlyMeshes;
  14280. },
  14281. set: function (value) {
  14282. this._includedOnlyMeshes = value;
  14283. this._hookArrayForIncludedOnly(value);
  14284. },
  14285. enumerable: true,
  14286. configurable: true
  14287. });
  14288. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14289. get: function () {
  14290. return this._excludedMeshes;
  14291. },
  14292. set: function (value) {
  14293. this._excludedMeshes = value;
  14294. this._hookArrayForExcluded(value);
  14295. },
  14296. enumerable: true,
  14297. configurable: true
  14298. });
  14299. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14300. get: function () {
  14301. return this._excludeWithLayerMask;
  14302. },
  14303. set: function (value) {
  14304. this._excludeWithLayerMask = value;
  14305. this._resyncMeshes();
  14306. },
  14307. enumerable: true,
  14308. configurable: true
  14309. });
  14310. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14311. get: function () {
  14312. return this._includeOnlyWithLayerMask;
  14313. },
  14314. set: function (value) {
  14315. this._includeOnlyWithLayerMask = value;
  14316. this._resyncMeshes();
  14317. },
  14318. enumerable: true,
  14319. configurable: true
  14320. });
  14321. Object.defineProperty(Light.prototype, "lightmapMode", {
  14322. get: function () {
  14323. return this._lightmapMode;
  14324. },
  14325. set: function (value) {
  14326. if (this._lightmapMode === value) {
  14327. return;
  14328. }
  14329. this._lightmapMode = value;
  14330. this._markMeshesAsLightDirty();
  14331. },
  14332. enumerable: true,
  14333. configurable: true
  14334. });
  14335. Light.prototype._buildUniformLayout = function () {
  14336. // Overridden
  14337. };
  14338. /**
  14339. * Returns the string "Light".
  14340. */
  14341. Light.prototype.getClassName = function () {
  14342. return "Light";
  14343. };
  14344. /**
  14345. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14346. */
  14347. Light.prototype.toString = function (fullDetails) {
  14348. var ret = "Name: " + this.name;
  14349. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14350. if (this.animations) {
  14351. for (var i = 0; i < this.animations.length; i++) {
  14352. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14353. }
  14354. }
  14355. if (fullDetails) {
  14356. }
  14357. return ret;
  14358. };
  14359. /**
  14360. * Set the enabled state of this node.
  14361. * @param {boolean} value - the new enabled state
  14362. * @see isEnabled
  14363. */
  14364. Light.prototype.setEnabled = function (value) {
  14365. _super.prototype.setEnabled.call(this, value);
  14366. this._resyncMeshes();
  14367. };
  14368. /**
  14369. * Returns the Light associated shadow generator.
  14370. */
  14371. Light.prototype.getShadowGenerator = function () {
  14372. return this._shadowGenerator;
  14373. };
  14374. /**
  14375. * Returns a Vector3, the absolute light position in the World.
  14376. */
  14377. Light.prototype.getAbsolutePosition = function () {
  14378. return BABYLON.Vector3.Zero();
  14379. };
  14380. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14381. };
  14382. Light.prototype._getWorldMatrix = function () {
  14383. return BABYLON.Matrix.Identity();
  14384. };
  14385. /**
  14386. * Boolean : True if the light will affect the passed mesh.
  14387. */
  14388. Light.prototype.canAffectMesh = function (mesh) {
  14389. if (!mesh) {
  14390. return true;
  14391. }
  14392. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14393. return false;
  14394. }
  14395. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14396. return false;
  14397. }
  14398. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14399. return false;
  14400. }
  14401. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14402. return false;
  14403. }
  14404. return true;
  14405. };
  14406. /**
  14407. * Returns the light World matrix.
  14408. */
  14409. Light.prototype.getWorldMatrix = function () {
  14410. this._currentRenderId = this.getScene().getRenderId();
  14411. var worldMatrix = this._getWorldMatrix();
  14412. if (this.parent && this.parent.getWorldMatrix) {
  14413. if (!this._parentedWorldMatrix) {
  14414. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14415. }
  14416. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14417. this._markSyncedWithParent();
  14418. return this._parentedWorldMatrix;
  14419. }
  14420. return worldMatrix;
  14421. };
  14422. /**
  14423. * Sort function to order lights for rendering.
  14424. * @param a First Light object to compare to second.
  14425. * @param b Second Light object to compare first.
  14426. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14427. */
  14428. Light.compareLightsPriority = function (a, b) {
  14429. //shadow-casting lights have priority over non-shadow-casting lights
  14430. //the renderPrioirty is a secondary sort criterion
  14431. if (a.shadowEnabled !== b.shadowEnabled) {
  14432. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14433. }
  14434. return b.renderPriority - a.renderPriority;
  14435. };
  14436. /**
  14437. * Disposes the light.
  14438. */
  14439. Light.prototype.dispose = function () {
  14440. if (this._shadowGenerator) {
  14441. this._shadowGenerator.dispose();
  14442. this._shadowGenerator = null;
  14443. }
  14444. // Animations
  14445. this.getScene().stopAnimation(this);
  14446. // Remove from meshes
  14447. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14448. var mesh = _a[_i];
  14449. mesh._removeLightSource(this);
  14450. }
  14451. this._uniformBuffer.dispose();
  14452. // Remove from scene
  14453. this.getScene().removeLight(this);
  14454. _super.prototype.dispose.call(this);
  14455. };
  14456. /**
  14457. * Returns the light type ID (integer).
  14458. */
  14459. Light.prototype.getTypeID = function () {
  14460. return 0;
  14461. };
  14462. /**
  14463. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14464. */
  14465. Light.prototype.getScaledIntensity = function () {
  14466. return this._photometricScale * this.intensity;
  14467. };
  14468. /**
  14469. * Returns a new Light object, named "name", from the current one.
  14470. */
  14471. Light.prototype.clone = function (name) {
  14472. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14473. };
  14474. /**
  14475. * Serializes the current light into a Serialization object.
  14476. * Returns the serialized object.
  14477. */
  14478. Light.prototype.serialize = function () {
  14479. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14480. // Type
  14481. serializationObject.type = this.getTypeID();
  14482. // Parent
  14483. if (this.parent) {
  14484. serializationObject.parentId = this.parent.id;
  14485. }
  14486. // Inclusion / exclusions
  14487. if (this.excludedMeshes.length > 0) {
  14488. serializationObject.excludedMeshesIds = [];
  14489. this.excludedMeshes.forEach(function (mesh) {
  14490. serializationObject.excludedMeshesIds.push(mesh.id);
  14491. });
  14492. }
  14493. if (this.includedOnlyMeshes.length > 0) {
  14494. serializationObject.includedOnlyMeshesIds = [];
  14495. this.includedOnlyMeshes.forEach(function (mesh) {
  14496. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14497. });
  14498. }
  14499. // Animations
  14500. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14501. serializationObject.ranges = this.serializeAnimationRanges();
  14502. return serializationObject;
  14503. };
  14504. /**
  14505. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14506. * This new light is named "name" and added to the passed scene.
  14507. */
  14508. Light.GetConstructorFromName = function (type, name, scene) {
  14509. switch (type) {
  14510. case 0:
  14511. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14512. case 1:
  14513. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14514. case 2:
  14515. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14516. case 3:
  14517. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14518. }
  14519. };
  14520. /**
  14521. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14522. */
  14523. Light.Parse = function (parsedLight, scene) {
  14524. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14525. // Inclusion / exclusions
  14526. if (parsedLight.excludedMeshesIds) {
  14527. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14528. }
  14529. if (parsedLight.includedOnlyMeshesIds) {
  14530. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14531. }
  14532. // Parent
  14533. if (parsedLight.parentId) {
  14534. light._waitingParentId = parsedLight.parentId;
  14535. }
  14536. // Animations
  14537. if (parsedLight.animations) {
  14538. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14539. var parsedAnimation = parsedLight.animations[animationIndex];
  14540. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14541. }
  14542. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14543. }
  14544. if (parsedLight.autoAnimate) {
  14545. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14546. }
  14547. return light;
  14548. };
  14549. Light.prototype._hookArrayForExcluded = function (array) {
  14550. var _this = this;
  14551. var oldPush = array.push;
  14552. array.push = function () {
  14553. var items = [];
  14554. for (var _i = 0; _i < arguments.length; _i++) {
  14555. items[_i] = arguments[_i];
  14556. }
  14557. var result = oldPush.apply(array, items);
  14558. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14559. var item = items_1[_a];
  14560. item._resyncLighSource(_this);
  14561. }
  14562. return result;
  14563. };
  14564. var oldSplice = array.splice;
  14565. array.splice = function (index, deleteCount) {
  14566. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14567. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14568. var item = deleted_1[_i];
  14569. item._resyncLighSource(_this);
  14570. }
  14571. return deleted;
  14572. };
  14573. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14574. var item = array_1[_i];
  14575. item._resyncLighSource(this);
  14576. }
  14577. };
  14578. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14579. var _this = this;
  14580. var oldPush = array.push;
  14581. array.push = function () {
  14582. var items = [];
  14583. for (var _i = 0; _i < arguments.length; _i++) {
  14584. items[_i] = arguments[_i];
  14585. }
  14586. var result = oldPush.apply(array, items);
  14587. _this._resyncMeshes();
  14588. return result;
  14589. };
  14590. var oldSplice = array.splice;
  14591. array.splice = function (index, deleteCount) {
  14592. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14593. _this._resyncMeshes();
  14594. return deleted;
  14595. };
  14596. this._resyncMeshes();
  14597. };
  14598. Light.prototype._resyncMeshes = function () {
  14599. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14600. var mesh = _a[_i];
  14601. mesh._resyncLighSource(this);
  14602. }
  14603. };
  14604. Light.prototype._markMeshesAsLightDirty = function () {
  14605. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14606. var mesh = _a[_i];
  14607. if (mesh._lightSources.indexOf(this) !== -1) {
  14608. mesh._markSubMeshesAsLightDirty();
  14609. }
  14610. }
  14611. };
  14612. /**
  14613. * Recomputes the cached photometric scale if needed.
  14614. */
  14615. Light.prototype._computePhotometricScale = function () {
  14616. this._photometricScale = this._getPhotometricScale();
  14617. this.getScene().resetCachedMaterial();
  14618. };
  14619. /**
  14620. * Returns the Photometric Scale according to the light type and intensity mode.
  14621. */
  14622. Light.prototype._getPhotometricScale = function () {
  14623. var photometricScale = 0.0;
  14624. var lightTypeID = this.getTypeID();
  14625. //get photometric mode
  14626. var photometricMode = this.intensityMode;
  14627. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14628. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14629. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14630. }
  14631. else {
  14632. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14633. }
  14634. }
  14635. //compute photometric scale
  14636. switch (lightTypeID) {
  14637. case Light.LIGHTTYPEID_POINTLIGHT:
  14638. case Light.LIGHTTYPEID_SPOTLIGHT:
  14639. switch (photometricMode) {
  14640. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14641. photometricScale = 1.0 / (4.0 * Math.PI);
  14642. break;
  14643. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14644. photometricScale = 1.0;
  14645. break;
  14646. case Light.INTENSITYMODE_LUMINANCE:
  14647. photometricScale = this.radius * this.radius;
  14648. break;
  14649. }
  14650. break;
  14651. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14652. switch (photometricMode) {
  14653. case Light.INTENSITYMODE_ILLUMINANCE:
  14654. photometricScale = 1.0;
  14655. break;
  14656. case Light.INTENSITYMODE_LUMINANCE:
  14657. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14658. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14659. var apexAngleRadians = this.radius;
  14660. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14661. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14662. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14663. photometricScale = solidAngle;
  14664. break;
  14665. }
  14666. break;
  14667. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14668. // No fall off in hemisperic light.
  14669. photometricScale = 1.0;
  14670. break;
  14671. }
  14672. return photometricScale;
  14673. };
  14674. Light.prototype._reorderLightsInScene = function () {
  14675. var scene = this.getScene();
  14676. if (this.renderPriority != 0) {
  14677. scene.requireLightSorting = true;
  14678. }
  14679. this.getScene().sortLightsByPriority();
  14680. };
  14681. //lightmapMode Consts
  14682. Light._LIGHTMAP_DEFAULT = 0;
  14683. Light._LIGHTMAP_SPECULAR = 1;
  14684. Light._LIGHTMAP_SHADOWSONLY = 2;
  14685. // Intensity Mode Consts
  14686. Light._INTENSITYMODE_AUTOMATIC = 0;
  14687. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14688. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14689. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14690. Light._INTENSITYMODE_LUMINANCE = 4;
  14691. // Light types ids const.
  14692. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14693. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14694. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14695. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14696. __decorate([
  14697. BABYLON.serializeAsColor3()
  14698. ], Light.prototype, "diffuse", void 0);
  14699. __decorate([
  14700. BABYLON.serializeAsColor3()
  14701. ], Light.prototype, "specular", void 0);
  14702. __decorate([
  14703. BABYLON.serialize()
  14704. ], Light.prototype, "intensity", void 0);
  14705. __decorate([
  14706. BABYLON.serialize()
  14707. ], Light.prototype, "range", void 0);
  14708. __decorate([
  14709. BABYLON.serialize()
  14710. ], Light.prototype, "intensityMode", null);
  14711. __decorate([
  14712. BABYLON.serialize()
  14713. ], Light.prototype, "radius", null);
  14714. __decorate([
  14715. BABYLON.serialize()
  14716. ], Light.prototype, "_renderPriority", void 0);
  14717. __decorate([
  14718. BABYLON.expandToProperty("_reorderLightsInScene")
  14719. ], Light.prototype, "renderPriority", void 0);
  14720. __decorate([
  14721. BABYLON.serialize()
  14722. ], Light.prototype, "shadowEnabled", void 0);
  14723. __decorate([
  14724. BABYLON.serialize("excludeWithLayerMask")
  14725. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14726. __decorate([
  14727. BABYLON.serialize("includeOnlyWithLayerMask")
  14728. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14729. __decorate([
  14730. BABYLON.serialize("lightmapMode")
  14731. ], Light.prototype, "_lightmapMode", void 0);
  14732. return Light;
  14733. }(BABYLON.Node));
  14734. BABYLON.Light = Light;
  14735. })(BABYLON || (BABYLON = {}));
  14736. //# sourceMappingURL=babylon.light.js.map
  14737. var BABYLON;
  14738. (function (BABYLON) {
  14739. var Camera = (function (_super) {
  14740. __extends(Camera, _super);
  14741. function Camera(name, position, scene) {
  14742. var _this = _super.call(this, name, scene) || this;
  14743. _this.upVector = BABYLON.Vector3.Up();
  14744. _this.orthoLeft = null;
  14745. _this.orthoRight = null;
  14746. _this.orthoBottom = null;
  14747. _this.orthoTop = null;
  14748. _this.fov = 0.8;
  14749. _this.minZ = 1;
  14750. _this.maxZ = 10000.0;
  14751. _this.inertia = 0.9;
  14752. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14753. _this.isIntermediate = false;
  14754. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14755. _this.layerMask = 0x0FFFFFFF;
  14756. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14757. // Camera rig members
  14758. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14759. _this._rigCameras = new Array();
  14760. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14761. _this.customRenderTargets = new Array();
  14762. // Observables
  14763. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14764. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14765. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14766. // Cache
  14767. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14768. _this._projectionMatrix = new BABYLON.Matrix();
  14769. _this._doNotComputeProjectionMatrix = false;
  14770. _this._postProcesses = new Array();
  14771. _this._transformMatrix = BABYLON.Matrix.Zero();
  14772. _this._activeMeshes = new BABYLON.SmartArray(256);
  14773. _this._globalPosition = BABYLON.Vector3.Zero();
  14774. _this._refreshFrustumPlanes = true;
  14775. _this.getScene().addCamera(_this);
  14776. if (!_this.getScene().activeCamera) {
  14777. _this.getScene().activeCamera = _this;
  14778. }
  14779. _this.position = position;
  14780. return _this;
  14781. }
  14782. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14783. get: function () {
  14784. return Camera._PERSPECTIVE_CAMERA;
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14790. get: function () {
  14791. return Camera._ORTHOGRAPHIC_CAMERA;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14797. get: function () {
  14798. return Camera._FOVMODE_VERTICAL_FIXED;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14804. get: function () {
  14805. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14811. get: function () {
  14812. return Camera._RIG_MODE_NONE;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14818. get: function () {
  14819. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14825. get: function () {
  14826. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14832. get: function () {
  14833. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14839. get: function () {
  14840. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14841. },
  14842. enumerable: true,
  14843. configurable: true
  14844. });
  14845. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14846. get: function () {
  14847. return Camera._RIG_MODE_VR;
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14853. get: function () {
  14854. return Camera._RIG_MODE_WEBVR;
  14855. },
  14856. enumerable: true,
  14857. configurable: true
  14858. });
  14859. /**
  14860. * Store current camera state (fov, position, etc..)
  14861. */
  14862. Camera.prototype.storeState = function () {
  14863. this._stateStored = true;
  14864. this._storedFov = this.fov;
  14865. return this;
  14866. };
  14867. /**
  14868. * Restored camera state. You must call storeState() first
  14869. */
  14870. Camera.prototype.restoreState = function () {
  14871. if (!this._stateStored) {
  14872. return false;
  14873. }
  14874. this.fov = this._storedFov;
  14875. return true;
  14876. };
  14877. Camera.prototype.getClassName = function () {
  14878. return "Camera";
  14879. };
  14880. /**
  14881. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14882. */
  14883. Camera.prototype.toString = function (fullDetails) {
  14884. var ret = "Name: " + this.name;
  14885. ret += ", type: " + this.getClassName();
  14886. if (this.animations) {
  14887. for (var i = 0; i < this.animations.length; i++) {
  14888. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14889. }
  14890. }
  14891. if (fullDetails) {
  14892. }
  14893. return ret;
  14894. };
  14895. Object.defineProperty(Camera.prototype, "globalPosition", {
  14896. get: function () {
  14897. return this._globalPosition;
  14898. },
  14899. enumerable: true,
  14900. configurable: true
  14901. });
  14902. Camera.prototype.getActiveMeshes = function () {
  14903. return this._activeMeshes;
  14904. };
  14905. Camera.prototype.isActiveMesh = function (mesh) {
  14906. return (this._activeMeshes.indexOf(mesh) !== -1);
  14907. };
  14908. //Cache
  14909. Camera.prototype._initCache = function () {
  14910. _super.prototype._initCache.call(this);
  14911. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14912. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14913. this._cache.mode = undefined;
  14914. this._cache.minZ = undefined;
  14915. this._cache.maxZ = undefined;
  14916. this._cache.fov = undefined;
  14917. this._cache.fovMode = undefined;
  14918. this._cache.aspectRatio = undefined;
  14919. this._cache.orthoLeft = undefined;
  14920. this._cache.orthoRight = undefined;
  14921. this._cache.orthoBottom = undefined;
  14922. this._cache.orthoTop = undefined;
  14923. this._cache.renderWidth = undefined;
  14924. this._cache.renderHeight = undefined;
  14925. };
  14926. Camera.prototype._updateCache = function (ignoreParentClass) {
  14927. if (!ignoreParentClass) {
  14928. _super.prototype._updateCache.call(this);
  14929. }
  14930. var engine = this.getEngine();
  14931. this._cache.position.copyFrom(this.position);
  14932. this._cache.upVector.copyFrom(this.upVector);
  14933. this._cache.mode = this.mode;
  14934. this._cache.minZ = this.minZ;
  14935. this._cache.maxZ = this.maxZ;
  14936. this._cache.fov = this.fov;
  14937. this._cache.fovMode = this.fovMode;
  14938. this._cache.aspectRatio = engine.getAspectRatio(this);
  14939. this._cache.orthoLeft = this.orthoLeft;
  14940. this._cache.orthoRight = this.orthoRight;
  14941. this._cache.orthoBottom = this.orthoBottom;
  14942. this._cache.orthoTop = this.orthoTop;
  14943. this._cache.renderWidth = engine.getRenderWidth();
  14944. this._cache.renderHeight = engine.getRenderHeight();
  14945. };
  14946. Camera.prototype._updateFromScene = function () {
  14947. this.updateCache();
  14948. this.update();
  14949. };
  14950. // Synchronized
  14951. Camera.prototype._isSynchronized = function () {
  14952. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14953. };
  14954. Camera.prototype._isSynchronizedViewMatrix = function () {
  14955. if (!_super.prototype._isSynchronized.call(this))
  14956. return false;
  14957. return this._cache.position.equals(this.position)
  14958. && this._cache.upVector.equals(this.upVector)
  14959. && this.isSynchronizedWithParent();
  14960. };
  14961. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14962. var check = this._cache.mode === this.mode
  14963. && this._cache.minZ === this.minZ
  14964. && this._cache.maxZ === this.maxZ;
  14965. if (!check) {
  14966. return false;
  14967. }
  14968. var engine = this.getEngine();
  14969. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14970. check = this._cache.fov === this.fov
  14971. && this._cache.fovMode === this.fovMode
  14972. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14973. }
  14974. else {
  14975. check = this._cache.orthoLeft === this.orthoLeft
  14976. && this._cache.orthoRight === this.orthoRight
  14977. && this._cache.orthoBottom === this.orthoBottom
  14978. && this._cache.orthoTop === this.orthoTop
  14979. && this._cache.renderWidth === engine.getRenderWidth()
  14980. && this._cache.renderHeight === engine.getRenderHeight();
  14981. }
  14982. return check;
  14983. };
  14984. // Controls
  14985. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14986. };
  14987. Camera.prototype.detachControl = function (element) {
  14988. };
  14989. Camera.prototype.update = function () {
  14990. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14991. this._updateRigCameras();
  14992. }
  14993. this._checkInputs();
  14994. };
  14995. Camera.prototype._checkInputs = function () {
  14996. this.onAfterCheckInputsObservable.notifyObservers(this);
  14997. };
  14998. Object.defineProperty(Camera.prototype, "rigCameras", {
  14999. get: function () {
  15000. return this._rigCameras;
  15001. },
  15002. enumerable: true,
  15003. configurable: true
  15004. });
  15005. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15006. get: function () {
  15007. return this._rigPostProcess;
  15008. },
  15009. enumerable: true,
  15010. configurable: true
  15011. });
  15012. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15013. // invalidate framebuffer
  15014. if (this._postProcesses.length > 0) {
  15015. this._postProcesses[0].markTextureDirty();
  15016. }
  15017. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15018. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15019. var cam = this._rigCameras[i];
  15020. var rigPostProcess = cam._rigPostProcess;
  15021. // for VR rig, there does not have to be a post process
  15022. if (rigPostProcess) {
  15023. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15024. if (isPass) {
  15025. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15026. cam.isIntermediate = this._postProcesses.length === 0;
  15027. }
  15028. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15029. rigPostProcess.markTextureDirty();
  15030. }
  15031. else {
  15032. cam._postProcesses = this._postProcesses.slice(0);
  15033. }
  15034. }
  15035. };
  15036. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15037. if (insertAt === void 0) { insertAt = null; }
  15038. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15039. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15040. return 0;
  15041. }
  15042. if (insertAt == null || insertAt < 0) {
  15043. this._postProcesses.push(postProcess);
  15044. }
  15045. else {
  15046. this._postProcesses.splice(insertAt, 0, postProcess);
  15047. }
  15048. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15049. return this._postProcesses.indexOf(postProcess);
  15050. };
  15051. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15052. if (atIndices === void 0) { atIndices = null; }
  15053. var result = [];
  15054. var i;
  15055. var index;
  15056. if (!atIndices) {
  15057. var idx = this._postProcesses.indexOf(postProcess);
  15058. if (idx !== -1) {
  15059. this._postProcesses.splice(idx, 1);
  15060. }
  15061. }
  15062. else {
  15063. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15064. // iterate descending, so can just splice as we go
  15065. for (i = atIndices.length - 1; i >= 0; i--) {
  15066. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15067. result.push(i);
  15068. continue;
  15069. }
  15070. index = atIndices[i];
  15071. this._postProcesses.splice(index, 1);
  15072. }
  15073. }
  15074. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15075. return result;
  15076. };
  15077. Camera.prototype.getWorldMatrix = function () {
  15078. if (!this._worldMatrix) {
  15079. this._worldMatrix = BABYLON.Matrix.Identity();
  15080. }
  15081. var viewMatrix = this.getViewMatrix();
  15082. viewMatrix.invertToRef(this._worldMatrix);
  15083. return this._worldMatrix;
  15084. };
  15085. Camera.prototype._getViewMatrix = function () {
  15086. return BABYLON.Matrix.Identity();
  15087. };
  15088. Camera.prototype.getViewMatrix = function (force) {
  15089. if (!force && this._isSynchronizedViewMatrix()) {
  15090. return this._computedViewMatrix;
  15091. }
  15092. this._computedViewMatrix = this._getViewMatrix();
  15093. this._currentRenderId = this.getScene().getRenderId();
  15094. this._refreshFrustumPlanes = true;
  15095. if (!this.parent || !this.parent.getWorldMatrix) {
  15096. this._globalPosition.copyFrom(this.position);
  15097. }
  15098. else {
  15099. if (!this._worldMatrix) {
  15100. this._worldMatrix = BABYLON.Matrix.Identity();
  15101. }
  15102. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15103. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15104. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15105. this._computedViewMatrix.invert();
  15106. this._markSyncedWithParent();
  15107. }
  15108. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15109. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15110. }
  15111. this.onViewMatrixChangedObservable.notifyObservers(this);
  15112. return this._computedViewMatrix;
  15113. };
  15114. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15115. this._doNotComputeProjectionMatrix = true;
  15116. if (projection !== undefined) {
  15117. this._projectionMatrix = projection;
  15118. }
  15119. };
  15120. ;
  15121. Camera.prototype.unfreezeProjectionMatrix = function () {
  15122. this._doNotComputeProjectionMatrix = false;
  15123. };
  15124. ;
  15125. Camera.prototype.getProjectionMatrix = function (force) {
  15126. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15127. return this._projectionMatrix;
  15128. }
  15129. this._refreshFrustumPlanes = true;
  15130. var engine = this.getEngine();
  15131. var scene = this.getScene();
  15132. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15133. if (this.minZ <= 0) {
  15134. this.minZ = 0.1;
  15135. }
  15136. if (scene.useRightHandedSystem) {
  15137. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15138. }
  15139. else {
  15140. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15141. }
  15142. }
  15143. else {
  15144. var halfWidth = engine.getRenderWidth() / 2.0;
  15145. var halfHeight = engine.getRenderHeight() / 2.0;
  15146. if (scene.useRightHandedSystem) {
  15147. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15148. }
  15149. else {
  15150. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15151. }
  15152. }
  15153. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15154. return this._projectionMatrix;
  15155. };
  15156. Camera.prototype.getTranformationMatrix = function () {
  15157. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15158. return this._transformMatrix;
  15159. };
  15160. Camera.prototype.updateFrustumPlanes = function () {
  15161. if (!this._refreshFrustumPlanes) {
  15162. return;
  15163. }
  15164. this.getTranformationMatrix();
  15165. if (!this._frustumPlanes) {
  15166. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15167. }
  15168. else {
  15169. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15170. }
  15171. this._refreshFrustumPlanes = false;
  15172. };
  15173. Camera.prototype.isInFrustum = function (target) {
  15174. this.updateFrustumPlanes();
  15175. return target.isInFrustum(this._frustumPlanes);
  15176. };
  15177. Camera.prototype.isCompletelyInFrustum = function (target) {
  15178. this.updateFrustumPlanes();
  15179. return target.isCompletelyInFrustum(this._frustumPlanes);
  15180. };
  15181. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15182. if (length === void 0) { length = 100; }
  15183. if (!transform) {
  15184. transform = this.getWorldMatrix();
  15185. }
  15186. if (!origin) {
  15187. origin = this.position;
  15188. }
  15189. var forward = new BABYLON.Vector3(0, 0, 1);
  15190. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15191. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15192. return new BABYLON.Ray(origin, direction, length);
  15193. };
  15194. Camera.prototype.dispose = function () {
  15195. // Observables
  15196. this.onViewMatrixChangedObservable.clear();
  15197. this.onProjectionMatrixChangedObservable.clear();
  15198. this.onAfterCheckInputsObservable.clear();
  15199. // Inputs
  15200. if (this.inputs) {
  15201. this.inputs.clear();
  15202. }
  15203. // Animations
  15204. this.getScene().stopAnimation(this);
  15205. // Remove from scene
  15206. this.getScene().removeCamera(this);
  15207. while (this._rigCameras.length > 0) {
  15208. this._rigCameras.pop().dispose();
  15209. }
  15210. // Postprocesses
  15211. var i = this._postProcesses.length;
  15212. while (--i >= 0) {
  15213. this._postProcesses[i].dispose(this);
  15214. }
  15215. // Render targets
  15216. var i = this.customRenderTargets.length;
  15217. while (--i >= 0) {
  15218. this.customRenderTargets[i].dispose();
  15219. }
  15220. this.customRenderTargets = [];
  15221. // Active Meshes
  15222. this._activeMeshes.dispose();
  15223. _super.prototype.dispose.call(this);
  15224. };
  15225. Object.defineProperty(Camera.prototype, "leftCamera", {
  15226. // ---- Camera rigs section ----
  15227. get: function () {
  15228. if (this._rigCameras.length < 1) {
  15229. return undefined;
  15230. }
  15231. return this._rigCameras[0];
  15232. },
  15233. enumerable: true,
  15234. configurable: true
  15235. });
  15236. Object.defineProperty(Camera.prototype, "rightCamera", {
  15237. get: function () {
  15238. if (this._rigCameras.length < 2) {
  15239. return undefined;
  15240. }
  15241. return this._rigCameras[1];
  15242. },
  15243. enumerable: true,
  15244. configurable: true
  15245. });
  15246. Camera.prototype.getLeftTarget = function () {
  15247. if (this._rigCameras.length < 1) {
  15248. return undefined;
  15249. }
  15250. return this._rigCameras[0].getTarget();
  15251. };
  15252. Camera.prototype.getRightTarget = function () {
  15253. if (this._rigCameras.length < 2) {
  15254. return undefined;
  15255. }
  15256. return this._rigCameras[1].getTarget();
  15257. };
  15258. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15259. while (this._rigCameras.length > 0) {
  15260. this._rigCameras.pop().dispose();
  15261. }
  15262. this.cameraRigMode = mode;
  15263. this._cameraRigParams = {};
  15264. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15265. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15266. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15267. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15268. // create the rig cameras, unless none
  15269. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15270. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15271. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15272. }
  15273. switch (this.cameraRigMode) {
  15274. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15275. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15276. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15277. break;
  15278. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15279. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15280. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15281. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15282. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15283. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15284. break;
  15285. case Camera.RIG_MODE_VR:
  15286. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15287. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15288. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15289. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15290. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15291. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15292. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15293. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15294. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15295. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15296. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15297. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15298. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15299. if (metrics.compensateDistortion) {
  15300. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15301. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15302. }
  15303. break;
  15304. case Camera.RIG_MODE_WEBVR:
  15305. if (rigParams.vrDisplay) {
  15306. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15307. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15308. //Left eye
  15309. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15310. this._rigCameras[0].setCameraRigParameter("left", true);
  15311. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15312. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15313. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15314. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15315. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15316. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15317. this._rigCameras[0].parent = this;
  15318. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15319. //Right eye
  15320. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15321. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15322. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15323. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15324. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15325. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15326. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15327. this._rigCameras[1].parent = this;
  15328. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15329. }
  15330. break;
  15331. }
  15332. this._cascadePostProcessesToRigCams();
  15333. this.
  15334. update();
  15335. };
  15336. Camera.prototype._getVRProjectionMatrix = function () {
  15337. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15338. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15339. return this._projectionMatrix;
  15340. };
  15341. Camera.prototype._updateCameraRotationMatrix = function () {
  15342. //Here for WebVR
  15343. };
  15344. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15345. //Here for WebVR
  15346. };
  15347. /**
  15348. * This function MUST be overwritten by the different WebVR cameras available.
  15349. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15350. */
  15351. Camera.prototype._getWebVRProjectionMatrix = function () {
  15352. return BABYLON.Matrix.Identity();
  15353. };
  15354. /**
  15355. * This function MUST be overwritten by the different WebVR cameras available.
  15356. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15357. */
  15358. Camera.prototype._getWebVRViewMatrix = function () {
  15359. return BABYLON.Matrix.Identity();
  15360. };
  15361. Camera.prototype.setCameraRigParameter = function (name, value) {
  15362. if (!this._cameraRigParams) {
  15363. this._cameraRigParams = {};
  15364. }
  15365. this._cameraRigParams[name] = value;
  15366. //provisionnally:
  15367. if (name === "interaxialDistance") {
  15368. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15369. }
  15370. };
  15371. /**
  15372. * needs to be overridden by children so sub has required properties to be copied
  15373. */
  15374. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15375. return null;
  15376. };
  15377. /**
  15378. * May need to be overridden by children
  15379. */
  15380. Camera.prototype._updateRigCameras = function () {
  15381. for (var i = 0; i < this._rigCameras.length; i++) {
  15382. this._rigCameras[i].minZ = this.minZ;
  15383. this._rigCameras[i].maxZ = this.maxZ;
  15384. this._rigCameras[i].fov = this.fov;
  15385. }
  15386. // only update viewport when ANAGLYPH
  15387. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15388. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15389. }
  15390. };
  15391. Camera.prototype._setupInputs = function () {
  15392. };
  15393. Camera.prototype.serialize = function () {
  15394. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15395. // Type
  15396. serializationObject.type = this.getClassName();
  15397. // Parent
  15398. if (this.parent) {
  15399. serializationObject.parentId = this.parent.id;
  15400. }
  15401. if (this.inputs) {
  15402. this.inputs.serialize(serializationObject);
  15403. }
  15404. // Animations
  15405. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15406. serializationObject.ranges = this.serializeAnimationRanges();
  15407. return serializationObject;
  15408. };
  15409. Camera.prototype.clone = function (name) {
  15410. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15411. };
  15412. Camera.prototype.getDirection = function (localAxis) {
  15413. var result = BABYLON.Vector3.Zero();
  15414. this.getDirectionToRef(localAxis, result);
  15415. return result;
  15416. };
  15417. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15418. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15419. };
  15420. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15421. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15422. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15423. switch (type) {
  15424. case "ArcRotateCamera":
  15425. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15426. case "DeviceOrientationCamera":
  15427. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15428. case "FollowCamera":
  15429. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15430. case "ArcFollowCamera":
  15431. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15432. case "GamepadCamera":
  15433. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15434. case "TouchCamera":
  15435. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15436. case "VirtualJoysticksCamera":
  15437. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15438. case "WebVRFreeCamera":
  15439. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15440. case "WebVRGamepadCamera":
  15441. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15442. case "VRDeviceOrientationFreeCamera":
  15443. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15444. case "VRDeviceOrientationGamepadCamera":
  15445. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15446. case "AnaglyphArcRotateCamera":
  15447. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15448. case "AnaglyphFreeCamera":
  15449. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15450. case "AnaglyphGamepadCamera":
  15451. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15452. case "AnaglyphUniversalCamera":
  15453. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15454. case "StereoscopicArcRotateCamera":
  15455. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15456. case "StereoscopicFreeCamera":
  15457. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15458. case "StereoscopicGamepadCamera":
  15459. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15460. case "StereoscopicUniversalCamera":
  15461. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15462. case "FreeCamera":// Forcing Universal here
  15463. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15464. default:// Universal Camera is the default value
  15465. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15466. }
  15467. };
  15468. Camera.Parse = function (parsedCamera, scene) {
  15469. var type = parsedCamera.type;
  15470. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15471. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15472. // Parent
  15473. if (parsedCamera.parentId) {
  15474. camera._waitingParentId = parsedCamera.parentId;
  15475. }
  15476. //If camera has an input manager, let it parse inputs settings
  15477. if (camera.inputs) {
  15478. camera.inputs.parse(parsedCamera);
  15479. camera._setupInputs();
  15480. }
  15481. if (camera.setPosition) {
  15482. camera.position.copyFromFloats(0, 0, 0);
  15483. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15484. }
  15485. // Target
  15486. if (parsedCamera.target) {
  15487. if (camera.setTarget) {
  15488. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15489. }
  15490. }
  15491. // Apply 3d rig, when found
  15492. if (parsedCamera.cameraRigMode) {
  15493. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15494. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15495. }
  15496. // Animations
  15497. if (parsedCamera.animations) {
  15498. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15499. var parsedAnimation = parsedCamera.animations[animationIndex];
  15500. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15501. }
  15502. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15503. }
  15504. if (parsedCamera.autoAnimate) {
  15505. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15506. }
  15507. return camera;
  15508. };
  15509. // Statics
  15510. Camera._PERSPECTIVE_CAMERA = 0;
  15511. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15512. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15513. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15514. Camera._RIG_MODE_NONE = 0;
  15515. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15516. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15517. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15518. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15519. Camera._RIG_MODE_VR = 20;
  15520. Camera._RIG_MODE_WEBVR = 21;
  15521. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15522. __decorate([
  15523. BABYLON.serializeAsVector3()
  15524. ], Camera.prototype, "position", void 0);
  15525. __decorate([
  15526. BABYLON.serializeAsVector3()
  15527. ], Camera.prototype, "upVector", void 0);
  15528. __decorate([
  15529. BABYLON.serialize()
  15530. ], Camera.prototype, "orthoLeft", void 0);
  15531. __decorate([
  15532. BABYLON.serialize()
  15533. ], Camera.prototype, "orthoRight", void 0);
  15534. __decorate([
  15535. BABYLON.serialize()
  15536. ], Camera.prototype, "orthoBottom", void 0);
  15537. __decorate([
  15538. BABYLON.serialize()
  15539. ], Camera.prototype, "orthoTop", void 0);
  15540. __decorate([
  15541. BABYLON.serialize()
  15542. ], Camera.prototype, "fov", void 0);
  15543. __decorate([
  15544. BABYLON.serialize()
  15545. ], Camera.prototype, "minZ", void 0);
  15546. __decorate([
  15547. BABYLON.serialize()
  15548. ], Camera.prototype, "maxZ", void 0);
  15549. __decorate([
  15550. BABYLON.serialize()
  15551. ], Camera.prototype, "inertia", void 0);
  15552. __decorate([
  15553. BABYLON.serialize()
  15554. ], Camera.prototype, "mode", void 0);
  15555. __decorate([
  15556. BABYLON.serialize()
  15557. ], Camera.prototype, "layerMask", void 0);
  15558. __decorate([
  15559. BABYLON.serialize()
  15560. ], Camera.prototype, "fovMode", void 0);
  15561. __decorate([
  15562. BABYLON.serialize()
  15563. ], Camera.prototype, "cameraRigMode", void 0);
  15564. __decorate([
  15565. BABYLON.serialize()
  15566. ], Camera.prototype, "interaxialDistance", void 0);
  15567. __decorate([
  15568. BABYLON.serialize()
  15569. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15570. return Camera;
  15571. }(BABYLON.Node));
  15572. BABYLON.Camera = Camera;
  15573. })(BABYLON || (BABYLON = {}));
  15574. //# sourceMappingURL=babylon.camera.js.map
  15575. var BABYLON;
  15576. (function (BABYLON) {
  15577. var RenderingManager = (function () {
  15578. function RenderingManager(scene) {
  15579. this._renderingGroups = new Array();
  15580. this._autoClearDepthStencil = {};
  15581. this._customOpaqueSortCompareFn = {};
  15582. this._customAlphaTestSortCompareFn = {};
  15583. this._customTransparentSortCompareFn = {};
  15584. this._renderinGroupInfo = null;
  15585. this._scene = scene;
  15586. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15587. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15588. }
  15589. }
  15590. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15591. if (depth === void 0) { depth = true; }
  15592. if (stencil === void 0) { stencil = true; }
  15593. if (this._depthStencilBufferAlreadyCleaned) {
  15594. return;
  15595. }
  15596. this._scene.getEngine().clear(null, false, depth, stencil);
  15597. this._depthStencilBufferAlreadyCleaned = true;
  15598. };
  15599. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15600. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15601. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15602. var info = null;
  15603. if (observable) {
  15604. if (!this._renderinGroupInfo) {
  15605. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15606. }
  15607. info = this._renderinGroupInfo;
  15608. info.scene = this._scene;
  15609. info.camera = this._scene.activeCamera;
  15610. }
  15611. // Dispatch sprites
  15612. if (renderSprites) {
  15613. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15614. var manager = this._scene.spriteManagers[index];
  15615. this.dispatchSprites(manager);
  15616. }
  15617. }
  15618. // Render
  15619. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15620. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15621. var renderingGroup = this._renderingGroups[index];
  15622. if (!renderingGroup && !observable)
  15623. continue;
  15624. this._currentIndex = index;
  15625. var renderingGroupMask = 0;
  15626. // Fire PRECLEAR stage
  15627. if (observable) {
  15628. renderingGroupMask = Math.pow(2, index);
  15629. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15630. info.renderingGroupId = index;
  15631. observable.notifyObservers(info, renderingGroupMask);
  15632. }
  15633. // Clear depth/stencil if needed
  15634. if (RenderingManager.AUTOCLEAR) {
  15635. var autoClear = this._autoClearDepthStencil[index];
  15636. if (autoClear && autoClear.autoClear) {
  15637. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15638. }
  15639. }
  15640. if (observable) {
  15641. // Fire PREOPAQUE stage
  15642. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15643. observable.notifyObservers(info, renderingGroupMask);
  15644. // Fire PRETRANSPARENT stage
  15645. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15646. observable.notifyObservers(info, renderingGroupMask);
  15647. }
  15648. if (renderingGroup)
  15649. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15650. // Fire POSTTRANSPARENT stage
  15651. if (observable) {
  15652. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15653. observable.notifyObservers(info, renderingGroupMask);
  15654. }
  15655. }
  15656. };
  15657. RenderingManager.prototype.reset = function () {
  15658. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15659. var renderingGroup = this._renderingGroups[index];
  15660. if (renderingGroup) {
  15661. renderingGroup.prepare();
  15662. }
  15663. }
  15664. };
  15665. RenderingManager.prototype.dispose = function () {
  15666. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15667. var renderingGroup = this._renderingGroups[index];
  15668. if (renderingGroup) {
  15669. renderingGroup.dispose();
  15670. }
  15671. }
  15672. this._renderingGroups.length = 0;
  15673. };
  15674. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15675. if (!this._renderingGroups[renderingGroupId]) {
  15676. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15677. }
  15678. };
  15679. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15680. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15681. this._prepareRenderingGroup(renderingGroupId);
  15682. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15683. };
  15684. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15685. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15686. this._prepareRenderingGroup(renderingGroupId);
  15687. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15688. };
  15689. RenderingManager.prototype.dispatch = function (subMesh) {
  15690. var mesh = subMesh.getMesh();
  15691. var renderingGroupId = mesh.renderingGroupId || 0;
  15692. this._prepareRenderingGroup(renderingGroupId);
  15693. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15694. };
  15695. /**
  15696. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15697. * This allowed control for front to back rendering or reversly depending of the special needs.
  15698. *
  15699. * @param renderingGroupId The rendering group id corresponding to its index
  15700. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15701. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15702. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15703. */
  15704. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15705. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15706. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15707. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15708. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15709. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15710. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15711. if (this._renderingGroups[renderingGroupId]) {
  15712. var group = this._renderingGroups[renderingGroupId];
  15713. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15714. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15715. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15716. }
  15717. };
  15718. /**
  15719. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15720. *
  15721. * @param renderingGroupId The rendering group id corresponding to its index
  15722. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15723. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15724. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15725. */
  15726. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15727. if (depth === void 0) { depth = true; }
  15728. if (stencil === void 0) { stencil = true; }
  15729. this._autoClearDepthStencil[renderingGroupId] = {
  15730. autoClear: autoClearDepthStencil,
  15731. depth: depth,
  15732. stencil: stencil
  15733. };
  15734. };
  15735. /**
  15736. * The max id used for rendering groups (not included)
  15737. */
  15738. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15739. /**
  15740. * The min id used for rendering groups (included)
  15741. */
  15742. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15743. /**
  15744. * Used to globally prevent autoclearing scenes.
  15745. */
  15746. RenderingManager.AUTOCLEAR = true;
  15747. return RenderingManager;
  15748. }());
  15749. BABYLON.RenderingManager = RenderingManager;
  15750. })(BABYLON || (BABYLON = {}));
  15751. //# sourceMappingURL=babylon.renderingManager.js.map
  15752. var BABYLON;
  15753. (function (BABYLON) {
  15754. var RenderingGroup = (function () {
  15755. /**
  15756. * Creates a new rendering group.
  15757. * @param index The rendering group index
  15758. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15759. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15760. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15761. */
  15762. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15763. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15764. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15765. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15766. this.index = index;
  15767. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15768. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15769. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15770. this._particleSystems = new BABYLON.SmartArray(256);
  15771. this._spriteManagers = new BABYLON.SmartArray(256);
  15772. this._edgesRenderers = new BABYLON.SmartArray(16);
  15773. this._scene = scene;
  15774. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15775. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15776. this.transparentSortCompareFn = transparentSortCompareFn;
  15777. }
  15778. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15779. /**
  15780. * Set the opaque sort comparison function.
  15781. * If null the sub meshes will be render in the order they were created
  15782. */
  15783. set: function (value) {
  15784. this._opaqueSortCompareFn = value;
  15785. if (value) {
  15786. this._renderOpaque = this.renderOpaqueSorted;
  15787. }
  15788. else {
  15789. this._renderOpaque = RenderingGroup.renderUnsorted;
  15790. }
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15796. /**
  15797. * Set the alpha test sort comparison function.
  15798. * If null the sub meshes will be render in the order they were created
  15799. */
  15800. set: function (value) {
  15801. this._alphaTestSortCompareFn = value;
  15802. if (value) {
  15803. this._renderAlphaTest = this.renderAlphaTestSorted;
  15804. }
  15805. else {
  15806. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15807. }
  15808. },
  15809. enumerable: true,
  15810. configurable: true
  15811. });
  15812. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15813. /**
  15814. * Set the transparent sort comparison function.
  15815. * If null the sub meshes will be render in the order they were created
  15816. */
  15817. set: function (value) {
  15818. if (value) {
  15819. this._transparentSortCompareFn = value;
  15820. }
  15821. else {
  15822. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15823. }
  15824. this._renderTransparent = this.renderTransparentSorted;
  15825. },
  15826. enumerable: true,
  15827. configurable: true
  15828. });
  15829. /**
  15830. * Render all the sub meshes contained in the group.
  15831. * @param customRenderFunction Used to override the default render behaviour of the group.
  15832. * @returns true if rendered some submeshes.
  15833. */
  15834. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15835. if (customRenderFunction) {
  15836. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15837. return;
  15838. }
  15839. var engine = this._scene.getEngine();
  15840. // Opaque
  15841. if (this._opaqueSubMeshes.length !== 0) {
  15842. this._renderOpaque(this._opaqueSubMeshes);
  15843. }
  15844. // Alpha test
  15845. if (this._alphaTestSubMeshes.length !== 0) {
  15846. engine.setAlphaTesting(true);
  15847. this._renderAlphaTest(this._alphaTestSubMeshes);
  15848. engine.setAlphaTesting(false);
  15849. }
  15850. var stencilState = engine.getStencilBuffer();
  15851. engine.setStencilBuffer(false);
  15852. // Sprites
  15853. if (renderSprites) {
  15854. this._renderSprites();
  15855. }
  15856. // Particles
  15857. if (renderParticles) {
  15858. this._renderParticles(activeMeshes);
  15859. }
  15860. if (this.onBeforeTransparentRendering) {
  15861. this.onBeforeTransparentRendering();
  15862. }
  15863. // Transparent
  15864. if (this._transparentSubMeshes.length !== 0) {
  15865. this._renderTransparent(this._transparentSubMeshes);
  15866. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15867. }
  15868. // Set back stencil to false in case it changes before the edge renderer.
  15869. engine.setStencilBuffer(false);
  15870. // Edges
  15871. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15872. this._edgesRenderers.data[edgesRendererIndex].render();
  15873. }
  15874. // Restore Stencil state.
  15875. engine.setStencilBuffer(stencilState);
  15876. };
  15877. /**
  15878. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15879. * @param subMeshes The submeshes to render
  15880. */
  15881. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15882. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15883. };
  15884. /**
  15885. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15886. * @param subMeshes The submeshes to render
  15887. */
  15888. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15889. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15890. };
  15891. /**
  15892. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15893. * @param subMeshes The submeshes to render
  15894. */
  15895. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15896. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15897. };
  15898. /**
  15899. * Renders the submeshes in a specified order.
  15900. * @param subMeshes The submeshes to sort before render
  15901. * @param sortCompareFn The comparison function use to sort
  15902. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15903. * @param transparent Specifies to activate blending if true
  15904. */
  15905. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15906. var subIndex = 0;
  15907. var subMesh;
  15908. for (; subIndex < subMeshes.length; subIndex++) {
  15909. subMesh = subMeshes.data[subIndex];
  15910. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15911. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15912. }
  15913. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15914. sortedArray.sort(sortCompareFn);
  15915. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15916. subMesh = sortedArray[subIndex];
  15917. subMesh.render(transparent);
  15918. }
  15919. };
  15920. /**
  15921. * Renders the submeshes in the order they were dispatched (no sort applied).
  15922. * @param subMeshes The submeshes to render
  15923. */
  15924. RenderingGroup.renderUnsorted = function (subMeshes) {
  15925. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15926. var submesh = subMeshes.data[subIndex];
  15927. submesh.render(false);
  15928. }
  15929. };
  15930. /**
  15931. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15932. * are rendered back to front if in the same alpha index.
  15933. *
  15934. * @param a The first submesh
  15935. * @param b The second submesh
  15936. * @returns The result of the comparison
  15937. */
  15938. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15939. // Alpha index first
  15940. if (a._alphaIndex > b._alphaIndex) {
  15941. return 1;
  15942. }
  15943. if (a._alphaIndex < b._alphaIndex) {
  15944. return -1;
  15945. }
  15946. // Then distance to camera
  15947. return RenderingGroup.backToFrontSortCompare(a, b);
  15948. };
  15949. /**
  15950. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15951. * are rendered back to front.
  15952. *
  15953. * @param a The first submesh
  15954. * @param b The second submesh
  15955. * @returns The result of the comparison
  15956. */
  15957. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15958. // Then distance to camera
  15959. if (a._distanceToCamera < b._distanceToCamera) {
  15960. return 1;
  15961. }
  15962. if (a._distanceToCamera > b._distanceToCamera) {
  15963. return -1;
  15964. }
  15965. return 0;
  15966. };
  15967. /**
  15968. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15969. * are rendered front to back (prevent overdraw).
  15970. *
  15971. * @param a The first submesh
  15972. * @param b The second submesh
  15973. * @returns The result of the comparison
  15974. */
  15975. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15976. // Then distance to camera
  15977. if (a._distanceToCamera < b._distanceToCamera) {
  15978. return -1;
  15979. }
  15980. if (a._distanceToCamera > b._distanceToCamera) {
  15981. return 1;
  15982. }
  15983. return 0;
  15984. };
  15985. /**
  15986. * Resets the different lists of submeshes to prepare a new frame.
  15987. */
  15988. RenderingGroup.prototype.prepare = function () {
  15989. this._opaqueSubMeshes.reset();
  15990. this._transparentSubMeshes.reset();
  15991. this._alphaTestSubMeshes.reset();
  15992. this._particleSystems.reset();
  15993. this._spriteManagers.reset();
  15994. this._edgesRenderers.reset();
  15995. };
  15996. RenderingGroup.prototype.dispose = function () {
  15997. this._opaqueSubMeshes.dispose();
  15998. this._transparentSubMeshes.dispose();
  15999. this._alphaTestSubMeshes.dispose();
  16000. this._particleSystems.dispose();
  16001. this._spriteManagers.dispose();
  16002. this._edgesRenderers.dispose();
  16003. };
  16004. /**
  16005. * Inserts the submesh in its correct queue depending on its material.
  16006. * @param subMesh The submesh to dispatch
  16007. */
  16008. RenderingGroup.prototype.dispatch = function (subMesh) {
  16009. var material = subMesh.getMaterial();
  16010. var mesh = subMesh.getMesh();
  16011. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16012. this._transparentSubMeshes.push(subMesh);
  16013. }
  16014. else if (material.needAlphaTesting()) {
  16015. this._alphaTestSubMeshes.push(subMesh);
  16016. }
  16017. else {
  16018. this._opaqueSubMeshes.push(subMesh); // Opaque
  16019. }
  16020. if (mesh._edgesRenderer) {
  16021. this._edgesRenderers.push(mesh._edgesRenderer);
  16022. }
  16023. };
  16024. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16025. this._spriteManagers.push(spriteManager);
  16026. };
  16027. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16028. this._particleSystems.push(particleSystem);
  16029. };
  16030. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16031. if (this._particleSystems.length === 0) {
  16032. return;
  16033. }
  16034. // Particles
  16035. var activeCamera = this._scene.activeCamera;
  16036. this._scene._particlesDuration.beginMonitoring();
  16037. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16038. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16039. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16040. continue;
  16041. }
  16042. var emitter = particleSystem.emitter;
  16043. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16044. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16045. }
  16046. }
  16047. this._scene._particlesDuration.endMonitoring(false);
  16048. };
  16049. RenderingGroup.prototype._renderSprites = function () {
  16050. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16051. return;
  16052. }
  16053. // Sprites
  16054. var activeCamera = this._scene.activeCamera;
  16055. this._scene._spritesDuration.beginMonitoring();
  16056. for (var id = 0; id < this._spriteManagers.length; id++) {
  16057. var spriteManager = this._spriteManagers.data[id];
  16058. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16059. spriteManager.render();
  16060. }
  16061. }
  16062. this._scene._spritesDuration.endMonitoring(false);
  16063. };
  16064. return RenderingGroup;
  16065. }());
  16066. BABYLON.RenderingGroup = RenderingGroup;
  16067. })(BABYLON || (BABYLON = {}));
  16068. //# sourceMappingURL=babylon.renderingGroup.js.map
  16069. var BABYLON;
  16070. (function (BABYLON) {
  16071. var ClickInfo = (function () {
  16072. function ClickInfo() {
  16073. this._singleClick = false;
  16074. this._doubleClick = false;
  16075. this._hasSwiped = false;
  16076. this._ignore = false;
  16077. }
  16078. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16079. get: function () {
  16080. return this._singleClick;
  16081. },
  16082. set: function (b) {
  16083. this._singleClick = b;
  16084. },
  16085. enumerable: true,
  16086. configurable: true
  16087. });
  16088. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16089. get: function () {
  16090. return this._doubleClick;
  16091. },
  16092. set: function (b) {
  16093. this._doubleClick = b;
  16094. },
  16095. enumerable: true,
  16096. configurable: true
  16097. });
  16098. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16099. get: function () {
  16100. return this._hasSwiped;
  16101. },
  16102. set: function (b) {
  16103. this._hasSwiped = b;
  16104. },
  16105. enumerable: true,
  16106. configurable: true
  16107. });
  16108. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16109. get: function () {
  16110. return this._ignore;
  16111. },
  16112. set: function (b) {
  16113. this._ignore = b;
  16114. },
  16115. enumerable: true,
  16116. configurable: true
  16117. });
  16118. return ClickInfo;
  16119. }());
  16120. var PointerEventTypes = (function () {
  16121. function PointerEventTypes() {
  16122. }
  16123. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16124. get: function () {
  16125. return PointerEventTypes._POINTERDOWN;
  16126. },
  16127. enumerable: true,
  16128. configurable: true
  16129. });
  16130. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16131. get: function () {
  16132. return PointerEventTypes._POINTERUP;
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16138. get: function () {
  16139. return PointerEventTypes._POINTERMOVE;
  16140. },
  16141. enumerable: true,
  16142. configurable: true
  16143. });
  16144. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16145. get: function () {
  16146. return PointerEventTypes._POINTERWHEEL;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16152. get: function () {
  16153. return PointerEventTypes._POINTERPICK;
  16154. },
  16155. enumerable: true,
  16156. configurable: true
  16157. });
  16158. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  16159. get: function () {
  16160. return PointerEventTypes._POINTERTAP;
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  16166. get: function () {
  16167. return PointerEventTypes._POINTERDOUBLETAP;
  16168. },
  16169. enumerable: true,
  16170. configurable: true
  16171. });
  16172. PointerEventTypes._POINTERDOWN = 0x01;
  16173. PointerEventTypes._POINTERUP = 0x02;
  16174. PointerEventTypes._POINTERMOVE = 0x04;
  16175. PointerEventTypes._POINTERWHEEL = 0x08;
  16176. PointerEventTypes._POINTERPICK = 0x10;
  16177. PointerEventTypes._POINTERTAP = 0x20;
  16178. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  16179. return PointerEventTypes;
  16180. }());
  16181. BABYLON.PointerEventTypes = PointerEventTypes;
  16182. var PointerInfoBase = (function () {
  16183. function PointerInfoBase(type, event) {
  16184. this.type = type;
  16185. this.event = event;
  16186. }
  16187. return PointerInfoBase;
  16188. }());
  16189. BABYLON.PointerInfoBase = PointerInfoBase;
  16190. /**
  16191. * This class is used to store pointer related info for the onPrePointerObservable event.
  16192. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16193. */
  16194. var PointerInfoPre = (function (_super) {
  16195. __extends(PointerInfoPre, _super);
  16196. function PointerInfoPre(type, event, localX, localY) {
  16197. var _this = _super.call(this, type, event) || this;
  16198. _this.skipOnPointerObservable = false;
  16199. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16200. return _this;
  16201. }
  16202. return PointerInfoPre;
  16203. }(PointerInfoBase));
  16204. BABYLON.PointerInfoPre = PointerInfoPre;
  16205. /**
  16206. * This type contains all the data related to a pointer event in Babylon.js.
  16207. * 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.
  16208. */
  16209. var PointerInfo = (function (_super) {
  16210. __extends(PointerInfo, _super);
  16211. function PointerInfo(type, event, pickInfo) {
  16212. var _this = _super.call(this, type, event) || this;
  16213. _this.pickInfo = pickInfo;
  16214. return _this;
  16215. }
  16216. return PointerInfo;
  16217. }(PointerInfoBase));
  16218. BABYLON.PointerInfo = PointerInfo;
  16219. /**
  16220. * This class is used by the onRenderingGroupObservable
  16221. */
  16222. var RenderingGroupInfo = (function () {
  16223. function RenderingGroupInfo() {
  16224. }
  16225. /**
  16226. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16227. * This stage will be fired no matter what
  16228. */
  16229. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16230. /**
  16231. * Called before opaque object are rendered.
  16232. * This stage will be fired only if there's 3D Opaque content to render
  16233. */
  16234. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16235. /**
  16236. * Called after the opaque objects are rendered and before the transparent ones
  16237. * This stage will be fired only if there's 3D transparent content to render
  16238. */
  16239. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16240. /**
  16241. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16242. * This stage will be fired no matter what
  16243. */
  16244. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16245. return RenderingGroupInfo;
  16246. }());
  16247. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16248. /**
  16249. * Represents a scene to be rendered by the engine.
  16250. * @see http://doc.babylonjs.com/page.php?p=21911
  16251. */
  16252. var Scene = (function () {
  16253. /**
  16254. * @constructor
  16255. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16256. */
  16257. function Scene(engine) {
  16258. // Members
  16259. this.autoClear = true;
  16260. this.autoClearDepthAndStencil = true;
  16261. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16262. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16263. this.forceWireframe = false;
  16264. this._forcePointsCloud = false;
  16265. this.forceShowBoundingBoxes = false;
  16266. this.animationsEnabled = true;
  16267. this.constantlyUpdateMeshUnderPointer = false;
  16268. this.hoverCursor = "pointer";
  16269. this.defaultCursor = "";
  16270. // Metadata
  16271. this.metadata = null;
  16272. // Events
  16273. /**
  16274. * An event triggered when the scene is disposed.
  16275. * @type {BABYLON.Observable}
  16276. */
  16277. this.onDisposeObservable = new BABYLON.Observable();
  16278. /**
  16279. * An event triggered before rendering the scene
  16280. * @type {BABYLON.Observable}
  16281. */
  16282. this.onBeforeRenderObservable = new BABYLON.Observable();
  16283. /**
  16284. * An event triggered after rendering the scene
  16285. * @type {BABYLON.Observable}
  16286. */
  16287. this.onAfterRenderObservable = new BABYLON.Observable();
  16288. /**
  16289. * An event triggered when the scene is ready
  16290. * @type {BABYLON.Observable}
  16291. */
  16292. this.onReadyObservable = new BABYLON.Observable();
  16293. /**
  16294. * An event triggered before rendering a camera
  16295. * @type {BABYLON.Observable}
  16296. */
  16297. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16298. /**
  16299. * An event triggered after rendering a camera
  16300. * @type {BABYLON.Observable}
  16301. */
  16302. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16303. /**
  16304. * An event triggered when a camera is created
  16305. * @type {BABYLON.Observable}
  16306. */
  16307. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16308. /**
  16309. * An event triggered when a camera is removed
  16310. * @type {BABYLON.Observable}
  16311. */
  16312. this.onCameraRemovedObservable = new BABYLON.Observable();
  16313. /**
  16314. * An event triggered when a light is created
  16315. * @type {BABYLON.Observable}
  16316. */
  16317. this.onNewLightAddedObservable = new BABYLON.Observable();
  16318. /**
  16319. * An event triggered when a light is removed
  16320. * @type {BABYLON.Observable}
  16321. */
  16322. this.onLightRemovedObservable = new BABYLON.Observable();
  16323. /**
  16324. * An event triggered when a geometry is created
  16325. * @type {BABYLON.Observable}
  16326. */
  16327. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16328. /**
  16329. * An event triggered when a geometry is removed
  16330. * @type {BABYLON.Observable}
  16331. */
  16332. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16333. /**
  16334. * An event triggered when a mesh is created
  16335. * @type {BABYLON.Observable}
  16336. */
  16337. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16338. /**
  16339. * An event triggered when a mesh is removed
  16340. * @type {BABYLON.Observable}
  16341. */
  16342. this.onMeshRemovedObservable = new BABYLON.Observable();
  16343. /**
  16344. * An event triggered before calculating deterministic simulation step
  16345. * @type {BABYLON.Observable}
  16346. */
  16347. this.onBeforeStepObservable = new BABYLON.Observable();
  16348. /**
  16349. * An event triggered after calculating deterministic simulation step
  16350. * @type {BABYLON.Observable}
  16351. */
  16352. this.onAfterStepObservable = new BABYLON.Observable();
  16353. /**
  16354. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16355. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16356. * 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)
  16357. */
  16358. this.onRenderingGroupObservable = new BABYLON.Observable();
  16359. // Animations
  16360. this.animations = [];
  16361. /**
  16362. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  16363. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16364. */
  16365. this.onPrePointerObservable = new BABYLON.Observable();
  16366. /**
  16367. * Observable event triggered each time an input event is received from the rendering canvas
  16368. */
  16369. this.onPointerObservable = new BABYLON.Observable();
  16370. this._meshPickProceed = false;
  16371. this._previousHasSwiped = false;
  16372. this._currentPickResult = null;
  16373. this._previousPickResult = null;
  16374. this._isButtonPressed = false;
  16375. this._doubleClickOccured = false;
  16376. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16377. this.cameraToUseForPointers = null;
  16378. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16379. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16380. this._startingPointerTime = 0;
  16381. this._previousStartingPointerTime = 0;
  16382. // Deterministic lockstep
  16383. this._timeAccumulator = 0;
  16384. this._currentStepId = 0;
  16385. this._currentInternalStep = 0;
  16386. // Coordinate system
  16387. /**
  16388. * use right-handed coordinate system on this scene.
  16389. * @type {boolean}
  16390. */
  16391. this._useRightHandedSystem = false;
  16392. // Fog
  16393. this._fogEnabled = true;
  16394. this._fogMode = Scene.FOGMODE_NONE;
  16395. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16396. this.fogDensity = 0.1;
  16397. this.fogStart = 0;
  16398. this.fogEnd = 1000.0;
  16399. // Lights
  16400. /**
  16401. * is shadow enabled on this scene.
  16402. * @type {boolean}
  16403. */
  16404. this._shadowsEnabled = true;
  16405. /**
  16406. * is light enabled on this scene.
  16407. * @type {boolean}
  16408. */
  16409. this._lightsEnabled = true;
  16410. /**
  16411. * All of the lights added to this scene.
  16412. * @see BABYLON.Light
  16413. * @type {BABYLON.Light[]}
  16414. */
  16415. this.lights = new Array();
  16416. // Cameras
  16417. /** All of the cameras added to this scene. */
  16418. this.cameras = new Array();
  16419. /** All of the active cameras added to this scene. */
  16420. this.activeCameras = new Array();
  16421. // Meshes
  16422. /**
  16423. * All of the (abstract) meshes added to this scene.
  16424. * @see BABYLON.AbstractMesh
  16425. * @type {BABYLON.AbstractMesh[]}
  16426. */
  16427. this.meshes = new Array();
  16428. // Geometries
  16429. this._geometries = new Array();
  16430. this.materials = new Array();
  16431. this.multiMaterials = new Array();
  16432. // Textures
  16433. this._texturesEnabled = true;
  16434. this.textures = new Array();
  16435. // Particles
  16436. this.particlesEnabled = true;
  16437. this.particleSystems = new Array();
  16438. // Sprites
  16439. this.spritesEnabled = true;
  16440. this.spriteManagers = new Array();
  16441. // Layers
  16442. this.layers = new Array();
  16443. this.highlightLayers = new Array();
  16444. // Skeletons
  16445. this._skeletonsEnabled = true;
  16446. this.skeletons = new Array();
  16447. // Morph targets
  16448. this.morphTargetManagers = new Array();
  16449. // Lens flares
  16450. this.lensFlaresEnabled = true;
  16451. this.lensFlareSystems = new Array();
  16452. // Collisions
  16453. this.collisionsEnabled = true;
  16454. /** Defines the gravity applied to this scene */
  16455. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16456. // Postprocesses
  16457. this.postProcesses = new Array();
  16458. this.postProcessesEnabled = true;
  16459. // Customs render targets
  16460. this.renderTargetsEnabled = true;
  16461. this.dumpNextRenderTargets = false;
  16462. this.customRenderTargets = new Array();
  16463. // Imported meshes
  16464. this.importedMeshesFiles = new Array();
  16465. // Probes
  16466. this.probesEnabled = true;
  16467. this.reflectionProbes = new Array();
  16468. this._actionManagers = new Array();
  16469. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16470. // Procedural textures
  16471. this.proceduralTexturesEnabled = true;
  16472. this._proceduralTextures = new Array();
  16473. this.soundTracks = new Array();
  16474. this._audioEnabled = true;
  16475. this._headphone = false;
  16476. // Performance counters
  16477. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16478. this._totalLightsCounter = new BABYLON.PerfCounter();
  16479. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16480. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16481. this._totalVertices = new BABYLON.PerfCounter();
  16482. this._activeIndices = new BABYLON.PerfCounter();
  16483. this._activeParticles = new BABYLON.PerfCounter();
  16484. this._lastFrameDuration = new BABYLON.PerfCounter();
  16485. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16486. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16487. this._particlesDuration = new BABYLON.PerfCounter();
  16488. this._renderDuration = new BABYLON.PerfCounter();
  16489. this._spritesDuration = new BABYLON.PerfCounter();
  16490. this._activeBones = new BABYLON.PerfCounter();
  16491. this._animationTime = 0;
  16492. this.animationTimeScale = 1;
  16493. this._renderId = 0;
  16494. this._executeWhenReadyTimeoutId = -1;
  16495. this._intermediateRendering = false;
  16496. this._viewUpdateFlag = -1;
  16497. this._projectionUpdateFlag = -1;
  16498. this._toBeDisposed = new BABYLON.SmartArray(256);
  16499. this._pendingData = []; //ANY
  16500. this._activeMeshes = new BABYLON.SmartArray(256);
  16501. this._processedMaterials = new BABYLON.SmartArray(256);
  16502. this._renderTargets = new BABYLON.SmartArray(256);
  16503. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16504. this._activeSkeletons = new BABYLON.SmartArray(32);
  16505. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16506. this._activeAnimatables = new Array();
  16507. this._transformMatrix = BABYLON.Matrix.Zero();
  16508. this.requireLightSorting = false;
  16509. this._uniqueIdCounter = 0;
  16510. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16511. this._engine.scenes.push(this);
  16512. this._uid = null;
  16513. this._renderingManager = new BABYLON.RenderingManager(this);
  16514. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16515. if (BABYLON.OutlineRenderer) {
  16516. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16517. }
  16518. this.attachControl();
  16519. if (BABYLON.SoundTrack) {
  16520. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16521. }
  16522. //simplification queue
  16523. if (BABYLON.SimplificationQueue) {
  16524. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16525. }
  16526. //collision coordinator initialization. For now legacy per default.
  16527. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16528. // Uniform Buffer
  16529. this._createUbo();
  16530. // Default Image processing definition.
  16531. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16532. }
  16533. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16534. /** The fog is deactivated */
  16535. get: function () {
  16536. return Scene._FOGMODE_NONE;
  16537. },
  16538. enumerable: true,
  16539. configurable: true
  16540. });
  16541. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16542. /** The fog density is following an exponential function */
  16543. get: function () {
  16544. return Scene._FOGMODE_EXP;
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16550. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16551. get: function () {
  16552. return Scene._FOGMODE_EXP2;
  16553. },
  16554. enumerable: true,
  16555. configurable: true
  16556. });
  16557. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16558. /** The fog density is following a linear function. */
  16559. get: function () {
  16560. return Scene._FOGMODE_LINEAR;
  16561. },
  16562. enumerable: true,
  16563. configurable: true
  16564. });
  16565. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16566. /**
  16567. * Texture used in all pbr material as the reflection texture.
  16568. * As in the majority of the scene they are the same (exception for multi room and so on),
  16569. * this is easier to reference from here than from all the materials.
  16570. */
  16571. get: function () {
  16572. return this._environmentTexture;
  16573. },
  16574. /**
  16575. * Texture used in all pbr material as the reflection texture.
  16576. * As in the majority of the scene they are the same (exception for multi room and so on),
  16577. * this is easier to set here than in all the materials.
  16578. */
  16579. set: function (value) {
  16580. this._environmentTexture = value;
  16581. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16582. },
  16583. enumerable: true,
  16584. configurable: true
  16585. });
  16586. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16587. /**
  16588. * Default image processing configuration used either in the rendering
  16589. * Forward main pass or through the imageProcessingPostProcess if present.
  16590. * As in the majority of the scene they are the same (exception for multi camera),
  16591. * this is easier to reference from here than from all the materials and post process.
  16592. *
  16593. * No setter as we it is a shared configuration, you can set the values instead.
  16594. */
  16595. get: function () {
  16596. return this._imageProcessingConfiguration;
  16597. },
  16598. enumerable: true,
  16599. configurable: true
  16600. });
  16601. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16602. get: function () {
  16603. return this._forcePointsCloud;
  16604. },
  16605. set: function (value) {
  16606. if (this._forcePointsCloud === value) {
  16607. return;
  16608. }
  16609. this._forcePointsCloud = value;
  16610. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16611. },
  16612. enumerable: true,
  16613. configurable: true
  16614. });
  16615. Object.defineProperty(Scene.prototype, "onDispose", {
  16616. /** A function to be executed when this scene is disposed. */
  16617. set: function (callback) {
  16618. if (this._onDisposeObserver) {
  16619. this.onDisposeObservable.remove(this._onDisposeObserver);
  16620. }
  16621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16622. },
  16623. enumerable: true,
  16624. configurable: true
  16625. });
  16626. Object.defineProperty(Scene.prototype, "beforeRender", {
  16627. /** A function to be executed before rendering this scene */
  16628. set: function (callback) {
  16629. if (this._onBeforeRenderObserver) {
  16630. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16631. }
  16632. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16633. },
  16634. enumerable: true,
  16635. configurable: true
  16636. });
  16637. Object.defineProperty(Scene.prototype, "afterRender", {
  16638. /** A function to be executed after rendering this scene */
  16639. set: function (callback) {
  16640. if (this._onAfterRenderObserver) {
  16641. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16642. }
  16643. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16644. },
  16645. enumerable: true,
  16646. configurable: true
  16647. });
  16648. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16649. set: function (callback) {
  16650. if (this._onBeforeCameraRenderObserver) {
  16651. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16652. }
  16653. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16654. },
  16655. enumerable: true,
  16656. configurable: true
  16657. });
  16658. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16659. set: function (callback) {
  16660. if (this._onAfterCameraRenderObserver) {
  16661. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16662. }
  16663. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16664. },
  16665. enumerable: true,
  16666. configurable: true
  16667. });
  16668. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16669. get: function () {
  16670. if (!this._gamepadManager) {
  16671. this._gamepadManager = new BABYLON.GamepadManager();
  16672. }
  16673. return this._gamepadManager;
  16674. },
  16675. enumerable: true,
  16676. configurable: true
  16677. });
  16678. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16679. get: function () {
  16680. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16681. },
  16682. enumerable: true,
  16683. configurable: true
  16684. });
  16685. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16686. get: function () {
  16687. return this._useRightHandedSystem;
  16688. },
  16689. set: function (value) {
  16690. if (this._useRightHandedSystem === value) {
  16691. return;
  16692. }
  16693. this._useRightHandedSystem = value;
  16694. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16695. },
  16696. enumerable: true,
  16697. configurable: true
  16698. });
  16699. Scene.prototype.setStepId = function (newStepId) {
  16700. this._currentStepId = newStepId;
  16701. };
  16702. ;
  16703. Scene.prototype.getStepId = function () {
  16704. return this._currentStepId;
  16705. };
  16706. ;
  16707. Scene.prototype.getInternalStep = function () {
  16708. return this._currentInternalStep;
  16709. };
  16710. ;
  16711. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16712. get: function () {
  16713. return this._fogEnabled;
  16714. },
  16715. /**
  16716. * is fog enabled on this scene.
  16717. */
  16718. set: function (value) {
  16719. if (this._fogEnabled === value) {
  16720. return;
  16721. }
  16722. this._fogEnabled = value;
  16723. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16724. },
  16725. enumerable: true,
  16726. configurable: true
  16727. });
  16728. Object.defineProperty(Scene.prototype, "fogMode", {
  16729. get: function () {
  16730. return this._fogMode;
  16731. },
  16732. set: function (value) {
  16733. if (this._fogMode === value) {
  16734. return;
  16735. }
  16736. this._fogMode = value;
  16737. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16738. },
  16739. enumerable: true,
  16740. configurable: true
  16741. });
  16742. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16743. get: function () {
  16744. return this._shadowsEnabled;
  16745. },
  16746. set: function (value) {
  16747. if (this._shadowsEnabled === value) {
  16748. return;
  16749. }
  16750. this._shadowsEnabled = value;
  16751. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16752. },
  16753. enumerable: true,
  16754. configurable: true
  16755. });
  16756. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16757. get: function () {
  16758. return this._lightsEnabled;
  16759. },
  16760. set: function (value) {
  16761. if (this._lightsEnabled === value) {
  16762. return;
  16763. }
  16764. this._lightsEnabled = value;
  16765. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16766. },
  16767. enumerable: true,
  16768. configurable: true
  16769. });
  16770. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16771. /** The default material used on meshes when no material is affected */
  16772. get: function () {
  16773. if (!this._defaultMaterial) {
  16774. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16775. }
  16776. return this._defaultMaterial;
  16777. },
  16778. /** The default material used on meshes when no material is affected */
  16779. set: function (value) {
  16780. this._defaultMaterial = value;
  16781. },
  16782. enumerable: true,
  16783. configurable: true
  16784. });
  16785. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16786. get: function () {
  16787. return this._texturesEnabled;
  16788. },
  16789. set: function (value) {
  16790. if (this._texturesEnabled === value) {
  16791. return;
  16792. }
  16793. this._texturesEnabled = value;
  16794. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16795. },
  16796. enumerable: true,
  16797. configurable: true
  16798. });
  16799. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16800. get: function () {
  16801. return this._skeletonsEnabled;
  16802. },
  16803. set: function (value) {
  16804. if (this._skeletonsEnabled === value) {
  16805. return;
  16806. }
  16807. this._skeletonsEnabled = value;
  16808. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16809. },
  16810. enumerable: true,
  16811. configurable: true
  16812. });
  16813. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16814. get: function () {
  16815. if (!this._postProcessRenderPipelineManager) {
  16816. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16817. }
  16818. return this._postProcessRenderPipelineManager;
  16819. },
  16820. enumerable: true,
  16821. configurable: true
  16822. });
  16823. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16824. get: function () {
  16825. return this._frustumPlanes;
  16826. },
  16827. enumerable: true,
  16828. configurable: true
  16829. });
  16830. Object.defineProperty(Scene.prototype, "debugLayer", {
  16831. // Properties
  16832. get: function () {
  16833. if (!this._debugLayer) {
  16834. this._debugLayer = new BABYLON.DebugLayer(this);
  16835. }
  16836. return this._debugLayer;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16842. get: function () {
  16843. return this._workerCollisions;
  16844. },
  16845. set: function (enabled) {
  16846. if (!BABYLON.CollisionCoordinatorLegacy) {
  16847. return;
  16848. }
  16849. enabled = (enabled && !!Worker);
  16850. this._workerCollisions = enabled;
  16851. if (this.collisionCoordinator) {
  16852. this.collisionCoordinator.destroy();
  16853. }
  16854. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16855. this.collisionCoordinator.init(this);
  16856. },
  16857. enumerable: true,
  16858. configurable: true
  16859. });
  16860. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16861. get: function () {
  16862. return this._selectionOctree;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16868. /**
  16869. * The mesh that is currently under the pointer.
  16870. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16871. */
  16872. get: function () {
  16873. return this._pointerOverMesh;
  16874. },
  16875. enumerable: true,
  16876. configurable: true
  16877. });
  16878. Object.defineProperty(Scene.prototype, "pointerX", {
  16879. /**
  16880. * Current on-screen X position of the pointer
  16881. * @return {number} X position of the pointer
  16882. */
  16883. get: function () {
  16884. return this._pointerX;
  16885. },
  16886. enumerable: true,
  16887. configurable: true
  16888. });
  16889. Object.defineProperty(Scene.prototype, "pointerY", {
  16890. /**
  16891. * Current on-screen Y position of the pointer
  16892. * @return {number} Y position of the pointer
  16893. */
  16894. get: function () {
  16895. return this._pointerY;
  16896. },
  16897. enumerable: true,
  16898. configurable: true
  16899. });
  16900. Scene.prototype.getCachedMaterial = function () {
  16901. return this._cachedMaterial;
  16902. };
  16903. Scene.prototype.getCachedEffect = function () {
  16904. return this._cachedEffect;
  16905. };
  16906. Scene.prototype.getCachedVisibility = function () {
  16907. return this._cachedVisibility;
  16908. };
  16909. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16910. if (visibility === void 0) { visibility = 1; }
  16911. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16912. };
  16913. Scene.prototype.getBoundingBoxRenderer = function () {
  16914. if (!this._boundingBoxRenderer) {
  16915. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16916. }
  16917. return this._boundingBoxRenderer;
  16918. };
  16919. Scene.prototype.getOutlineRenderer = function () {
  16920. return this._outlineRenderer;
  16921. };
  16922. Scene.prototype.getEngine = function () {
  16923. return this._engine;
  16924. };
  16925. Scene.prototype.getTotalVertices = function () {
  16926. return this._totalVertices.current;
  16927. };
  16928. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16929. get: function () {
  16930. return this._totalVertices;
  16931. },
  16932. enumerable: true,
  16933. configurable: true
  16934. });
  16935. Scene.prototype.getActiveIndices = function () {
  16936. return this._activeIndices.current;
  16937. };
  16938. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16939. get: function () {
  16940. return this._activeIndices;
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Scene.prototype.getActiveParticles = function () {
  16946. return this._activeParticles.current;
  16947. };
  16948. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16949. get: function () {
  16950. return this._activeParticles;
  16951. },
  16952. enumerable: true,
  16953. configurable: true
  16954. });
  16955. Scene.prototype.getActiveBones = function () {
  16956. return this._activeBones.current;
  16957. };
  16958. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16959. get: function () {
  16960. return this._activeBones;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. // Stats
  16966. Scene.prototype.getLastFrameDuration = function () {
  16967. return this._lastFrameDuration.current;
  16968. };
  16969. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16970. get: function () {
  16971. return this._lastFrameDuration;
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16977. return this._evaluateActiveMeshesDuration.current;
  16978. };
  16979. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16980. get: function () {
  16981. return this._evaluateActiveMeshesDuration;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Scene.prototype.getActiveMeshes = function () {
  16987. return this._activeMeshes;
  16988. };
  16989. Scene.prototype.getRenderTargetsDuration = function () {
  16990. return this._renderTargetsDuration.current;
  16991. };
  16992. Scene.prototype.getRenderDuration = function () {
  16993. return this._renderDuration.current;
  16994. };
  16995. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16996. get: function () {
  16997. return this._renderDuration;
  16998. },
  16999. enumerable: true,
  17000. configurable: true
  17001. });
  17002. Scene.prototype.getParticlesDuration = function () {
  17003. return this._particlesDuration.current;
  17004. };
  17005. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17006. get: function () {
  17007. return this._particlesDuration;
  17008. },
  17009. enumerable: true,
  17010. configurable: true
  17011. });
  17012. Scene.prototype.getSpritesDuration = function () {
  17013. return this._spritesDuration.current;
  17014. };
  17015. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17016. get: function () {
  17017. return this._spritesDuration;
  17018. },
  17019. enumerable: true,
  17020. configurable: true
  17021. });
  17022. Scene.prototype.getAnimationRatio = function () {
  17023. return this._animationRatio;
  17024. };
  17025. Scene.prototype.getRenderId = function () {
  17026. return this._renderId;
  17027. };
  17028. Scene.prototype.incrementRenderId = function () {
  17029. this._renderId++;
  17030. };
  17031. Scene.prototype._updatePointerPosition = function (evt) {
  17032. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17033. this._pointerX = evt.clientX - canvasRect.left;
  17034. this._pointerY = evt.clientY - canvasRect.top;
  17035. this._unTranslatedPointerX = this._pointerX;
  17036. this._unTranslatedPointerY = this._pointerY;
  17037. };
  17038. Scene.prototype._createUbo = function () {
  17039. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17040. this._sceneUbo.addUniform("viewProjection", 16);
  17041. this._sceneUbo.addUniform("view", 16);
  17042. };
  17043. // Pointers handling
  17044. /**
  17045. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17046. * @param attachUp defines if you want to attach events to pointerup
  17047. * @param attachDown defines if you want to attach events to pointerdown
  17048. * @param attachMove defines if you want to attach events to pointermove
  17049. */
  17050. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17051. var _this = this;
  17052. if (attachUp === void 0) { attachUp = true; }
  17053. if (attachDown === void 0) { attachDown = true; }
  17054. if (attachMove === void 0) { attachMove = true; }
  17055. this._initActionManager = function (act, clickInfo) {
  17056. if (!_this._meshPickProceed) {
  17057. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17058. _this._currentPickResult = pickResult;
  17059. if (pickResult) {
  17060. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17061. }
  17062. _this._meshPickProceed = true;
  17063. }
  17064. return act;
  17065. };
  17066. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17067. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17068. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17069. btn !== _this._previousButtonPressed) {
  17070. _this._doubleClickOccured = false;
  17071. clickInfo.singleClick = true;
  17072. clickInfo.ignore = false;
  17073. cb(clickInfo, _this._currentPickResult);
  17074. }
  17075. };
  17076. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17077. var clickInfo = new ClickInfo();
  17078. _this._currentPickResult = null;
  17079. var act;
  17080. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  17081. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  17082. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17083. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17084. act = _this._initActionManager(act, clickInfo);
  17085. if (act)
  17086. checkPicking = act.hasPickTriggers;
  17087. }
  17088. if (checkPicking) {
  17089. var btn = evt.button;
  17090. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17091. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17092. if (!clickInfo.hasSwiped) {
  17093. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17094. if (!checkSingleClickImmediately) {
  17095. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  17096. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17097. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17098. act = _this._initActionManager(act, clickInfo);
  17099. if (act)
  17100. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17101. }
  17102. }
  17103. if (checkSingleClickImmediately) {
  17104. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17105. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17106. btn !== _this._previousButtonPressed) {
  17107. clickInfo.singleClick = true;
  17108. cb(clickInfo, _this._currentPickResult);
  17109. }
  17110. }
  17111. else {
  17112. // wait that no double click has been raised during the double click delay
  17113. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17114. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17115. }
  17116. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  17117. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17118. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17119. act = _this._initActionManager(act, clickInfo);
  17120. if (act)
  17121. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17122. }
  17123. if (checkDoubleClick) {
  17124. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17125. if (btn === _this._previousButtonPressed &&
  17126. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17127. !_this._doubleClickOccured) {
  17128. // pointer has not moved for 2 clicks, it's a double click
  17129. if (!clickInfo.hasSwiped &&
  17130. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17131. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17132. _this._previousStartingPointerTime = 0;
  17133. _this._doubleClickOccured = true;
  17134. clickInfo.doubleClick = true;
  17135. clickInfo.ignore = false;
  17136. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17137. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17138. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17139. cb(clickInfo, _this._currentPickResult);
  17140. }
  17141. else {
  17142. _this._doubleClickOccured = false;
  17143. _this._previousStartingPointerTime = _this._startingPointerTime;
  17144. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17145. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17146. _this._previousButtonPressed = btn;
  17147. _this._previousHasSwiped = clickInfo.hasSwiped;
  17148. if (Scene.ExclusiveDoubleClickMode) {
  17149. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17150. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17151. }
  17152. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17153. cb(clickInfo, _this._previousPickResult);
  17154. }
  17155. else {
  17156. cb(clickInfo, _this._currentPickResult);
  17157. }
  17158. }
  17159. }
  17160. else {
  17161. _this._doubleClickOccured = false;
  17162. _this._previousStartingPointerTime = _this._startingPointerTime;
  17163. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17164. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17165. _this._previousButtonPressed = btn;
  17166. _this._previousHasSwiped = clickInfo.hasSwiped;
  17167. }
  17168. }
  17169. }
  17170. }
  17171. clickInfo.ignore = true;
  17172. cb(clickInfo, _this._currentPickResult);
  17173. };
  17174. var spritePredicate = function (sprite) {
  17175. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17176. };
  17177. this._onPointerMove = function (evt) {
  17178. _this._updatePointerPosition(evt);
  17179. // PreObservable support
  17180. if (_this.onPrePointerObservable.hasObservers()) {
  17181. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17182. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17183. _this.onPrePointerObservable.notifyObservers(pi, type);
  17184. if (pi.skipOnPointerObservable) {
  17185. return;
  17186. }
  17187. }
  17188. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17189. return;
  17190. }
  17191. var canvas = _this._engine.getRenderingCanvas();
  17192. if (!_this.pointerMovePredicate) {
  17193. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17194. }
  17195. // Meshes
  17196. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17197. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17198. _this.setPointerOverSprite(null);
  17199. _this.setPointerOverMesh(pickResult.pickedMesh);
  17200. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17201. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17202. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17203. }
  17204. else {
  17205. canvas.style.cursor = _this.hoverCursor;
  17206. }
  17207. }
  17208. else {
  17209. canvas.style.cursor = _this.defaultCursor;
  17210. }
  17211. }
  17212. else {
  17213. _this.setPointerOverMesh(null);
  17214. // Sprites
  17215. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17216. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17217. _this.setPointerOverSprite(pickResult.pickedSprite);
  17218. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17219. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17220. }
  17221. else {
  17222. canvas.style.cursor = _this.hoverCursor;
  17223. }
  17224. }
  17225. else {
  17226. _this.setPointerOverSprite(null);
  17227. // Restore pointer
  17228. canvas.style.cursor = _this.defaultCursor;
  17229. }
  17230. }
  17231. if (_this.onPointerMove) {
  17232. _this.onPointerMove(evt, pickResult);
  17233. }
  17234. if (_this.onPointerObservable.hasObservers()) {
  17235. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17236. var pi = new PointerInfo(type, evt, pickResult);
  17237. _this.onPointerObservable.notifyObservers(pi, type);
  17238. }
  17239. };
  17240. this._onPointerDown = function (evt) {
  17241. _this._isButtonPressed = true;
  17242. _this._pickedDownMesh = null;
  17243. _this._meshPickProceed = false;
  17244. _this._updatePointerPosition(evt);
  17245. // PreObservable support
  17246. if (_this.onPrePointerObservable.hasObservers()) {
  17247. var type = PointerEventTypes.POINTERDOWN;
  17248. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17249. _this.onPrePointerObservable.notifyObservers(pi, type);
  17250. if (pi.skipOnPointerObservable) {
  17251. return;
  17252. }
  17253. }
  17254. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17255. return;
  17256. }
  17257. _this._startingPointerPosition.x = _this._pointerX;
  17258. _this._startingPointerPosition.y = _this._pointerY;
  17259. _this._startingPointerTime = new Date().getTime();
  17260. if (!_this.pointerDownPredicate) {
  17261. _this.pointerDownPredicate = function (mesh) {
  17262. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17263. };
  17264. }
  17265. // Meshes
  17266. _this._pickedDownMesh = null;
  17267. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17268. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17269. _this._pickedDownMesh = pickResult.pickedMesh;
  17270. var actionManager = pickResult.pickedMesh.actionManager;
  17271. if (actionManager) {
  17272. if (actionManager.hasPickTriggers) {
  17273. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17274. switch (evt.button) {
  17275. case 0:
  17276. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17277. break;
  17278. case 1:
  17279. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17280. break;
  17281. case 2:
  17282. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17283. break;
  17284. }
  17285. }
  17286. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17287. window.setTimeout((function () {
  17288. var _this = this;
  17289. 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);
  17290. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17291. if (this._isButtonPressed &&
  17292. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17293. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17294. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17295. this._startingPointerTime = 0;
  17296. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17297. }
  17298. }
  17299. }).bind(_this), Scene.LongPressDelay);
  17300. }
  17301. }
  17302. }
  17303. if (_this.onPointerDown) {
  17304. _this.onPointerDown(evt, pickResult);
  17305. }
  17306. if (_this.onPointerObservable.hasObservers()) {
  17307. var type = PointerEventTypes.POINTERDOWN;
  17308. var pi = new PointerInfo(type, evt, pickResult);
  17309. _this.onPointerObservable.notifyObservers(pi, type);
  17310. }
  17311. // Sprites
  17312. _this._pickedDownSprite = null;
  17313. if (_this.spriteManagers.length > 0) {
  17314. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17315. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17316. if (pickResult.pickedSprite.actionManager) {
  17317. _this._pickedDownSprite = pickResult.pickedSprite;
  17318. switch (evt.button) {
  17319. case 0:
  17320. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17321. break;
  17322. case 1:
  17323. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17324. break;
  17325. case 2:
  17326. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17327. break;
  17328. }
  17329. if (pickResult.pickedSprite.actionManager) {
  17330. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17331. }
  17332. }
  17333. }
  17334. }
  17335. };
  17336. this._onPointerUp = function (evt) {
  17337. _this._isButtonPressed = false;
  17338. _this._pickedUpMesh = null;
  17339. _this._meshPickProceed = false;
  17340. _this._updatePointerPosition(evt);
  17341. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17342. // PreObservable support
  17343. if (this.onPrePointerObservable.hasObservers()) {
  17344. if (!clickInfo.ignore) {
  17345. if (!clickInfo.hasSwiped) {
  17346. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17347. var type = PointerEventTypes.POINTERTAP;
  17348. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17349. this.onPrePointerObservable.notifyObservers(pi, type);
  17350. if (pi.skipOnPointerObservable) {
  17351. return;
  17352. }
  17353. }
  17354. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17355. var type = PointerEventTypes.POINTERDOUBLETAP;
  17356. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17357. this.onPrePointerObservable.notifyObservers(pi, type);
  17358. if (pi.skipOnPointerObservable) {
  17359. return;
  17360. }
  17361. }
  17362. }
  17363. }
  17364. else {
  17365. var type = PointerEventTypes.POINTERUP;
  17366. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17367. this.onPrePointerObservable.notifyObservers(pi, type);
  17368. if (pi.skipOnPointerObservable) {
  17369. return;
  17370. }
  17371. }
  17372. }
  17373. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17374. return;
  17375. }
  17376. if (!this.pointerUpPredicate) {
  17377. this.pointerUpPredicate = function (mesh) {
  17378. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17379. };
  17380. }
  17381. // Meshes
  17382. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17383. this._initActionManager(null, clickInfo);
  17384. }
  17385. if (!pickResult) {
  17386. pickResult = this._currentPickResult;
  17387. }
  17388. if (pickResult && pickResult && pickResult.pickedMesh) {
  17389. this._pickedUpMesh = pickResult.pickedMesh;
  17390. if (this._pickedDownMesh === this._pickedUpMesh) {
  17391. if (this.onPointerPick) {
  17392. this.onPointerPick(evt, pickResult);
  17393. }
  17394. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17395. var type = PointerEventTypes.POINTERPICK;
  17396. var pi = new PointerInfo(type, evt, pickResult);
  17397. this.onPointerObservable.notifyObservers(pi, type);
  17398. }
  17399. }
  17400. if (pickResult.pickedMesh.actionManager) {
  17401. if (clickInfo.ignore) {
  17402. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17403. }
  17404. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17405. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17406. }
  17407. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17408. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17409. }
  17410. }
  17411. }
  17412. if (this._pickedDownMesh &&
  17413. this._pickedDownMesh.actionManager &&
  17414. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17415. this._pickedDownMesh !== this._pickedUpMesh) {
  17416. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17417. }
  17418. if (this.onPointerUp) {
  17419. this.onPointerUp(evt, pickResult);
  17420. }
  17421. if (this.onPointerObservable.hasObservers()) {
  17422. if (!clickInfo.ignore) {
  17423. if (!clickInfo.hasSwiped) {
  17424. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17425. var type = PointerEventTypes.POINTERTAP;
  17426. var pi = new PointerInfo(type, evt, pickResult);
  17427. this.onPointerObservable.notifyObservers(pi, type);
  17428. }
  17429. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17430. var type = PointerEventTypes.POINTERDOUBLETAP;
  17431. var pi = new PointerInfo(type, evt, pickResult);
  17432. this.onPointerObservable.notifyObservers(pi, type);
  17433. }
  17434. }
  17435. }
  17436. else {
  17437. var type = PointerEventTypes.POINTERUP;
  17438. var pi = new PointerInfo(type, evt, pickResult);
  17439. this.onPointerObservable.notifyObservers(pi, type);
  17440. }
  17441. }
  17442. // Sprites
  17443. if (this.spriteManagers.length > 0) {
  17444. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17445. if (pickResult.hit && pickResult.pickedSprite) {
  17446. if (pickResult.pickedSprite.actionManager) {
  17447. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17448. if (pickResult.pickedSprite.actionManager) {
  17449. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17450. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17451. }
  17452. }
  17453. }
  17454. }
  17455. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17456. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17457. }
  17458. }
  17459. this._previousPickResult = this._currentPickResult;
  17460. }).bind(_this));
  17461. };
  17462. this._onKeyDown = function (evt) {
  17463. if (_this.actionManager) {
  17464. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17465. }
  17466. };
  17467. this._onKeyUp = function (evt) {
  17468. if (_this.actionManager) {
  17469. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17470. }
  17471. };
  17472. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17473. var canvas = this._engine.getRenderingCanvas();
  17474. if (attachMove) {
  17475. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17476. // Wheel
  17477. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17478. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17479. }
  17480. if (attachDown) {
  17481. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17482. }
  17483. if (attachUp) {
  17484. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17485. }
  17486. canvas.tabIndex = 1;
  17487. canvas.addEventListener("keydown", this._onKeyDown, false);
  17488. canvas.addEventListener("keyup", this._onKeyUp, false);
  17489. };
  17490. Scene.prototype.detachControl = function () {
  17491. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17492. var canvas = this._engine.getRenderingCanvas();
  17493. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17494. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17495. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17496. // Wheel
  17497. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17498. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17499. canvas.removeEventListener("keydown", this._onKeyDown);
  17500. canvas.removeEventListener("keyup", this._onKeyUp);
  17501. };
  17502. // Ready
  17503. Scene.prototype.isReady = function () {
  17504. if (this._pendingData.length > 0) {
  17505. return false;
  17506. }
  17507. var index;
  17508. // Geometries
  17509. for (index = 0; index < this._geometries.length; index++) {
  17510. var geometry = this._geometries[index];
  17511. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17512. return false;
  17513. }
  17514. }
  17515. // Meshes
  17516. for (index = 0; index < this.meshes.length; index++) {
  17517. var mesh = this.meshes[index];
  17518. if (!mesh.isEnabled()) {
  17519. continue;
  17520. }
  17521. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17522. continue;
  17523. }
  17524. if (!mesh.isReady()) {
  17525. return false;
  17526. }
  17527. var mat = mesh.material;
  17528. if (mat) {
  17529. if (!mat.isReady(mesh)) {
  17530. return false;
  17531. }
  17532. }
  17533. }
  17534. return true;
  17535. };
  17536. Scene.prototype.resetCachedMaterial = function () {
  17537. this._cachedMaterial = null;
  17538. this._cachedEffect = null;
  17539. this._cachedVisibility = null;
  17540. };
  17541. Scene.prototype.registerBeforeRender = function (func) {
  17542. this.onBeforeRenderObservable.add(func);
  17543. };
  17544. Scene.prototype.unregisterBeforeRender = function (func) {
  17545. this.onBeforeRenderObservable.removeCallback(func);
  17546. };
  17547. Scene.prototype.registerAfterRender = function (func) {
  17548. this.onAfterRenderObservable.add(func);
  17549. };
  17550. Scene.prototype.unregisterAfterRender = function (func) {
  17551. this.onAfterRenderObservable.removeCallback(func);
  17552. };
  17553. Scene.prototype._addPendingData = function (data) {
  17554. this._pendingData.push(data);
  17555. };
  17556. Scene.prototype._removePendingData = function (data) {
  17557. var index = this._pendingData.indexOf(data);
  17558. if (index !== -1) {
  17559. this._pendingData.splice(index, 1);
  17560. }
  17561. };
  17562. Scene.prototype.getWaitingItemsCount = function () {
  17563. return this._pendingData.length;
  17564. };
  17565. /**
  17566. * Registers a function to be executed when the scene is ready.
  17567. * @param {Function} func - the function to be executed.
  17568. */
  17569. Scene.prototype.executeWhenReady = function (func) {
  17570. var _this = this;
  17571. this.onReadyObservable.add(func);
  17572. if (this._executeWhenReadyTimeoutId !== -1) {
  17573. return;
  17574. }
  17575. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17576. _this._checkIsReady();
  17577. }, 150);
  17578. };
  17579. Scene.prototype._checkIsReady = function () {
  17580. var _this = this;
  17581. if (this.isReady()) {
  17582. this.onReadyObservable.notifyObservers(this);
  17583. this.onReadyObservable.clear();
  17584. this._executeWhenReadyTimeoutId = -1;
  17585. return;
  17586. }
  17587. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17588. _this._checkIsReady();
  17589. }, 150);
  17590. };
  17591. // Animations
  17592. /**
  17593. * Will start the animation sequence of a given target
  17594. * @param target - the target
  17595. * @param {number} from - from which frame should animation start
  17596. * @param {number} to - till which frame should animation run.
  17597. * @param {boolean} [loop] - should the animation loop
  17598. * @param {number} [speedRatio] - the speed in which to run the animation
  17599. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17600. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17601. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17602. * See BABYLON.Animatable
  17603. */
  17604. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17605. if (speedRatio === void 0) { speedRatio = 1.0; }
  17606. if (from > to && speedRatio > 0) {
  17607. speedRatio *= -1;
  17608. }
  17609. this.stopAnimation(target);
  17610. if (!animatable) {
  17611. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17612. }
  17613. // Local animations
  17614. if (target.animations) {
  17615. animatable.appendAnimations(target, target.animations);
  17616. }
  17617. // Children animations
  17618. if (target.getAnimatables) {
  17619. var animatables = target.getAnimatables();
  17620. for (var index = 0; index < animatables.length; index++) {
  17621. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17622. }
  17623. }
  17624. animatable.reset();
  17625. return animatable;
  17626. };
  17627. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17628. if (speedRatio === undefined) {
  17629. speedRatio = 1.0;
  17630. }
  17631. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17632. return animatable;
  17633. };
  17634. Scene.prototype.getAnimatableByTarget = function (target) {
  17635. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17636. if (this._activeAnimatables[index].target === target) {
  17637. return this._activeAnimatables[index];
  17638. }
  17639. }
  17640. return null;
  17641. };
  17642. Object.defineProperty(Scene.prototype, "Animatables", {
  17643. get: function () {
  17644. return this._activeAnimatables;
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. /**
  17650. * Will stop the animation of the given target
  17651. * @param target - the target
  17652. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17653. * @see beginAnimation
  17654. */
  17655. Scene.prototype.stopAnimation = function (target, animationName) {
  17656. var animatable = this.getAnimatableByTarget(target);
  17657. if (animatable) {
  17658. animatable.stop(animationName);
  17659. }
  17660. };
  17661. Scene.prototype._animate = function () {
  17662. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17663. return;
  17664. }
  17665. // Getting time
  17666. var now = BABYLON.Tools.Now;
  17667. if (!this._animationTimeLast) {
  17668. if (this._pendingData.length > 0) {
  17669. return;
  17670. }
  17671. this._animationTimeLast = now;
  17672. }
  17673. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17674. this._animationTime += deltaTime;
  17675. this._animationTimeLast = now;
  17676. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17677. this._activeAnimatables[index]._animate(this._animationTime);
  17678. }
  17679. };
  17680. // Matrix
  17681. Scene.prototype.getViewMatrix = function () {
  17682. return this._viewMatrix;
  17683. };
  17684. Scene.prototype.getProjectionMatrix = function () {
  17685. return this._projectionMatrix;
  17686. };
  17687. Scene.prototype.getTransformMatrix = function () {
  17688. return this._transformMatrix;
  17689. };
  17690. Scene.prototype.setTransformMatrix = function (view, projection) {
  17691. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17692. return;
  17693. }
  17694. this._viewUpdateFlag = view.updateFlag;
  17695. this._projectionUpdateFlag = projection.updateFlag;
  17696. this._viewMatrix = view;
  17697. this._projectionMatrix = projection;
  17698. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17699. // Update frustum
  17700. if (!this._frustumPlanes) {
  17701. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17702. }
  17703. else {
  17704. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17705. }
  17706. if (this._sceneUbo.useUbo) {
  17707. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17708. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17709. this._sceneUbo.update();
  17710. }
  17711. };
  17712. Scene.prototype.getSceneUniformBuffer = function () {
  17713. return this._sceneUbo;
  17714. };
  17715. // Methods
  17716. Scene.prototype.getUniqueId = function () {
  17717. var result = this._uniqueIdCounter;
  17718. this._uniqueIdCounter++;
  17719. return result;
  17720. };
  17721. Scene.prototype.addMesh = function (newMesh) {
  17722. newMesh.uniqueId = this.getUniqueId();
  17723. var position = this.meshes.push(newMesh);
  17724. //notify the collision coordinator
  17725. if (this.collisionCoordinator) {
  17726. this.collisionCoordinator.onMeshAdded(newMesh);
  17727. }
  17728. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17729. };
  17730. Scene.prototype.removeMesh = function (toRemove) {
  17731. var index = this.meshes.indexOf(toRemove);
  17732. if (index !== -1) {
  17733. // Remove from the scene if mesh found
  17734. this.meshes.splice(index, 1);
  17735. }
  17736. //notify the collision coordinator
  17737. if (this.collisionCoordinator) {
  17738. this.collisionCoordinator.onMeshRemoved(toRemove);
  17739. }
  17740. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17741. return index;
  17742. };
  17743. Scene.prototype.removeSkeleton = function (toRemove) {
  17744. var index = this.skeletons.indexOf(toRemove);
  17745. if (index !== -1) {
  17746. // Remove from the scene if found
  17747. this.skeletons.splice(index, 1);
  17748. }
  17749. return index;
  17750. };
  17751. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17752. var index = this.morphTargetManagers.indexOf(toRemove);
  17753. if (index !== -1) {
  17754. // Remove from the scene if found
  17755. this.morphTargetManagers.splice(index, 1);
  17756. }
  17757. return index;
  17758. };
  17759. Scene.prototype.removeLight = function (toRemove) {
  17760. var index = this.lights.indexOf(toRemove);
  17761. if (index !== -1) {
  17762. // Remove from the scene if mesh found
  17763. this.lights.splice(index, 1);
  17764. this.sortLightsByPriority();
  17765. }
  17766. this.onLightRemovedObservable.notifyObservers(toRemove);
  17767. return index;
  17768. };
  17769. Scene.prototype.removeCamera = function (toRemove) {
  17770. var index = this.cameras.indexOf(toRemove);
  17771. if (index !== -1) {
  17772. // Remove from the scene if mesh found
  17773. this.cameras.splice(index, 1);
  17774. }
  17775. // Remove from activeCameras
  17776. var index2 = this.activeCameras.indexOf(toRemove);
  17777. if (index2 !== -1) {
  17778. // Remove from the scene if mesh found
  17779. this.activeCameras.splice(index2, 1);
  17780. }
  17781. // Reset the activeCamera
  17782. if (this.activeCamera === toRemove) {
  17783. if (this.cameras.length > 0) {
  17784. this.activeCamera = this.cameras[0];
  17785. }
  17786. else {
  17787. this.activeCamera = null;
  17788. }
  17789. }
  17790. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17791. return index;
  17792. };
  17793. Scene.prototype.addLight = function (newLight) {
  17794. newLight.uniqueId = this.getUniqueId();
  17795. this.lights.push(newLight);
  17796. this.sortLightsByPriority();
  17797. this.onNewLightAddedObservable.notifyObservers(newLight);
  17798. };
  17799. Scene.prototype.sortLightsByPriority = function () {
  17800. if (this.requireLightSorting) {
  17801. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17802. }
  17803. };
  17804. Scene.prototype.addCamera = function (newCamera) {
  17805. newCamera.uniqueId = this.getUniqueId();
  17806. var position = this.cameras.push(newCamera);
  17807. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17808. };
  17809. /**
  17810. * Switch active camera
  17811. * @param {Camera} newCamera - new active camera
  17812. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17813. */
  17814. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17815. if (attachControl === void 0) { attachControl = true; }
  17816. var canvas = this._engine.getRenderingCanvas();
  17817. this.activeCamera.detachControl(canvas);
  17818. this.activeCamera = newCamera;
  17819. if (attachControl) {
  17820. newCamera.attachControl(canvas);
  17821. }
  17822. };
  17823. /**
  17824. * sets the active camera of the scene using its ID
  17825. * @param {string} id - the camera's ID
  17826. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17827. * @see activeCamera
  17828. */
  17829. Scene.prototype.setActiveCameraByID = function (id) {
  17830. var camera = this.getCameraByID(id);
  17831. if (camera) {
  17832. this.activeCamera = camera;
  17833. return camera;
  17834. }
  17835. return null;
  17836. };
  17837. /**
  17838. * sets the active camera of the scene using its name
  17839. * @param {string} name - the camera's name
  17840. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17841. * @see activeCamera
  17842. */
  17843. Scene.prototype.setActiveCameraByName = function (name) {
  17844. var camera = this.getCameraByName(name);
  17845. if (camera) {
  17846. this.activeCamera = camera;
  17847. return camera;
  17848. }
  17849. return null;
  17850. };
  17851. /**
  17852. * get a material using its id
  17853. * @param {string} the material's ID
  17854. * @return {BABYLON.Material|null} the material or null if none found.
  17855. */
  17856. Scene.prototype.getMaterialByID = function (id) {
  17857. for (var index = 0; index < this.materials.length; index++) {
  17858. if (this.materials[index].id === id) {
  17859. return this.materials[index];
  17860. }
  17861. }
  17862. return null;
  17863. };
  17864. /**
  17865. * get a material using its name
  17866. * @param {string} the material's name
  17867. * @return {BABYLON.Material|null} the material or null if none found.
  17868. */
  17869. Scene.prototype.getMaterialByName = function (name) {
  17870. for (var index = 0; index < this.materials.length; index++) {
  17871. if (this.materials[index].name === name) {
  17872. return this.materials[index];
  17873. }
  17874. }
  17875. return null;
  17876. };
  17877. Scene.prototype.getLensFlareSystemByName = function (name) {
  17878. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17879. if (this.lensFlareSystems[index].name === name) {
  17880. return this.lensFlareSystems[index];
  17881. }
  17882. }
  17883. return null;
  17884. };
  17885. Scene.prototype.getLensFlareSystemByID = function (id) {
  17886. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17887. if (this.lensFlareSystems[index].id === id) {
  17888. return this.lensFlareSystems[index];
  17889. }
  17890. }
  17891. return null;
  17892. };
  17893. Scene.prototype.getCameraByID = function (id) {
  17894. for (var index = 0; index < this.cameras.length; index++) {
  17895. if (this.cameras[index].id === id) {
  17896. return this.cameras[index];
  17897. }
  17898. }
  17899. return null;
  17900. };
  17901. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17902. for (var index = 0; index < this.cameras.length; index++) {
  17903. if (this.cameras[index].uniqueId === uniqueId) {
  17904. return this.cameras[index];
  17905. }
  17906. }
  17907. return null;
  17908. };
  17909. /**
  17910. * get a camera using its name
  17911. * @param {string} the camera's name
  17912. * @return {BABYLON.Camera|null} the camera or null if none found.
  17913. */
  17914. Scene.prototype.getCameraByName = function (name) {
  17915. for (var index = 0; index < this.cameras.length; index++) {
  17916. if (this.cameras[index].name === name) {
  17917. return this.cameras[index];
  17918. }
  17919. }
  17920. return null;
  17921. };
  17922. /**
  17923. * get a bone using its id
  17924. * @param {string} the bone's id
  17925. * @return {BABYLON.Bone|null} the bone or null if not found
  17926. */
  17927. Scene.prototype.getBoneByID = function (id) {
  17928. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17929. var skeleton = this.skeletons[skeletonIndex];
  17930. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17931. if (skeleton.bones[boneIndex].id === id) {
  17932. return skeleton.bones[boneIndex];
  17933. }
  17934. }
  17935. }
  17936. return null;
  17937. };
  17938. /**
  17939. * get a bone using its id
  17940. * @param {string} the bone's name
  17941. * @return {BABYLON.Bone|null} the bone or null if not found
  17942. */
  17943. Scene.prototype.getBoneByName = function (name) {
  17944. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17945. var skeleton = this.skeletons[skeletonIndex];
  17946. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17947. if (skeleton.bones[boneIndex].name === name) {
  17948. return skeleton.bones[boneIndex];
  17949. }
  17950. }
  17951. }
  17952. return null;
  17953. };
  17954. /**
  17955. * get a light node using its name
  17956. * @param {string} the light's name
  17957. * @return {BABYLON.Light|null} the light or null if none found.
  17958. */
  17959. Scene.prototype.getLightByName = function (name) {
  17960. for (var index = 0; index < this.lights.length; index++) {
  17961. if (this.lights[index].name === name) {
  17962. return this.lights[index];
  17963. }
  17964. }
  17965. return null;
  17966. };
  17967. /**
  17968. * get a light node using its ID
  17969. * @param {string} the light's id
  17970. * @return {BABYLON.Light|null} the light or null if none found.
  17971. */
  17972. Scene.prototype.getLightByID = function (id) {
  17973. for (var index = 0; index < this.lights.length; index++) {
  17974. if (this.lights[index].id === id) {
  17975. return this.lights[index];
  17976. }
  17977. }
  17978. return null;
  17979. };
  17980. /**
  17981. * get a light node using its scene-generated unique ID
  17982. * @param {number} the light's unique id
  17983. * @return {BABYLON.Light|null} the light or null if none found.
  17984. */
  17985. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17986. for (var index = 0; index < this.lights.length; index++) {
  17987. if (this.lights[index].uniqueId === uniqueId) {
  17988. return this.lights[index];
  17989. }
  17990. }
  17991. return null;
  17992. };
  17993. /**
  17994. * get a particle system by id
  17995. * @param id {number} the particle system id
  17996. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17997. */
  17998. Scene.prototype.getParticleSystemByID = function (id) {
  17999. for (var index = 0; index < this.particleSystems.length; index++) {
  18000. if (this.particleSystems[index].id === id) {
  18001. return this.particleSystems[index];
  18002. }
  18003. }
  18004. return null;
  18005. };
  18006. /**
  18007. * get a geometry using its ID
  18008. * @param {string} the geometry's id
  18009. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18010. */
  18011. Scene.prototype.getGeometryByID = function (id) {
  18012. for (var index = 0; index < this._geometries.length; index++) {
  18013. if (this._geometries[index].id === id) {
  18014. return this._geometries[index];
  18015. }
  18016. }
  18017. return null;
  18018. };
  18019. /**
  18020. * add a new geometry to this scene.
  18021. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18022. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18023. * @return {boolean} was the geometry added or not
  18024. */
  18025. Scene.prototype.pushGeometry = function (geometry, force) {
  18026. if (!force && this.getGeometryByID(geometry.id)) {
  18027. return false;
  18028. }
  18029. this._geometries.push(geometry);
  18030. //notify the collision coordinator
  18031. if (this.collisionCoordinator) {
  18032. this.collisionCoordinator.onGeometryAdded(geometry);
  18033. }
  18034. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18035. return true;
  18036. };
  18037. /**
  18038. * Removes an existing geometry
  18039. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18040. * @return {boolean} was the geometry removed or not
  18041. */
  18042. Scene.prototype.removeGeometry = function (geometry) {
  18043. var index = this._geometries.indexOf(geometry);
  18044. if (index > -1) {
  18045. this._geometries.splice(index, 1);
  18046. //notify the collision coordinator
  18047. if (this.collisionCoordinator) {
  18048. this.collisionCoordinator.onGeometryDeleted(geometry);
  18049. }
  18050. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18051. return true;
  18052. }
  18053. return false;
  18054. };
  18055. Scene.prototype.getGeometries = function () {
  18056. return this._geometries;
  18057. };
  18058. /**
  18059. * Get the first added mesh found of a given ID
  18060. * @param {string} id - the id to search for
  18061. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18062. */
  18063. Scene.prototype.getMeshByID = function (id) {
  18064. for (var index = 0; index < this.meshes.length; index++) {
  18065. if (this.meshes[index].id === id) {
  18066. return this.meshes[index];
  18067. }
  18068. }
  18069. return null;
  18070. };
  18071. Scene.prototype.getMeshesByID = function (id) {
  18072. return this.meshes.filter(function (m) {
  18073. return m.id === id;
  18074. });
  18075. };
  18076. /**
  18077. * Get a mesh with its auto-generated unique id
  18078. * @param {number} uniqueId - the unique id to search for
  18079. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18080. */
  18081. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18082. for (var index = 0; index < this.meshes.length; index++) {
  18083. if (this.meshes[index].uniqueId === uniqueId) {
  18084. return this.meshes[index];
  18085. }
  18086. }
  18087. return null;
  18088. };
  18089. /**
  18090. * Get a the last added mesh found of a given ID
  18091. * @param {string} id - the id to search for
  18092. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18093. */
  18094. Scene.prototype.getLastMeshByID = function (id) {
  18095. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18096. if (this.meshes[index].id === id) {
  18097. return this.meshes[index];
  18098. }
  18099. }
  18100. return null;
  18101. };
  18102. /**
  18103. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18104. * @param {string} id - the id to search for
  18105. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18106. */
  18107. Scene.prototype.getLastEntryByID = function (id) {
  18108. var index;
  18109. for (index = this.meshes.length - 1; index >= 0; index--) {
  18110. if (this.meshes[index].id === id) {
  18111. return this.meshes[index];
  18112. }
  18113. }
  18114. for (index = this.cameras.length - 1; index >= 0; index--) {
  18115. if (this.cameras[index].id === id) {
  18116. return this.cameras[index];
  18117. }
  18118. }
  18119. for (index = this.lights.length - 1; index >= 0; index--) {
  18120. if (this.lights[index].id === id) {
  18121. return this.lights[index];
  18122. }
  18123. }
  18124. return null;
  18125. };
  18126. Scene.prototype.getNodeByID = function (id) {
  18127. var mesh = this.getMeshByID(id);
  18128. if (mesh) {
  18129. return mesh;
  18130. }
  18131. var light = this.getLightByID(id);
  18132. if (light) {
  18133. return light;
  18134. }
  18135. var camera = this.getCameraByID(id);
  18136. if (camera) {
  18137. return camera;
  18138. }
  18139. var bone = this.getBoneByID(id);
  18140. return bone;
  18141. };
  18142. Scene.prototype.getNodeByName = function (name) {
  18143. var mesh = this.getMeshByName(name);
  18144. if (mesh) {
  18145. return mesh;
  18146. }
  18147. var light = this.getLightByName(name);
  18148. if (light) {
  18149. return light;
  18150. }
  18151. var camera = this.getCameraByName(name);
  18152. if (camera) {
  18153. return camera;
  18154. }
  18155. var bone = this.getBoneByName(name);
  18156. return bone;
  18157. };
  18158. Scene.prototype.getMeshByName = function (name) {
  18159. for (var index = 0; index < this.meshes.length; index++) {
  18160. if (this.meshes[index].name === name) {
  18161. return this.meshes[index];
  18162. }
  18163. }
  18164. return null;
  18165. };
  18166. Scene.prototype.getSoundByName = function (name) {
  18167. var index;
  18168. if (BABYLON.AudioEngine) {
  18169. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18170. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18171. return this.mainSoundTrack.soundCollection[index];
  18172. }
  18173. }
  18174. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18175. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18176. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18177. return this.soundTracks[sdIndex].soundCollection[index];
  18178. }
  18179. }
  18180. }
  18181. }
  18182. return null;
  18183. };
  18184. Scene.prototype.getLastSkeletonByID = function (id) {
  18185. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18186. if (this.skeletons[index].id === id) {
  18187. return this.skeletons[index];
  18188. }
  18189. }
  18190. return null;
  18191. };
  18192. Scene.prototype.getSkeletonById = function (id) {
  18193. for (var index = 0; index < this.skeletons.length; index++) {
  18194. if (this.skeletons[index].id === id) {
  18195. return this.skeletons[index];
  18196. }
  18197. }
  18198. return null;
  18199. };
  18200. Scene.prototype.getSkeletonByName = function (name) {
  18201. for (var index = 0; index < this.skeletons.length; index++) {
  18202. if (this.skeletons[index].name === name) {
  18203. return this.skeletons[index];
  18204. }
  18205. }
  18206. return null;
  18207. };
  18208. Scene.prototype.getMorphTargetManagerById = function (id) {
  18209. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18210. if (this.morphTargetManagers[index].uniqueId === id) {
  18211. return this.morphTargetManagers[index];
  18212. }
  18213. }
  18214. return null;
  18215. };
  18216. Scene.prototype.isActiveMesh = function (mesh) {
  18217. return (this._activeMeshes.indexOf(mesh) !== -1);
  18218. };
  18219. /**
  18220. * Return a the first highlight layer of the scene with a given name.
  18221. * @param name The name of the highlight layer to look for.
  18222. * @return The highlight layer if found otherwise null.
  18223. */
  18224. Scene.prototype.getHighlightLayerByName = function (name) {
  18225. for (var index = 0; index < this.highlightLayers.length; index++) {
  18226. if (this.highlightLayers[index].name === name) {
  18227. return this.highlightLayers[index];
  18228. }
  18229. }
  18230. return null;
  18231. };
  18232. Object.defineProperty(Scene.prototype, "uid", {
  18233. /**
  18234. * Return a unique id as a string which can serve as an identifier for the scene
  18235. */
  18236. get: function () {
  18237. if (!this._uid) {
  18238. this._uid = BABYLON.Tools.RandomId();
  18239. }
  18240. return this._uid;
  18241. },
  18242. enumerable: true,
  18243. configurable: true
  18244. });
  18245. /**
  18246. * Add an externaly attached data from its key.
  18247. * This method call will fail and return false, if such key already exists.
  18248. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18249. * @param key the unique key that identifies the data
  18250. * @param data the data object to associate to the key for this Engine instance
  18251. * @return true if no such key were already present and the data was added successfully, false otherwise
  18252. */
  18253. Scene.prototype.addExternalData = function (key, data) {
  18254. if (!this._externalData) {
  18255. this._externalData = new BABYLON.StringDictionary();
  18256. }
  18257. return this._externalData.add(key, data);
  18258. };
  18259. /**
  18260. * Get an externaly attached data from its key
  18261. * @param key the unique key that identifies the data
  18262. * @return the associated data, if present (can be null), or undefined if not present
  18263. */
  18264. Scene.prototype.getExternalData = function (key) {
  18265. if (!this._externalData) {
  18266. return null;
  18267. }
  18268. return this._externalData.get(key);
  18269. };
  18270. /**
  18271. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18272. * @param key the unique key that identifies the data
  18273. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18274. * @return the associated data, can be null if the factory returned null.
  18275. */
  18276. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18277. if (!this._externalData) {
  18278. this._externalData = new BABYLON.StringDictionary();
  18279. }
  18280. return this._externalData.getOrAddWithFactory(key, factory);
  18281. };
  18282. /**
  18283. * Remove an externaly attached data from the Engine instance
  18284. * @param key the unique key that identifies the data
  18285. * @return true if the data was successfully removed, false if it doesn't exist
  18286. */
  18287. Scene.prototype.removeExternalData = function (key) {
  18288. return this._externalData.remove(key);
  18289. };
  18290. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18291. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18292. var material = subMesh.getMaterial();
  18293. if (mesh.showSubMeshesBoundingBox) {
  18294. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18295. }
  18296. if (material) {
  18297. // Render targets
  18298. if (material.getRenderTargetTextures) {
  18299. if (this._processedMaterials.indexOf(material) === -1) {
  18300. this._processedMaterials.push(material);
  18301. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18302. }
  18303. }
  18304. // Dispatch
  18305. this._activeIndices.addCount(subMesh.indexCount, false);
  18306. this._renderingManager.dispatch(subMesh);
  18307. }
  18308. }
  18309. };
  18310. Scene.prototype._isInIntermediateRendering = function () {
  18311. return this._intermediateRendering;
  18312. };
  18313. Scene.prototype._evaluateActiveMeshes = function () {
  18314. this.activeCamera._activeMeshes.reset();
  18315. this._activeMeshes.reset();
  18316. this._renderingManager.reset();
  18317. this._processedMaterials.reset();
  18318. this._activeParticleSystems.reset();
  18319. this._activeSkeletons.reset();
  18320. this._softwareSkinnedMeshes.reset();
  18321. if (this._boundingBoxRenderer) {
  18322. this._boundingBoxRenderer.reset();
  18323. }
  18324. // Meshes
  18325. var meshes;
  18326. var len;
  18327. if (this._selectionOctree) {
  18328. var selection = this._selectionOctree.select(this._frustumPlanes);
  18329. meshes = selection.data;
  18330. len = selection.length;
  18331. }
  18332. else {
  18333. len = this.meshes.length;
  18334. meshes = this.meshes;
  18335. }
  18336. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18337. var mesh = meshes[meshIndex];
  18338. if (mesh.isBlocked) {
  18339. continue;
  18340. }
  18341. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18342. if (!mesh.isReady() || !mesh.isEnabled()) {
  18343. continue;
  18344. }
  18345. mesh.computeWorldMatrix();
  18346. // Intersections
  18347. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18348. this._meshesForIntersections.pushNoDuplicate(mesh);
  18349. }
  18350. // Switch to current LOD
  18351. var meshLOD = mesh.getLOD(this.activeCamera);
  18352. if (!meshLOD) {
  18353. continue;
  18354. }
  18355. mesh._preActivate();
  18356. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18357. this._activeMeshes.push(mesh);
  18358. this.activeCamera._activeMeshes.push(mesh);
  18359. mesh._activate(this._renderId);
  18360. if (meshLOD !== mesh) {
  18361. meshLOD._activate(this._renderId);
  18362. }
  18363. this._activeMesh(mesh, meshLOD);
  18364. }
  18365. }
  18366. // Particle systems
  18367. this._particlesDuration.beginMonitoring();
  18368. var beforeParticlesDate = BABYLON.Tools.Now;
  18369. if (this.particlesEnabled) {
  18370. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18371. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18372. var particleSystem = this.particleSystems[particleIndex];
  18373. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18374. continue;
  18375. }
  18376. var emitter = particleSystem.emitter;
  18377. if (!emitter.position || emitter.isEnabled()) {
  18378. this._activeParticleSystems.push(particleSystem);
  18379. particleSystem.animate();
  18380. this._renderingManager.dispatchParticles(particleSystem);
  18381. }
  18382. }
  18383. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18384. }
  18385. this._particlesDuration.endMonitoring(false);
  18386. };
  18387. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18388. if (mesh.skeleton && this.skeletonsEnabled) {
  18389. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18390. mesh.skeleton.prepare();
  18391. }
  18392. if (!mesh.computeBonesUsingShaders) {
  18393. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18394. }
  18395. }
  18396. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18397. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18398. }
  18399. if (mesh && mesh.subMeshes) {
  18400. // Submeshes Octrees
  18401. var len;
  18402. var subMeshes;
  18403. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18404. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18405. len = intersections.length;
  18406. subMeshes = intersections.data;
  18407. }
  18408. else {
  18409. subMeshes = mesh.subMeshes;
  18410. len = subMeshes.length;
  18411. }
  18412. for (var subIndex = 0; subIndex < len; subIndex++) {
  18413. var subMesh = subMeshes[subIndex];
  18414. this._evaluateSubMesh(subMesh, mesh);
  18415. }
  18416. }
  18417. };
  18418. Scene.prototype.updateTransformMatrix = function (force) {
  18419. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18420. };
  18421. Scene.prototype._renderForCamera = function (camera) {
  18422. var engine = this._engine;
  18423. var startTime = BABYLON.Tools.Now;
  18424. this.activeCamera = camera;
  18425. if (!this.activeCamera)
  18426. throw new Error("Active camera not set");
  18427. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18428. // Viewport
  18429. engine.setViewport(this.activeCamera.viewport);
  18430. // Camera
  18431. this.resetCachedMaterial();
  18432. this._renderId++;
  18433. this.updateTransformMatrix();
  18434. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18435. // Meshes
  18436. this._evaluateActiveMeshesDuration.beginMonitoring();
  18437. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18438. this._evaluateActiveMeshes();
  18439. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18440. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18441. // Software skinning
  18442. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18443. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18444. mesh.applySkeleton(mesh.skeleton);
  18445. }
  18446. // Render targets
  18447. this._renderTargetsDuration.beginMonitoring();
  18448. var needsRestoreFrameBuffer = false;
  18449. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18450. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18451. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18452. }
  18453. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18454. this._intermediateRendering = true;
  18455. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18456. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18457. var renderTarget = this._renderTargets.data[renderIndex];
  18458. if (renderTarget._shouldRender()) {
  18459. this._renderId++;
  18460. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18461. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18462. }
  18463. }
  18464. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18465. this._intermediateRendering = false;
  18466. this._renderId++;
  18467. needsRestoreFrameBuffer = true; // Restore back buffer
  18468. }
  18469. // Render HighlightLayer Texture
  18470. var stencilState = this._engine.getStencilBuffer();
  18471. var renderhighlights = false;
  18472. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18473. this._intermediateRendering = true;
  18474. for (var i = 0; i < this.highlightLayers.length; i++) {
  18475. var highlightLayer = this.highlightLayers[i];
  18476. if (highlightLayer.shouldRender() &&
  18477. (!highlightLayer.camera ||
  18478. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18479. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18480. renderhighlights = true;
  18481. var renderTarget = highlightLayer._mainTexture;
  18482. if (renderTarget._shouldRender()) {
  18483. this._renderId++;
  18484. renderTarget.render(false, false);
  18485. needsRestoreFrameBuffer = true;
  18486. }
  18487. }
  18488. }
  18489. this._intermediateRendering = false;
  18490. this._renderId++;
  18491. }
  18492. if (needsRestoreFrameBuffer) {
  18493. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18494. }
  18495. this._renderTargetsDuration.endMonitoring(false);
  18496. // Prepare Frame
  18497. this.postProcessManager._prepareFrame();
  18498. this._renderDuration.beginMonitoring();
  18499. // Backgrounds
  18500. var layerIndex;
  18501. var layer;
  18502. if (this.layers.length) {
  18503. engine.setDepthBuffer(false);
  18504. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18505. layer = this.layers[layerIndex];
  18506. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18507. layer.render();
  18508. }
  18509. }
  18510. engine.setDepthBuffer(true);
  18511. }
  18512. // Render
  18513. BABYLON.Tools.StartPerformanceCounter("Main render");
  18514. // Activate HighlightLayer stencil
  18515. if (renderhighlights) {
  18516. this._engine.setStencilBuffer(true);
  18517. }
  18518. this._renderingManager.render(null, null, true, true);
  18519. // Restore HighlightLayer stencil
  18520. if (renderhighlights) {
  18521. this._engine.setStencilBuffer(stencilState);
  18522. }
  18523. BABYLON.Tools.EndPerformanceCounter("Main render");
  18524. // Bounding boxes
  18525. if (this._boundingBoxRenderer) {
  18526. this._boundingBoxRenderer.render();
  18527. }
  18528. // Lens flares
  18529. if (this.lensFlaresEnabled) {
  18530. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18531. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18532. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18533. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18534. lensFlareSystem.render();
  18535. }
  18536. }
  18537. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18538. }
  18539. // Foregrounds
  18540. if (this.layers.length) {
  18541. engine.setDepthBuffer(false);
  18542. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18543. layer = this.layers[layerIndex];
  18544. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18545. layer.render();
  18546. }
  18547. }
  18548. engine.setDepthBuffer(true);
  18549. }
  18550. // Highlight Layer
  18551. if (renderhighlights) {
  18552. engine.setDepthBuffer(false);
  18553. for (var i = 0; i < this.highlightLayers.length; i++) {
  18554. if (this.highlightLayers[i].shouldRender()) {
  18555. this.highlightLayers[i].render();
  18556. }
  18557. }
  18558. engine.setDepthBuffer(true);
  18559. }
  18560. this._renderDuration.endMonitoring(false);
  18561. // Finalize frame
  18562. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18563. // Update camera
  18564. this.activeCamera._updateFromScene();
  18565. // Reset some special arrays
  18566. this._renderTargets.reset();
  18567. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18568. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18569. };
  18570. Scene.prototype._processSubCameras = function (camera) {
  18571. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18572. this._renderForCamera(camera);
  18573. return;
  18574. }
  18575. // rig cameras
  18576. for (var index = 0; index < camera._rigCameras.length; index++) {
  18577. this._renderForCamera(camera._rigCameras[index]);
  18578. }
  18579. this.activeCamera = camera;
  18580. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18581. // Update camera
  18582. this.activeCamera._updateFromScene();
  18583. };
  18584. Scene.prototype._checkIntersections = function () {
  18585. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18586. var sourceMesh = this._meshesForIntersections.data[index];
  18587. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18588. var action = sourceMesh.actionManager.actions[actionIndex];
  18589. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18590. var parameters = action.getTriggerParameter();
  18591. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18592. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18593. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18594. if (areIntersecting && currentIntersectionInProgress === -1) {
  18595. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18596. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18597. sourceMesh._intersectionsInProgress.push(otherMesh);
  18598. }
  18599. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18600. sourceMesh._intersectionsInProgress.push(otherMesh);
  18601. }
  18602. }
  18603. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18604. //They intersected, and now they don't.
  18605. //is this trigger an exit trigger? execute an event.
  18606. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18607. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18608. }
  18609. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18610. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18611. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18612. }
  18613. }
  18614. }
  18615. }
  18616. }
  18617. };
  18618. Scene.prototype.render = function () {
  18619. if (this.isDisposed) {
  18620. return;
  18621. }
  18622. this._lastFrameDuration.beginMonitoring();
  18623. this._particlesDuration.fetchNewFrame();
  18624. this._spritesDuration.fetchNewFrame();
  18625. this._activeParticles.fetchNewFrame();
  18626. this._renderDuration.fetchNewFrame();
  18627. this._renderTargetsDuration.fetchNewFrame();
  18628. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18629. this._totalVertices.fetchNewFrame();
  18630. this._activeIndices.fetchNewFrame();
  18631. this._activeBones.fetchNewFrame();
  18632. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18633. this._meshesForIntersections.reset();
  18634. this.resetCachedMaterial();
  18635. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18636. // Actions
  18637. if (this.actionManager) {
  18638. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18639. }
  18640. //Simplification Queue
  18641. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18642. this.simplificationQueue.executeNext();
  18643. }
  18644. if (this._engine.isDeterministicLockStep()) {
  18645. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18646. var defaultTimeStep = (60.0 / 1000.0);
  18647. if (this._physicsEngine) {
  18648. defaultTimeStep = this._physicsEngine.getTimeStep();
  18649. }
  18650. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18651. this._timeAccumulator += deltaTime;
  18652. // compute the amount of fixed steps we should have taken since the last step
  18653. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18654. internalSteps = Math.min(internalSteps, maxSubSteps);
  18655. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18656. this.onBeforeStepObservable.notifyObservers(this);
  18657. // Animations
  18658. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18659. this._animate();
  18660. // Physics
  18661. if (this._physicsEngine) {
  18662. BABYLON.Tools.StartPerformanceCounter("Physics");
  18663. this._physicsEngine._step(defaultTimeStep);
  18664. BABYLON.Tools.EndPerformanceCounter("Physics");
  18665. }
  18666. this._timeAccumulator -= defaultTimeStep;
  18667. this.onAfterStepObservable.notifyObservers(this);
  18668. this._currentStepId++;
  18669. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18670. // Q: can this be optimized by putting some code in the afterStep callback?
  18671. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18672. // would return incorrect positions for internal stepIds (non-rendered steps)
  18673. this._evaluateActiveMeshes();
  18674. }
  18675. }
  18676. }
  18677. else {
  18678. // Animations
  18679. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18680. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18681. this._animate();
  18682. // Physics
  18683. if (this._physicsEngine) {
  18684. BABYLON.Tools.StartPerformanceCounter("Physics");
  18685. this._physicsEngine._step(deltaTime / 1000.0);
  18686. BABYLON.Tools.EndPerformanceCounter("Physics");
  18687. }
  18688. }
  18689. // Before render
  18690. this.onBeforeRenderObservable.notifyObservers(this);
  18691. // Customs render targets
  18692. this._renderTargetsDuration.beginMonitoring();
  18693. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18694. var engine = this.getEngine();
  18695. var currentActiveCamera = this.activeCamera;
  18696. if (this.renderTargetsEnabled) {
  18697. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18698. this._intermediateRendering = true;
  18699. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18700. var renderTarget = this.customRenderTargets[customIndex];
  18701. if (renderTarget._shouldRender()) {
  18702. this._renderId++;
  18703. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18704. if (!this.activeCamera)
  18705. throw new Error("Active camera not set");
  18706. // Viewport
  18707. engine.setViewport(this.activeCamera.viewport);
  18708. // Camera
  18709. this.updateTransformMatrix();
  18710. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18711. }
  18712. }
  18713. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18714. this._intermediateRendering = false;
  18715. this._renderId++;
  18716. }
  18717. // Restore back buffer
  18718. if (this.customRenderTargets.length > 0) {
  18719. engine.restoreDefaultFramebuffer();
  18720. }
  18721. this._renderTargetsDuration.endMonitoring();
  18722. this.activeCamera = currentActiveCamera;
  18723. // Procedural textures
  18724. if (this.proceduralTexturesEnabled) {
  18725. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18726. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18727. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18728. if (proceduralTexture._shouldRender()) {
  18729. proceduralTexture.render();
  18730. }
  18731. }
  18732. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18733. }
  18734. // Clear
  18735. if (this.autoClearDepthAndStencil || this.autoClear) {
  18736. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18737. }
  18738. // Shadows
  18739. if (this.shadowsEnabled) {
  18740. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18741. var light = this.lights[lightIndex];
  18742. var shadowGenerator = light.getShadowGenerator();
  18743. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18744. var shadowMap = shadowGenerator.getShadowMap();
  18745. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18746. this._renderTargets.push(shadowMap);
  18747. }
  18748. }
  18749. }
  18750. }
  18751. // Depth renderer
  18752. if (this._depthRenderer) {
  18753. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18754. }
  18755. // Geometry renderer
  18756. if (this._geometryBufferRenderer) {
  18757. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18758. }
  18759. // RenderPipeline
  18760. if (this._postProcessRenderPipelineManager) {
  18761. this._postProcessRenderPipelineManager.update();
  18762. }
  18763. // Multi-cameras?
  18764. if (this.activeCameras.length > 0) {
  18765. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18766. if (cameraIndex > 0) {
  18767. this._engine.clear(null, false, true, true);
  18768. }
  18769. this._processSubCameras(this.activeCameras[cameraIndex]);
  18770. }
  18771. }
  18772. else {
  18773. if (!this.activeCamera) {
  18774. throw new Error("No camera defined");
  18775. }
  18776. this._processSubCameras(this.activeCamera);
  18777. }
  18778. // Intersection checks
  18779. this._checkIntersections();
  18780. // Update the audio listener attached to the camera
  18781. if (BABYLON.AudioEngine) {
  18782. this._updateAudioParameters();
  18783. }
  18784. // After render
  18785. if (this.afterRender) {
  18786. this.afterRender();
  18787. }
  18788. this.onAfterRenderObservable.notifyObservers(this);
  18789. // Cleaning
  18790. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18791. this._toBeDisposed.data[index].dispose();
  18792. this._toBeDisposed[index] = null;
  18793. }
  18794. this._toBeDisposed.reset();
  18795. if (this.dumpNextRenderTargets) {
  18796. this.dumpNextRenderTargets = false;
  18797. }
  18798. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18799. this._lastFrameDuration.endMonitoring();
  18800. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18801. this._totalLightsCounter.addCount(this.lights.length, true);
  18802. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18803. this._totalTexturesCounter.addCount(this.textures.length, true);
  18804. this._activeBones.addCount(0, true);
  18805. this._activeIndices.addCount(0, true);
  18806. this._activeParticles.addCount(0, true);
  18807. };
  18808. Scene.prototype._updateAudioParameters = function () {
  18809. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18810. return;
  18811. }
  18812. var listeningCamera;
  18813. var audioEngine = BABYLON.Engine.audioEngine;
  18814. if (this.activeCameras.length > 0) {
  18815. listeningCamera = this.activeCameras[0];
  18816. }
  18817. else {
  18818. listeningCamera = this.activeCamera;
  18819. }
  18820. if (listeningCamera && audioEngine.canUseWebAudio) {
  18821. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18822. // for VR cameras
  18823. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18824. listeningCamera = listeningCamera.rigCameras[0];
  18825. }
  18826. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18827. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18828. cameraDirection.normalize();
  18829. // To avoid some errors on GearVR
  18830. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18831. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18832. }
  18833. var i;
  18834. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18835. var sound = this.mainSoundTrack.soundCollection[i];
  18836. if (sound.useCustomAttenuation) {
  18837. sound.updateDistanceFromListener();
  18838. }
  18839. }
  18840. for (i = 0; i < this.soundTracks.length; i++) {
  18841. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18842. sound = this.soundTracks[i].soundCollection[j];
  18843. if (sound.useCustomAttenuation) {
  18844. sound.updateDistanceFromListener();
  18845. }
  18846. }
  18847. }
  18848. }
  18849. };
  18850. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18851. // Audio
  18852. get: function () {
  18853. return this._audioEnabled;
  18854. },
  18855. set: function (value) {
  18856. this._audioEnabled = value;
  18857. if (BABYLON.AudioEngine) {
  18858. if (this._audioEnabled) {
  18859. this._enableAudio();
  18860. }
  18861. else {
  18862. this._disableAudio();
  18863. }
  18864. }
  18865. },
  18866. enumerable: true,
  18867. configurable: true
  18868. });
  18869. Scene.prototype._disableAudio = function () {
  18870. var i;
  18871. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18872. this.mainSoundTrack.soundCollection[i].pause();
  18873. }
  18874. for (i = 0; i < this.soundTracks.length; i++) {
  18875. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18876. this.soundTracks[i].soundCollection[j].pause();
  18877. }
  18878. }
  18879. };
  18880. Scene.prototype._enableAudio = function () {
  18881. var i;
  18882. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18883. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18884. this.mainSoundTrack.soundCollection[i].play();
  18885. }
  18886. }
  18887. for (i = 0; i < this.soundTracks.length; i++) {
  18888. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18889. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18890. this.soundTracks[i].soundCollection[j].play();
  18891. }
  18892. }
  18893. }
  18894. };
  18895. Object.defineProperty(Scene.prototype, "headphone", {
  18896. get: function () {
  18897. return this._headphone;
  18898. },
  18899. set: function (value) {
  18900. this._headphone = value;
  18901. if (BABYLON.AudioEngine) {
  18902. if (this._headphone) {
  18903. this._switchAudioModeForHeadphones();
  18904. }
  18905. else {
  18906. this._switchAudioModeForNormalSpeakers();
  18907. }
  18908. }
  18909. },
  18910. enumerable: true,
  18911. configurable: true
  18912. });
  18913. Scene.prototype._switchAudioModeForHeadphones = function () {
  18914. this.mainSoundTrack.switchPanningModelToHRTF();
  18915. for (var i = 0; i < this.soundTracks.length; i++) {
  18916. this.soundTracks[i].switchPanningModelToHRTF();
  18917. }
  18918. };
  18919. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18920. this.mainSoundTrack.switchPanningModelToEqualPower();
  18921. for (var i = 0; i < this.soundTracks.length; i++) {
  18922. this.soundTracks[i].switchPanningModelToEqualPower();
  18923. }
  18924. };
  18925. Scene.prototype.enableDepthRenderer = function () {
  18926. if (this._depthRenderer) {
  18927. return this._depthRenderer;
  18928. }
  18929. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18930. return this._depthRenderer;
  18931. };
  18932. Scene.prototype.disableDepthRenderer = function () {
  18933. if (!this._depthRenderer) {
  18934. return;
  18935. }
  18936. this._depthRenderer.dispose();
  18937. this._depthRenderer = null;
  18938. };
  18939. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18940. if (ratio === void 0) { ratio = 1; }
  18941. if (this._geometryBufferRenderer) {
  18942. return this._geometryBufferRenderer;
  18943. }
  18944. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18945. if (!this._geometryBufferRenderer.isSupported) {
  18946. this._geometryBufferRenderer = null;
  18947. }
  18948. return this._geometryBufferRenderer;
  18949. };
  18950. Scene.prototype.disableGeometryBufferRenderer = function () {
  18951. if (!this._geometryBufferRenderer) {
  18952. return;
  18953. }
  18954. this._geometryBufferRenderer.dispose();
  18955. this._geometryBufferRenderer = null;
  18956. };
  18957. Scene.prototype.freezeMaterials = function () {
  18958. for (var i = 0; i < this.materials.length; i++) {
  18959. this.materials[i].freeze();
  18960. }
  18961. };
  18962. Scene.prototype.unfreezeMaterials = function () {
  18963. for (var i = 0; i < this.materials.length; i++) {
  18964. this.materials[i].unfreeze();
  18965. }
  18966. };
  18967. Scene.prototype.dispose = function () {
  18968. this.beforeRender = null;
  18969. this.afterRender = null;
  18970. this.skeletons = [];
  18971. this.morphTargetManagers = [];
  18972. this.importedMeshesFiles = new Array();
  18973. this.resetCachedMaterial();
  18974. if (this._depthRenderer) {
  18975. this._depthRenderer.dispose();
  18976. }
  18977. if (this._gamepadManager) {
  18978. this._gamepadManager.dispose();
  18979. this._gamepadManager = null;
  18980. }
  18981. // Smart arrays
  18982. if (this.activeCamera) {
  18983. this.activeCamera._activeMeshes.dispose();
  18984. this.activeCamera = null;
  18985. }
  18986. this._activeMeshes.dispose();
  18987. this._renderingManager.dispose();
  18988. this._processedMaterials.dispose();
  18989. this._activeParticleSystems.dispose();
  18990. this._activeSkeletons.dispose();
  18991. this._softwareSkinnedMeshes.dispose();
  18992. this._renderTargets.dispose();
  18993. if (this._boundingBoxRenderer) {
  18994. this._boundingBoxRenderer.dispose();
  18995. }
  18996. this._meshesForIntersections.dispose();
  18997. this._toBeDisposed.dispose();
  18998. // Debug layer
  18999. if (this._debugLayer) {
  19000. this._debugLayer.hide();
  19001. }
  19002. // Events
  19003. this.onDisposeObservable.notifyObservers(this);
  19004. this.onDisposeObservable.clear();
  19005. this.onBeforeRenderObservable.clear();
  19006. this.onAfterRenderObservable.clear();
  19007. this.detachControl();
  19008. // Release sounds & sounds tracks
  19009. if (BABYLON.AudioEngine) {
  19010. this.disposeSounds();
  19011. }
  19012. // VR Helper
  19013. if (this.VRHelper) {
  19014. this.VRHelper.dispose();
  19015. }
  19016. // Detach cameras
  19017. var canvas = this._engine.getRenderingCanvas();
  19018. var index;
  19019. for (index = 0; index < this.cameras.length; index++) {
  19020. this.cameras[index].detachControl(canvas);
  19021. }
  19022. // Release lights
  19023. while (this.lights.length) {
  19024. this.lights[0].dispose();
  19025. }
  19026. // Release meshes
  19027. while (this.meshes.length) {
  19028. this.meshes[0].dispose(true);
  19029. }
  19030. // Release cameras
  19031. while (this.cameras.length) {
  19032. this.cameras[0].dispose();
  19033. }
  19034. // Release materials
  19035. if (this.defaultMaterial) {
  19036. this.defaultMaterial.dispose();
  19037. }
  19038. while (this.multiMaterials.length) {
  19039. this.multiMaterials[0].dispose();
  19040. }
  19041. while (this.materials.length) {
  19042. this.materials[0].dispose();
  19043. }
  19044. // Release particles
  19045. while (this.particleSystems.length) {
  19046. this.particleSystems[0].dispose();
  19047. }
  19048. // Release sprites
  19049. while (this.spriteManagers.length) {
  19050. this.spriteManagers[0].dispose();
  19051. }
  19052. // Release postProcesses
  19053. while (this.postProcesses.length) {
  19054. this.postProcesses[0].dispose();
  19055. }
  19056. // Release layers
  19057. while (this.layers.length) {
  19058. this.layers[0].dispose();
  19059. }
  19060. while (this.highlightLayers.length) {
  19061. this.highlightLayers[0].dispose();
  19062. }
  19063. // Release textures
  19064. while (this.textures.length) {
  19065. this.textures[0].dispose();
  19066. }
  19067. // Release UBO
  19068. this._sceneUbo.dispose();
  19069. // Post-processes
  19070. this.postProcessManager.dispose();
  19071. if (this._postProcessRenderPipelineManager) {
  19072. this._postProcessRenderPipelineManager.dispose();
  19073. }
  19074. // Physics
  19075. if (this._physicsEngine) {
  19076. this.disablePhysicsEngine();
  19077. }
  19078. // Remove from engine
  19079. index = this._engine.scenes.indexOf(this);
  19080. if (index > -1) {
  19081. this._engine.scenes.splice(index, 1);
  19082. }
  19083. this._engine.wipeCaches();
  19084. this._engine = null;
  19085. this.defaultMaterial = null;
  19086. this.multiMaterials = null;
  19087. this.materials = null;
  19088. };
  19089. Object.defineProperty(Scene.prototype, "isDisposed", {
  19090. get: function () {
  19091. return !this._engine;
  19092. },
  19093. enumerable: true,
  19094. configurable: true
  19095. });
  19096. // Release sounds & sounds tracks
  19097. Scene.prototype.disposeSounds = function () {
  19098. this.mainSoundTrack.dispose();
  19099. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19100. this.soundTracks[scIndex].dispose();
  19101. }
  19102. };
  19103. // Octrees
  19104. Scene.prototype.getWorldExtends = function () {
  19105. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19106. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19107. for (var index = 0; index < this.meshes.length; index++) {
  19108. var mesh = this.meshes[index];
  19109. mesh.computeWorldMatrix(true);
  19110. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19111. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19112. BABYLON.Tools.CheckExtends(minBox, min, max);
  19113. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19114. }
  19115. return {
  19116. min: min,
  19117. max: max
  19118. };
  19119. };
  19120. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19121. if (maxCapacity === void 0) { maxCapacity = 64; }
  19122. if (maxDepth === void 0) { maxDepth = 2; }
  19123. if (!this._selectionOctree) {
  19124. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19125. }
  19126. var worldExtends = this.getWorldExtends();
  19127. // Update octree
  19128. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19129. return this._selectionOctree;
  19130. };
  19131. // Picking
  19132. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19133. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19134. var engine = this._engine;
  19135. if (!camera) {
  19136. if (!this.activeCamera)
  19137. throw new Error("Active camera not set");
  19138. camera = this.activeCamera;
  19139. }
  19140. var cameraViewport = camera.viewport;
  19141. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19142. // Moving coordinates to local viewport world
  19143. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19144. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19145. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19146. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19147. };
  19148. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19149. if (!BABYLON.PickingInfo) {
  19150. return null;
  19151. }
  19152. var engine = this._engine;
  19153. if (!camera) {
  19154. if (!this.activeCamera)
  19155. throw new Error("Active camera not set");
  19156. camera = this.activeCamera;
  19157. }
  19158. var cameraViewport = camera.viewport;
  19159. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19160. var identity = BABYLON.Matrix.Identity();
  19161. // Moving coordinates to local viewport world
  19162. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19163. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19164. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19165. };
  19166. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19167. if (!BABYLON.PickingInfo) {
  19168. return null;
  19169. }
  19170. var pickingInfo = null;
  19171. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19172. var mesh = this.meshes[meshIndex];
  19173. if (predicate) {
  19174. if (!predicate(mesh)) {
  19175. continue;
  19176. }
  19177. }
  19178. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19179. continue;
  19180. }
  19181. var world = mesh.getWorldMatrix();
  19182. var ray = rayFunction(world);
  19183. var result = mesh.intersects(ray, fastCheck);
  19184. if (!result || !result.hit)
  19185. continue;
  19186. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19187. continue;
  19188. pickingInfo = result;
  19189. if (fastCheck) {
  19190. break;
  19191. }
  19192. }
  19193. return pickingInfo || new BABYLON.PickingInfo();
  19194. };
  19195. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19196. if (!BABYLON.PickingInfo) {
  19197. return null;
  19198. }
  19199. var pickingInfos = new Array();
  19200. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19201. var mesh = this.meshes[meshIndex];
  19202. if (predicate) {
  19203. if (!predicate(mesh)) {
  19204. continue;
  19205. }
  19206. }
  19207. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19208. continue;
  19209. }
  19210. var world = mesh.getWorldMatrix();
  19211. var ray = rayFunction(world);
  19212. var result = mesh.intersects(ray, false);
  19213. if (!result || !result.hit)
  19214. continue;
  19215. pickingInfos.push(result);
  19216. }
  19217. return pickingInfos;
  19218. };
  19219. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19220. if (!BABYLON.PickingInfo) {
  19221. return null;
  19222. }
  19223. var pickingInfo = null;
  19224. camera = camera || this.activeCamera;
  19225. if (this.spriteManagers.length > 0) {
  19226. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19227. var spriteManager = this.spriteManagers[spriteIndex];
  19228. if (!spriteManager.isPickable) {
  19229. continue;
  19230. }
  19231. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19232. if (!result || !result.hit)
  19233. continue;
  19234. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19235. continue;
  19236. pickingInfo = result;
  19237. if (fastCheck) {
  19238. break;
  19239. }
  19240. }
  19241. }
  19242. return pickingInfo || new BABYLON.PickingInfo();
  19243. };
  19244. /** Launch a ray to try to pick a mesh in the scene
  19245. * @param x position on screen
  19246. * @param y position on screen
  19247. * @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
  19248. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19249. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19250. */
  19251. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19252. var _this = this;
  19253. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19254. };
  19255. /** Launch a ray to try to pick a sprite in the scene
  19256. * @param x position on screen
  19257. * @param y position on screen
  19258. * @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
  19259. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19260. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19261. */
  19262. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19263. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19264. };
  19265. /** Use the given ray to pick a mesh in the scene
  19266. * @param ray The ray to use to pick meshes
  19267. * @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
  19268. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19269. */
  19270. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19271. var _this = this;
  19272. return this._internalPick(function (world) {
  19273. if (!_this._pickWithRayInverseMatrix) {
  19274. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19275. }
  19276. world.invertToRef(_this._pickWithRayInverseMatrix);
  19277. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19278. }, predicate, fastCheck);
  19279. };
  19280. /**
  19281. * Launch a ray to try to pick a mesh in the scene
  19282. * @param x X position on screen
  19283. * @param y Y position on screen
  19284. * @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
  19285. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19286. */
  19287. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19288. var _this = this;
  19289. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19290. };
  19291. /**
  19292. * Launch a ray to try to pick a mesh in the scene
  19293. * @param ray Ray to use
  19294. * @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
  19295. */
  19296. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19297. var _this = this;
  19298. return this._internalMultiPick(function (world) {
  19299. if (!_this._pickWithRayInverseMatrix) {
  19300. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19301. }
  19302. world.invertToRef(_this._pickWithRayInverseMatrix);
  19303. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19304. }, predicate);
  19305. };
  19306. Scene.prototype.setPointerOverMesh = function (mesh) {
  19307. if (this._pointerOverMesh === mesh) {
  19308. return;
  19309. }
  19310. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19311. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19312. }
  19313. this._pointerOverMesh = mesh;
  19314. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19315. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19316. }
  19317. };
  19318. Scene.prototype.getPointerOverMesh = function () {
  19319. return this._pointerOverMesh;
  19320. };
  19321. Scene.prototype.setPointerOverSprite = function (sprite) {
  19322. if (this._pointerOverSprite === sprite) {
  19323. return;
  19324. }
  19325. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19326. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19327. }
  19328. this._pointerOverSprite = sprite;
  19329. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19330. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19331. }
  19332. };
  19333. Scene.prototype.getPointerOverSprite = function () {
  19334. return this._pointerOverSprite;
  19335. };
  19336. // Physics
  19337. Scene.prototype.getPhysicsEngine = function () {
  19338. return this._physicsEngine;
  19339. };
  19340. /**
  19341. * Enables physics to the current scene
  19342. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19343. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19344. * @return {boolean} was the physics engine initialized
  19345. */
  19346. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19347. if (this._physicsEngine) {
  19348. return true;
  19349. }
  19350. try {
  19351. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19352. return true;
  19353. }
  19354. catch (e) {
  19355. BABYLON.Tools.Error(e.message);
  19356. return false;
  19357. }
  19358. };
  19359. Scene.prototype.disablePhysicsEngine = function () {
  19360. if (!this._physicsEngine) {
  19361. return;
  19362. }
  19363. this._physicsEngine.dispose();
  19364. this._physicsEngine = undefined;
  19365. };
  19366. Scene.prototype.isPhysicsEnabled = function () {
  19367. return this._physicsEngine !== undefined;
  19368. };
  19369. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19370. var mesh = compound.parts[0].mesh;
  19371. mesh.physicsImpostor.dispose();
  19372. mesh.physicsImpostor = null;
  19373. };
  19374. // Misc.
  19375. Scene.prototype._rebuildGeometries = function () {
  19376. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19377. var geometry = _a[_i];
  19378. geometry._rebuild();
  19379. }
  19380. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19381. var mesh = _c[_b];
  19382. mesh._rebuild();
  19383. }
  19384. if (this.postProcessManager) {
  19385. this.postProcessManager._rebuild();
  19386. }
  19387. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19388. var layer = _e[_d];
  19389. layer._rebuild();
  19390. }
  19391. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19392. var highlightLayer = _g[_f];
  19393. highlightLayer._rebuild();
  19394. }
  19395. if (this._boundingBoxRenderer) {
  19396. this._boundingBoxRenderer._rebuild();
  19397. }
  19398. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19399. var system = _j[_h];
  19400. system.rebuild();
  19401. }
  19402. if (this._postProcessRenderPipelineManager) {
  19403. this._postProcessRenderPipelineManager._rebuild();
  19404. }
  19405. };
  19406. Scene.prototype._rebuildTextures = function () {
  19407. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19408. var texture = _a[_i];
  19409. texture._rebuild();
  19410. }
  19411. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19412. };
  19413. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19414. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19415. if (replace === void 0) { replace = false; }
  19416. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19417. // Dispose existing camera or light in replace mode.
  19418. if (replace) {
  19419. if (this.activeCamera) {
  19420. this.activeCamera.dispose();
  19421. this.activeCamera = null;
  19422. }
  19423. if (this.lights) {
  19424. for (var i = 0; i < this.lights.length; i++) {
  19425. this.lights[i].dispose();
  19426. }
  19427. }
  19428. }
  19429. // Light
  19430. if (this.lights.length === 0) {
  19431. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19432. }
  19433. // Camera
  19434. if (!this.activeCamera) {
  19435. var worldExtends = this.getWorldExtends();
  19436. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19437. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19438. var camera;
  19439. var radius = worldSize.length() * 1.5;
  19440. if (createArcRotateCamera) {
  19441. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19442. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19443. arcRotateCamera.wheelPrecision = 100 / radius;
  19444. camera = arcRotateCamera;
  19445. }
  19446. else {
  19447. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19448. freeCamera.setTarget(worldCenter);
  19449. camera = freeCamera;
  19450. }
  19451. camera.minZ = radius * 0.01;
  19452. camera.maxZ = radius * 100;
  19453. camera.speed = radius * 0.2;
  19454. this.activeCamera = camera;
  19455. if (attachCameraControls) {
  19456. camera.attachControl(this.getEngine().getRenderingCanvas());
  19457. }
  19458. }
  19459. };
  19460. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19461. if (pbr === void 0) { pbr = false; }
  19462. if (scale === void 0) { scale = 1000; }
  19463. if (blur === void 0) { blur = 0; }
  19464. if (environmentTexture) {
  19465. this.environmentTexture = environmentTexture;
  19466. }
  19467. if (!this.environmentTexture) {
  19468. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19469. return;
  19470. }
  19471. // Skybox
  19472. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19473. if (pbr) {
  19474. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19475. hdrSkyboxMaterial.backFaceCulling = false;
  19476. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19477. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19478. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19479. hdrSkyboxMaterial.disableLighting = true;
  19480. hdrSkyboxMaterial.twoSidedLighting = true;
  19481. hdrSkybox.infiniteDistance = true;
  19482. hdrSkybox.material = hdrSkyboxMaterial;
  19483. }
  19484. else {
  19485. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19486. skyboxMaterial.backFaceCulling = false;
  19487. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19488. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19489. skyboxMaterial.disableLighting = true;
  19490. hdrSkybox.infiniteDistance = true;
  19491. hdrSkybox.material = skyboxMaterial;
  19492. }
  19493. return hdrSkybox;
  19494. };
  19495. Scene.prototype.createDefaultVRExperience = function () {
  19496. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19497. };
  19498. // Tags
  19499. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19500. if (tagsQuery === undefined) {
  19501. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19502. return list;
  19503. }
  19504. var listByTags = [];
  19505. forEach = forEach || (function (item) { return; });
  19506. for (var i in list) {
  19507. var item = list[i];
  19508. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19509. listByTags.push(item);
  19510. forEach(item);
  19511. }
  19512. }
  19513. return listByTags;
  19514. };
  19515. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19516. return this._getByTags(this.meshes, tagsQuery, forEach);
  19517. };
  19518. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19519. return this._getByTags(this.cameras, tagsQuery, forEach);
  19520. };
  19521. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19522. return this._getByTags(this.lights, tagsQuery, forEach);
  19523. };
  19524. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19525. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19526. };
  19527. /**
  19528. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19529. * This allowed control for front to back rendering or reversly depending of the special needs.
  19530. *
  19531. * @param renderingGroupId The rendering group id corresponding to its index
  19532. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19533. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19534. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19535. */
  19536. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19537. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19538. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19539. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19540. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19541. };
  19542. /**
  19543. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19544. *
  19545. * @param renderingGroupId The rendering group id corresponding to its index
  19546. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19547. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19548. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19549. */
  19550. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19551. if (depth === void 0) { depth = true; }
  19552. if (stencil === void 0) { stencil = true; }
  19553. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19554. };
  19555. /**
  19556. * Will flag all materials as dirty to trigger new shader compilation
  19557. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19558. */
  19559. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19560. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19561. var material = _a[_i];
  19562. if (predicate && !predicate(material)) {
  19563. continue;
  19564. }
  19565. material.markAsDirty(flag);
  19566. }
  19567. };
  19568. // Statics
  19569. Scene._FOGMODE_NONE = 0;
  19570. Scene._FOGMODE_EXP = 1;
  19571. Scene._FOGMODE_EXP2 = 2;
  19572. Scene._FOGMODE_LINEAR = 3;
  19573. Scene.MinDeltaTime = 1.0;
  19574. Scene.MaxDeltaTime = 1000.0;
  19575. /** The distance in pixel that you have to move to prevent some events */
  19576. Scene.DragMovementThreshold = 10; // in pixels
  19577. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19578. Scene.LongPressDelay = 500; // in milliseconds
  19579. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19580. Scene.DoubleClickDelay = 300; // in milliseconds
  19581. /** If you need to check double click without raising a single click at first click, enable this flag */
  19582. Scene.ExclusiveDoubleClickMode = false;
  19583. return Scene;
  19584. }());
  19585. BABYLON.Scene = Scene;
  19586. })(BABYLON || (BABYLON = {}));
  19587. //# sourceMappingURL=babylon.scene.js.map
  19588. var BABYLON;
  19589. (function (BABYLON) {
  19590. var Buffer = (function () {
  19591. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19592. if (engine instanceof BABYLON.Mesh) {
  19593. this._engine = engine.getScene().getEngine();
  19594. }
  19595. else {
  19596. this._engine = engine;
  19597. }
  19598. this._updatable = updatable;
  19599. this._data = data;
  19600. this._strideSize = stride;
  19601. if (!postponeInternalCreation) {
  19602. this.create();
  19603. }
  19604. this._instanced = instanced;
  19605. this._instanceDivisor = instanced ? 1 : 0;
  19606. }
  19607. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19608. // a lot of these parameters are ignored as they are overriden by the buffer
  19609. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19610. };
  19611. // Properties
  19612. Buffer.prototype.isUpdatable = function () {
  19613. return this._updatable;
  19614. };
  19615. Buffer.prototype.getData = function () {
  19616. return this._data;
  19617. };
  19618. Buffer.prototype.getBuffer = function () {
  19619. return this._buffer;
  19620. };
  19621. Buffer.prototype.getStrideSize = function () {
  19622. return this._strideSize;
  19623. };
  19624. Buffer.prototype.getIsInstanced = function () {
  19625. return this._instanced;
  19626. };
  19627. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19628. get: function () {
  19629. return this._instanceDivisor;
  19630. },
  19631. set: function (value) {
  19632. this._instanceDivisor = value;
  19633. if (value == 0) {
  19634. this._instanced = false;
  19635. }
  19636. else {
  19637. this._instanced = true;
  19638. }
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. // Methods
  19644. Buffer.prototype.create = function (data) {
  19645. if (!data && this._buffer) {
  19646. return; // nothing to do
  19647. }
  19648. data = data || this._data;
  19649. if (!this._buffer) {
  19650. if (this._updatable) {
  19651. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19652. this._data = data;
  19653. }
  19654. else {
  19655. this._buffer = this._engine.createVertexBuffer(data);
  19656. }
  19657. }
  19658. else if (this._updatable) {
  19659. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19660. this._data = data;
  19661. }
  19662. };
  19663. Buffer.prototype._rebuild = function () {
  19664. this._buffer = null;
  19665. this.create(this._data);
  19666. };
  19667. Buffer.prototype.update = function (data) {
  19668. this.create(data);
  19669. };
  19670. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19671. if (!this._buffer) {
  19672. return;
  19673. }
  19674. if (this._updatable) {
  19675. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19676. this._data = null;
  19677. }
  19678. };
  19679. Buffer.prototype.dispose = function () {
  19680. if (!this._buffer) {
  19681. return;
  19682. }
  19683. if (this._engine._releaseBuffer(this._buffer)) {
  19684. this._buffer = null;
  19685. }
  19686. };
  19687. return Buffer;
  19688. }());
  19689. BABYLON.Buffer = Buffer;
  19690. })(BABYLON || (BABYLON = {}));
  19691. //# sourceMappingURL=babylon.buffer.js.map
  19692. var BABYLON;
  19693. (function (BABYLON) {
  19694. var VertexBuffer = (function () {
  19695. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19696. if (!stride) {
  19697. // Deduce stride from kind
  19698. switch (kind) {
  19699. case VertexBuffer.PositionKind:
  19700. stride = 3;
  19701. break;
  19702. case VertexBuffer.NormalKind:
  19703. stride = 3;
  19704. break;
  19705. case VertexBuffer.UVKind:
  19706. case VertexBuffer.UV2Kind:
  19707. case VertexBuffer.UV3Kind:
  19708. case VertexBuffer.UV4Kind:
  19709. case VertexBuffer.UV5Kind:
  19710. case VertexBuffer.UV6Kind:
  19711. stride = 2;
  19712. break;
  19713. case VertexBuffer.TangentKind:
  19714. case VertexBuffer.ColorKind:
  19715. stride = 4;
  19716. break;
  19717. case VertexBuffer.MatricesIndicesKind:
  19718. case VertexBuffer.MatricesIndicesExtraKind:
  19719. stride = 4;
  19720. break;
  19721. case VertexBuffer.MatricesWeightsKind:
  19722. case VertexBuffer.MatricesWeightsExtraKind:
  19723. stride = 4;
  19724. break;
  19725. }
  19726. }
  19727. if (data instanceof BABYLON.Buffer) {
  19728. if (!stride) {
  19729. stride = data.getStrideSize();
  19730. }
  19731. this._buffer = data;
  19732. this._ownsBuffer = false;
  19733. }
  19734. else {
  19735. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19736. this._ownsBuffer = true;
  19737. }
  19738. this._stride = stride;
  19739. this._offset = offset ? offset : 0;
  19740. this._size = size ? size : stride;
  19741. this._kind = kind;
  19742. }
  19743. VertexBuffer.prototype._rebuild = function () {
  19744. if (!this._buffer) {
  19745. return;
  19746. }
  19747. this._buffer._rebuild();
  19748. };
  19749. /**
  19750. * Returns the kind of the VertexBuffer (string).
  19751. */
  19752. VertexBuffer.prototype.getKind = function () {
  19753. return this._kind;
  19754. };
  19755. // Properties
  19756. /**
  19757. * Boolean : is the VertexBuffer updatable ?
  19758. */
  19759. VertexBuffer.prototype.isUpdatable = function () {
  19760. return this._buffer.isUpdatable();
  19761. };
  19762. /**
  19763. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19764. */
  19765. VertexBuffer.prototype.getData = function () {
  19766. return this._buffer.getData();
  19767. };
  19768. /**
  19769. * Returns the WebGLBuffer associated to the VertexBuffer.
  19770. */
  19771. VertexBuffer.prototype.getBuffer = function () {
  19772. return this._buffer.getBuffer();
  19773. };
  19774. /**
  19775. * Returns the stride of the VertexBuffer (integer).
  19776. */
  19777. VertexBuffer.prototype.getStrideSize = function () {
  19778. return this._stride;
  19779. };
  19780. /**
  19781. * Returns the offset (integer).
  19782. */
  19783. VertexBuffer.prototype.getOffset = function () {
  19784. return this._offset;
  19785. };
  19786. /**
  19787. * Returns the VertexBuffer total size (integer).
  19788. */
  19789. VertexBuffer.prototype.getSize = function () {
  19790. return this._size;
  19791. };
  19792. /**
  19793. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19794. */
  19795. VertexBuffer.prototype.getIsInstanced = function () {
  19796. return this._buffer.getIsInstanced();
  19797. };
  19798. /**
  19799. * Returns the instancing divisor, zero for non-instanced (integer).
  19800. */
  19801. VertexBuffer.prototype.getInstanceDivisor = function () {
  19802. return this._buffer.instanceDivisor;
  19803. };
  19804. // Methods
  19805. /**
  19806. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19807. * Returns the created WebGLBuffer.
  19808. */
  19809. VertexBuffer.prototype.create = function (data) {
  19810. return this._buffer.create(data);
  19811. };
  19812. /**
  19813. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19814. * Returns the updated WebGLBuffer.
  19815. */
  19816. VertexBuffer.prototype.update = function (data) {
  19817. return this._buffer.update(data);
  19818. };
  19819. /**
  19820. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19821. * Returns the directly updated WebGLBuffer.
  19822. */
  19823. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19824. return this._buffer.updateDirectly(data, offset);
  19825. };
  19826. /**
  19827. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19828. */
  19829. VertexBuffer.prototype.dispose = function () {
  19830. if (this._ownsBuffer) {
  19831. this._buffer.dispose();
  19832. }
  19833. };
  19834. Object.defineProperty(VertexBuffer, "PositionKind", {
  19835. get: function () {
  19836. return VertexBuffer._PositionKind;
  19837. },
  19838. enumerable: true,
  19839. configurable: true
  19840. });
  19841. Object.defineProperty(VertexBuffer, "NormalKind", {
  19842. get: function () {
  19843. return VertexBuffer._NormalKind;
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(VertexBuffer, "TangentKind", {
  19849. get: function () {
  19850. return VertexBuffer._TangentKind;
  19851. },
  19852. enumerable: true,
  19853. configurable: true
  19854. });
  19855. Object.defineProperty(VertexBuffer, "UVKind", {
  19856. get: function () {
  19857. return VertexBuffer._UVKind;
  19858. },
  19859. enumerable: true,
  19860. configurable: true
  19861. });
  19862. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19863. get: function () {
  19864. return VertexBuffer._UV2Kind;
  19865. },
  19866. enumerable: true,
  19867. configurable: true
  19868. });
  19869. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19870. get: function () {
  19871. return VertexBuffer._UV3Kind;
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19877. get: function () {
  19878. return VertexBuffer._UV4Kind;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19884. get: function () {
  19885. return VertexBuffer._UV5Kind;
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19891. get: function () {
  19892. return VertexBuffer._UV6Kind;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(VertexBuffer, "ColorKind", {
  19898. get: function () {
  19899. return VertexBuffer._ColorKind;
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19905. get: function () {
  19906. return VertexBuffer._MatricesIndicesKind;
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19912. get: function () {
  19913. return VertexBuffer._MatricesWeightsKind;
  19914. },
  19915. enumerable: true,
  19916. configurable: true
  19917. });
  19918. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19919. get: function () {
  19920. return VertexBuffer._MatricesIndicesExtraKind;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19926. get: function () {
  19927. return VertexBuffer._MatricesWeightsExtraKind;
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. // Enums
  19933. VertexBuffer._PositionKind = "position";
  19934. VertexBuffer._NormalKind = "normal";
  19935. VertexBuffer._TangentKind = "tangent";
  19936. VertexBuffer._UVKind = "uv";
  19937. VertexBuffer._UV2Kind = "uv2";
  19938. VertexBuffer._UV3Kind = "uv3";
  19939. VertexBuffer._UV4Kind = "uv4";
  19940. VertexBuffer._UV5Kind = "uv5";
  19941. VertexBuffer._UV6Kind = "uv6";
  19942. VertexBuffer._ColorKind = "color";
  19943. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19944. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19945. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19946. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19947. return VertexBuffer;
  19948. }());
  19949. BABYLON.VertexBuffer = VertexBuffer;
  19950. })(BABYLON || (BABYLON = {}));
  19951. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19952. var BABYLON;
  19953. (function (BABYLON) {
  19954. var InternalTexture = (function () {
  19955. function InternalTexture(engine, dataSource) {
  19956. this.onLoadedObservable = new BABYLON.Observable();
  19957. // Private
  19958. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  19959. this._references = 1;
  19960. this._engine = engine;
  19961. this._dataSource = dataSource;
  19962. this._webGLTexture = engine._createTexture();
  19963. }
  19964. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  19965. get: function () {
  19966. return this._dataSource;
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. InternalTexture.prototype.incrementReferences = function () {
  19972. this._references++;
  19973. };
  19974. InternalTexture.prototype.updateSize = function (width, height) {
  19975. this.width = width;
  19976. this.height = height;
  19977. this._size = width * height;
  19978. this.baseWidth = width;
  19979. this.baseHeight = height;
  19980. };
  19981. InternalTexture.prototype._rebuild = function () {
  19982. var _this = this;
  19983. var proxy;
  19984. this.isReady = false;
  19985. this._cachedCoordinatesMode = null;
  19986. this._cachedWrapU = null;
  19987. this._cachedWrapV = null;
  19988. this._cachedAnisotropicFilteringLevel = null;
  19989. switch (this._dataSource) {
  19990. case InternalTexture.DATASOURCE_TEMP:
  19991. return;
  19992. case InternalTexture.DATASOURCE_URL:
  19993. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  19994. _this.isReady = true;
  19995. }, null, this._buffer, null, this.format);
  19996. proxy._swapAndDie(this);
  19997. return;
  19998. case InternalTexture.DATASOURCE_RAW:
  19999. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20000. proxy._swapAndDie(this);
  20001. this.isReady = true;
  20002. return;
  20003. case InternalTexture.DATASOURCE_DYNAMIC:
  20004. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20005. proxy._swapAndDie(this);
  20006. // The engine will make sure to update content so no need to flag it as isReady = true
  20007. return;
  20008. case InternalTexture.DATASOURCE_RENDERTARGET:
  20009. var options = new BABYLON.RenderTargetCreationOptions();
  20010. options.generateDepthBuffer = this._generateDepthBuffer;
  20011. options.generateMipMaps = this.generateMipMaps;
  20012. options.generateStencilBuffer = this._generateStencilBuffer;
  20013. options.samplingMode = this.samplingMode;
  20014. options.type = this.type;
  20015. if (this.isCube) {
  20016. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20017. }
  20018. else {
  20019. var size = {
  20020. width: this.width,
  20021. height: this.height
  20022. };
  20023. proxy = this._engine.createRenderTargetTexture(size, options);
  20024. }
  20025. proxy._swapAndDie(this);
  20026. this.isReady = true;
  20027. return;
  20028. case InternalTexture.DATASOURCE_CUBE:
  20029. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20030. _this.isReady = true;
  20031. }, null, this.format, this._extension);
  20032. proxy._swapAndDie(this);
  20033. return;
  20034. case InternalTexture.DATASOURCE_CUBERAW:
  20035. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20036. proxy._swapAndDie(this);
  20037. this.isReady = true;
  20038. return;
  20039. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20040. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20041. proxy._swapAndDie(_this);
  20042. _this.isReady = true;
  20043. }, null, this.format, this._extension);
  20044. return;
  20045. }
  20046. };
  20047. InternalTexture.prototype._swapAndDie = function (target) {
  20048. target._webGLTexture = this._webGLTexture;
  20049. if (this._framebuffer) {
  20050. target._framebuffer = this._framebuffer;
  20051. }
  20052. if (this._depthStencilBuffer) {
  20053. target._depthStencilBuffer = this._depthStencilBuffer;
  20054. }
  20055. if (this._lodTextureHigh) {
  20056. if (target._lodTextureHigh) {
  20057. target._lodTextureHigh.dispose();
  20058. }
  20059. target._lodTextureHigh = this._lodTextureHigh;
  20060. }
  20061. if (this._lodTextureMid) {
  20062. if (target._lodTextureMid) {
  20063. target._lodTextureMid.dispose();
  20064. }
  20065. target._lodTextureMid = this._lodTextureMid;
  20066. }
  20067. if (this._lodTextureLow) {
  20068. if (target._lodTextureLow) {
  20069. target._lodTextureLow.dispose();
  20070. }
  20071. target._lodTextureLow = this._lodTextureLow;
  20072. }
  20073. var cache = this._engine.getLoadedTexturesCache();
  20074. var index = cache.indexOf(this);
  20075. if (index !== -1) {
  20076. cache.splice(index, 1);
  20077. }
  20078. };
  20079. InternalTexture.prototype.dispose = function () {
  20080. if (!this._webGLTexture) {
  20081. return;
  20082. }
  20083. this._references--;
  20084. if (this._references === 0) {
  20085. this._engine._releaseTexture(this);
  20086. this._webGLTexture = null;
  20087. }
  20088. };
  20089. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20090. InternalTexture.DATASOURCE_URL = 1;
  20091. InternalTexture.DATASOURCE_TEMP = 2;
  20092. InternalTexture.DATASOURCE_RAW = 3;
  20093. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20094. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20095. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20096. InternalTexture.DATASOURCE_CUBE = 7;
  20097. InternalTexture.DATASOURCE_CUBERAW = 8;
  20098. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20099. return InternalTexture;
  20100. }());
  20101. BABYLON.InternalTexture = InternalTexture;
  20102. })(BABYLON || (BABYLON = {}));
  20103. //# sourceMappingURL=babylon.internalTexture.js.map
  20104. var BABYLON;
  20105. (function (BABYLON) {
  20106. var BaseTexture = (function () {
  20107. function BaseTexture(scene) {
  20108. this._hasAlpha = false;
  20109. this.getAlphaFromRGB = false;
  20110. this.level = 1;
  20111. this.coordinatesIndex = 0;
  20112. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20113. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20114. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20115. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20116. this.isCube = false;
  20117. this.gammaSpace = true;
  20118. this.invertZ = false;
  20119. this.lodLevelInAlpha = false;
  20120. this.lodGenerationOffset = 0.0;
  20121. this.lodGenerationScale = 0.8;
  20122. this.isRenderTarget = false;
  20123. this.animations = new Array();
  20124. /**
  20125. * An event triggered when the texture is disposed.
  20126. * @type {BABYLON.Observable}
  20127. */
  20128. this.onDisposeObservable = new BABYLON.Observable();
  20129. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20130. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20131. this._scene.textures.push(this);
  20132. this._uid = null;
  20133. }
  20134. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20135. get: function () {
  20136. return this._hasAlpha;
  20137. },
  20138. set: function (value) {
  20139. if (this._hasAlpha === value) {
  20140. return;
  20141. }
  20142. this._hasAlpha = value;
  20143. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20149. get: function () {
  20150. return this._coordinatesMode;
  20151. },
  20152. set: function (value) {
  20153. if (this._coordinatesMode === value) {
  20154. return;
  20155. }
  20156. this._coordinatesMode = value;
  20157. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(BaseTexture.prototype, "uid", {
  20163. get: function () {
  20164. if (!this._uid) {
  20165. this._uid = BABYLON.Tools.RandomId();
  20166. }
  20167. return this._uid;
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. BaseTexture.prototype.toString = function () {
  20173. return this.name;
  20174. };
  20175. BaseTexture.prototype.getClassName = function () {
  20176. return "BaseTexture";
  20177. };
  20178. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20179. set: function (callback) {
  20180. if (this._onDisposeObserver) {
  20181. this.onDisposeObservable.remove(this._onDisposeObserver);
  20182. }
  20183. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20184. },
  20185. enumerable: true,
  20186. configurable: true
  20187. });
  20188. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20189. get: function () {
  20190. return true;
  20191. },
  20192. enumerable: true,
  20193. configurable: true
  20194. });
  20195. BaseTexture.prototype.getScene = function () {
  20196. return this._scene;
  20197. };
  20198. BaseTexture.prototype.getTextureMatrix = function () {
  20199. return null;
  20200. };
  20201. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20202. return null;
  20203. };
  20204. BaseTexture.prototype.getInternalTexture = function () {
  20205. return this._texture;
  20206. };
  20207. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20208. return !this.isBlocking || this.isReady();
  20209. };
  20210. BaseTexture.prototype.isReady = function () {
  20211. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20212. this.delayLoad();
  20213. return false;
  20214. }
  20215. if (this._texture) {
  20216. return this._texture.isReady;
  20217. }
  20218. return false;
  20219. };
  20220. BaseTexture.prototype.getSize = function () {
  20221. if (this._texture.width) {
  20222. return new BABYLON.Size(this._texture.width, this._texture.height);
  20223. }
  20224. if (this._texture._size) {
  20225. return new BABYLON.Size(this._texture._size, this._texture._size);
  20226. }
  20227. return BABYLON.Size.Zero();
  20228. };
  20229. BaseTexture.prototype.getBaseSize = function () {
  20230. if (!this.isReady() || !this._texture)
  20231. return BABYLON.Size.Zero();
  20232. if (this._texture._size) {
  20233. return new BABYLON.Size(this._texture._size, this._texture._size);
  20234. }
  20235. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20236. };
  20237. BaseTexture.prototype.scale = function (ratio) {
  20238. };
  20239. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20240. get: function () {
  20241. return false;
  20242. },
  20243. enumerable: true,
  20244. configurable: true
  20245. });
  20246. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20247. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20248. for (var index = 0; index < texturesCache.length; index++) {
  20249. var texturesCacheEntry = texturesCache[index];
  20250. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20251. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20252. texturesCacheEntry.incrementReferences();
  20253. return texturesCacheEntry;
  20254. }
  20255. }
  20256. }
  20257. return null;
  20258. };
  20259. BaseTexture.prototype._rebuild = function () {
  20260. };
  20261. BaseTexture.prototype.delayLoad = function () {
  20262. };
  20263. BaseTexture.prototype.clone = function () {
  20264. return null;
  20265. };
  20266. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20267. get: function () {
  20268. if (!this._texture) {
  20269. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20270. }
  20271. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20272. },
  20273. enumerable: true,
  20274. configurable: true
  20275. });
  20276. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20277. get: function () {
  20278. if (!this._texture) {
  20279. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20280. }
  20281. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20282. },
  20283. enumerable: true,
  20284. configurable: true
  20285. });
  20286. BaseTexture.prototype.readPixels = function (faceIndex) {
  20287. if (faceIndex === void 0) { faceIndex = 0; }
  20288. if (!this._texture) {
  20289. return null;
  20290. }
  20291. var size = this.getSize();
  20292. var engine = this.getScene().getEngine();
  20293. if (this._texture.isCube) {
  20294. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20295. }
  20296. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20297. };
  20298. BaseTexture.prototype.releaseInternalTexture = function () {
  20299. if (this._texture) {
  20300. this._texture.dispose();
  20301. this._texture = null;
  20302. }
  20303. };
  20304. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20305. get: function () {
  20306. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20307. return null;
  20308. }
  20309. if (!this._texture._sphericalPolynomial) {
  20310. this._texture._sphericalPolynomial =
  20311. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20312. }
  20313. return this._texture._sphericalPolynomial;
  20314. },
  20315. set: function (value) {
  20316. if (this._texture) {
  20317. this._texture._sphericalPolynomial = value;
  20318. }
  20319. },
  20320. enumerable: true,
  20321. configurable: true
  20322. });
  20323. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20324. get: function () {
  20325. if (this._texture) {
  20326. return this._texture._lodTextureHigh;
  20327. }
  20328. return null;
  20329. },
  20330. enumerable: true,
  20331. configurable: true
  20332. });
  20333. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20334. get: function () {
  20335. if (this._texture) {
  20336. return this._texture._lodTextureMid;
  20337. }
  20338. return null;
  20339. },
  20340. enumerable: true,
  20341. configurable: true
  20342. });
  20343. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20344. get: function () {
  20345. if (this._texture) {
  20346. return this._texture._lodTextureLow;
  20347. }
  20348. return null;
  20349. },
  20350. enumerable: true,
  20351. configurable: true
  20352. });
  20353. BaseTexture.prototype.dispose = function () {
  20354. // Animations
  20355. this.getScene().stopAnimation(this);
  20356. // Remove from scene
  20357. this._scene._removePendingData(this);
  20358. var index = this._scene.textures.indexOf(this);
  20359. if (index >= 0) {
  20360. this._scene.textures.splice(index, 1);
  20361. }
  20362. if (this._texture === undefined) {
  20363. return;
  20364. }
  20365. // Release
  20366. this.releaseInternalTexture();
  20367. // Callback
  20368. this.onDisposeObservable.notifyObservers(this);
  20369. this.onDisposeObservable.clear();
  20370. };
  20371. BaseTexture.prototype.serialize = function () {
  20372. if (!this.name) {
  20373. return null;
  20374. }
  20375. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20376. // Animations
  20377. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20378. return serializationObject;
  20379. };
  20380. BaseTexture.WhenAllReady = function (textures, callback) {
  20381. var numRemaining = textures.length;
  20382. if (numRemaining === 0) {
  20383. callback();
  20384. return;
  20385. }
  20386. var _loop_1 = function () {
  20387. texture = textures[i];
  20388. if (texture.isReady()) {
  20389. if (--numRemaining === 0) {
  20390. callback();
  20391. }
  20392. }
  20393. else {
  20394. onLoadObservable = texture.onLoadObservable;
  20395. var onLoadCallback_1 = function () {
  20396. onLoadObservable.removeCallback(onLoadCallback_1);
  20397. if (--numRemaining === 0) {
  20398. callback();
  20399. }
  20400. };
  20401. onLoadObservable.add(onLoadCallback_1);
  20402. }
  20403. };
  20404. var texture, onLoadObservable;
  20405. for (var i = 0; i < textures.length; i++) {
  20406. _loop_1();
  20407. }
  20408. };
  20409. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20410. __decorate([
  20411. BABYLON.serialize()
  20412. ], BaseTexture.prototype, "name", void 0);
  20413. __decorate([
  20414. BABYLON.serialize("hasAlpha")
  20415. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20416. __decorate([
  20417. BABYLON.serialize()
  20418. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20419. __decorate([
  20420. BABYLON.serialize()
  20421. ], BaseTexture.prototype, "level", void 0);
  20422. __decorate([
  20423. BABYLON.serialize()
  20424. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20425. __decorate([
  20426. BABYLON.serialize("coordinatesMode")
  20427. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20428. __decorate([
  20429. BABYLON.serialize()
  20430. ], BaseTexture.prototype, "wrapU", void 0);
  20431. __decorate([
  20432. BABYLON.serialize()
  20433. ], BaseTexture.prototype, "wrapV", void 0);
  20434. __decorate([
  20435. BABYLON.serialize()
  20436. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20437. __decorate([
  20438. BABYLON.serialize()
  20439. ], BaseTexture.prototype, "isCube", void 0);
  20440. __decorate([
  20441. BABYLON.serialize()
  20442. ], BaseTexture.prototype, "gammaSpace", void 0);
  20443. __decorate([
  20444. BABYLON.serialize()
  20445. ], BaseTexture.prototype, "invertZ", void 0);
  20446. __decorate([
  20447. BABYLON.serialize()
  20448. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20449. __decorate([
  20450. BABYLON.serialize()
  20451. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20452. __decorate([
  20453. BABYLON.serialize()
  20454. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20455. __decorate([
  20456. BABYLON.serialize()
  20457. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20458. return BaseTexture;
  20459. }());
  20460. BABYLON.BaseTexture = BaseTexture;
  20461. })(BABYLON || (BABYLON = {}));
  20462. //# sourceMappingURL=babylon.baseTexture.js.map
  20463. var BABYLON;
  20464. (function (BABYLON) {
  20465. var Texture = (function (_super) {
  20466. __extends(Texture, _super);
  20467. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20468. if (noMipmap === void 0) { noMipmap = false; }
  20469. if (invertY === void 0) { invertY = true; }
  20470. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20471. if (onLoad === void 0) { onLoad = null; }
  20472. if (onError === void 0) { onError = null; }
  20473. if (buffer === void 0) { buffer = null; }
  20474. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20475. var _this = _super.call(this, scene) || this;
  20476. _this.uOffset = 0;
  20477. _this.vOffset = 0;
  20478. _this.uScale = 1.0;
  20479. _this.vScale = 1.0;
  20480. _this.uAng = 0;
  20481. _this.vAng = 0;
  20482. _this.wAng = 0;
  20483. _this._isBlocking = true;
  20484. _this.name = url;
  20485. _this.url = url;
  20486. _this._noMipmap = noMipmap;
  20487. _this._invertY = invertY;
  20488. _this._samplingMode = samplingMode;
  20489. _this._buffer = buffer;
  20490. _this._deleteBuffer = deleteBuffer;
  20491. _this._format = format;
  20492. scene = _this.getScene();
  20493. var load = function () {
  20494. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20495. _this.onLoadObservable.notifyObservers(_this);
  20496. }
  20497. if (onLoad) {
  20498. onLoad();
  20499. }
  20500. if (!_this.isBlocking) {
  20501. scene.resetCachedMaterial();
  20502. }
  20503. };
  20504. if (!url) {
  20505. _this._delayedOnLoad = load;
  20506. _this._delayedOnError = onError;
  20507. return _this;
  20508. }
  20509. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20510. if (!_this._texture) {
  20511. if (!scene.useDelayedTextureLoading) {
  20512. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20513. if (deleteBuffer) {
  20514. delete _this._buffer;
  20515. }
  20516. }
  20517. else {
  20518. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20519. _this._delayedOnLoad = load;
  20520. _this._delayedOnError = onError;
  20521. }
  20522. }
  20523. else {
  20524. if (_this._texture.isReady) {
  20525. BABYLON.Tools.SetImmediate(function () { return load(); });
  20526. }
  20527. else {
  20528. _this._texture.onLoadedObservable.add(load);
  20529. }
  20530. }
  20531. return _this;
  20532. }
  20533. Object.defineProperty(Texture.prototype, "noMipmap", {
  20534. get: function () {
  20535. return this._noMipmap;
  20536. },
  20537. enumerable: true,
  20538. configurable: true
  20539. });
  20540. Object.defineProperty(Texture.prototype, "isBlocking", {
  20541. get: function () {
  20542. return this._isBlocking;
  20543. },
  20544. set: function (value) {
  20545. this._isBlocking = value;
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. Object.defineProperty(Texture.prototype, "samplingMode", {
  20551. get: function () {
  20552. return this._samplingMode;
  20553. },
  20554. enumerable: true,
  20555. configurable: true
  20556. });
  20557. Texture.prototype.updateURL = function (url) {
  20558. this.url = url;
  20559. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20560. this.delayLoad();
  20561. };
  20562. Texture.prototype.delayLoad = function () {
  20563. var _this = this;
  20564. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20565. return;
  20566. }
  20567. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20568. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20569. if (!this._texture) {
  20570. 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);
  20571. if (this._deleteBuffer) {
  20572. delete this._buffer;
  20573. }
  20574. }
  20575. else {
  20576. if (this._texture.isReady) {
  20577. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20578. }
  20579. else {
  20580. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20581. }
  20582. }
  20583. };
  20584. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20585. if (!this._texture) {
  20586. return;
  20587. }
  20588. this._samplingMode = samplingMode;
  20589. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20590. };
  20591. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20592. x *= this.uScale;
  20593. y *= this.vScale;
  20594. x -= 0.5 * this.uScale;
  20595. y -= 0.5 * this.vScale;
  20596. z -= 0.5;
  20597. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20598. t.x += 0.5 * this.uScale + this.uOffset;
  20599. t.y += 0.5 * this.vScale + this.vOffset;
  20600. t.z += 0.5;
  20601. };
  20602. Texture.prototype.getTextureMatrix = function () {
  20603. var _this = this;
  20604. if (this.uOffset === this._cachedUOffset &&
  20605. this.vOffset === this._cachedVOffset &&
  20606. this.uScale === this._cachedUScale &&
  20607. this.vScale === this._cachedVScale &&
  20608. this.uAng === this._cachedUAng &&
  20609. this.vAng === this._cachedVAng &&
  20610. this.wAng === this._cachedWAng) {
  20611. return this._cachedTextureMatrix;
  20612. }
  20613. this._cachedUOffset = this.uOffset;
  20614. this._cachedVOffset = this.vOffset;
  20615. this._cachedUScale = this.uScale;
  20616. this._cachedVScale = this.vScale;
  20617. this._cachedUAng = this.uAng;
  20618. this._cachedVAng = this.vAng;
  20619. this._cachedWAng = this.wAng;
  20620. if (!this._cachedTextureMatrix) {
  20621. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20622. this._rowGenerationMatrix = new BABYLON.Matrix();
  20623. this._t0 = BABYLON.Vector3.Zero();
  20624. this._t1 = BABYLON.Vector3.Zero();
  20625. this._t2 = BABYLON.Vector3.Zero();
  20626. }
  20627. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20628. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20629. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20630. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20631. this._t1.subtractInPlace(this._t0);
  20632. this._t2.subtractInPlace(this._t0);
  20633. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20634. this._cachedTextureMatrix.m[0] = this._t1.x;
  20635. this._cachedTextureMatrix.m[1] = this._t1.y;
  20636. this._cachedTextureMatrix.m[2] = this._t1.z;
  20637. this._cachedTextureMatrix.m[4] = this._t2.x;
  20638. this._cachedTextureMatrix.m[5] = this._t2.y;
  20639. this._cachedTextureMatrix.m[6] = this._t2.z;
  20640. this._cachedTextureMatrix.m[8] = this._t0.x;
  20641. this._cachedTextureMatrix.m[9] = this._t0.y;
  20642. this._cachedTextureMatrix.m[10] = this._t0.z;
  20643. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20644. return mat.hasTexture(_this);
  20645. });
  20646. return this._cachedTextureMatrix;
  20647. };
  20648. Texture.prototype.getReflectionTextureMatrix = function () {
  20649. var _this = this;
  20650. var scene = this.getScene();
  20651. if (this.uOffset === this._cachedUOffset &&
  20652. this.vOffset === this._cachedVOffset &&
  20653. this.uScale === this._cachedUScale &&
  20654. this.vScale === this._cachedVScale &&
  20655. this.coordinatesMode === this._cachedCoordinatesMode) {
  20656. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20657. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20658. return this._cachedTextureMatrix;
  20659. }
  20660. }
  20661. else {
  20662. return this._cachedTextureMatrix;
  20663. }
  20664. }
  20665. if (!this._cachedTextureMatrix) {
  20666. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20667. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20668. }
  20669. this._cachedUOffset = this.uOffset;
  20670. this._cachedVOffset = this.vOffset;
  20671. this._cachedUScale = this.uScale;
  20672. this._cachedVScale = this.vScale;
  20673. this._cachedCoordinatesMode = this.coordinatesMode;
  20674. switch (this.coordinatesMode) {
  20675. case Texture.PLANAR_MODE:
  20676. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20677. this._cachedTextureMatrix[0] = this.uScale;
  20678. this._cachedTextureMatrix[5] = this.vScale;
  20679. this._cachedTextureMatrix[12] = this.uOffset;
  20680. this._cachedTextureMatrix[13] = this.vOffset;
  20681. break;
  20682. case Texture.PROJECTION_MODE:
  20683. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20684. this._projectionModeMatrix.m[0] = 0.5;
  20685. this._projectionModeMatrix.m[5] = -0.5;
  20686. this._projectionModeMatrix.m[10] = 0.0;
  20687. this._projectionModeMatrix.m[12] = 0.5;
  20688. this._projectionModeMatrix.m[13] = 0.5;
  20689. this._projectionModeMatrix.m[14] = 1.0;
  20690. this._projectionModeMatrix.m[15] = 1.0;
  20691. var projectionMatrix = scene.getProjectionMatrix();
  20692. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20693. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20694. break;
  20695. default:
  20696. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20697. break;
  20698. }
  20699. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20700. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20701. });
  20702. return this._cachedTextureMatrix;
  20703. };
  20704. Texture.prototype.clone = function () {
  20705. var _this = this;
  20706. return BABYLON.SerializationHelper.Clone(function () {
  20707. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20708. }, this);
  20709. };
  20710. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20711. get: function () {
  20712. if (!this._onLoadObservable) {
  20713. this._onLoadObservable = new BABYLON.Observable();
  20714. }
  20715. return this._onLoadObservable;
  20716. },
  20717. enumerable: true,
  20718. configurable: true
  20719. });
  20720. Texture.prototype.serialize = function () {
  20721. var serializationObject = _super.prototype.serialize.call(this);
  20722. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20723. serializationObject.base64String = this._buffer;
  20724. serializationObject.name = serializationObject.name.replace("data:", "");
  20725. }
  20726. return serializationObject;
  20727. };
  20728. Texture.prototype.getClassName = function () {
  20729. return "Texture";
  20730. };
  20731. Texture.prototype.dispose = function () {
  20732. _super.prototype.dispose.call(this);
  20733. if (this.onLoadObservable) {
  20734. this.onLoadObservable.clear();
  20735. this._onLoadObservable = null;
  20736. }
  20737. this._delayedOnLoad = null;
  20738. this._delayedOnError = null;
  20739. };
  20740. // Statics
  20741. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20742. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20743. if (onLoad === void 0) { onLoad = null; }
  20744. if (onError === void 0) { onError = null; }
  20745. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20746. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20747. };
  20748. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20749. if (parsedTexture.customType) {
  20750. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20751. // Update Sampling Mode
  20752. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20753. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20754. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20755. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20756. }
  20757. }
  20758. return parsedCustomTexture;
  20759. }
  20760. if (parsedTexture.isCube) {
  20761. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20762. }
  20763. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20764. return null;
  20765. }
  20766. var texture = BABYLON.SerializationHelper.Parse(function () {
  20767. if (parsedTexture.mirrorPlane) {
  20768. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20769. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20770. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20771. return mirrorTexture;
  20772. }
  20773. else if (parsedTexture.isRenderTarget) {
  20774. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20775. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20776. return renderTargetTexture;
  20777. }
  20778. else {
  20779. var texture;
  20780. if (parsedTexture.base64String) {
  20781. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20782. }
  20783. else {
  20784. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20785. }
  20786. return texture;
  20787. }
  20788. }, parsedTexture, scene);
  20789. // Update Sampling Mode
  20790. if (parsedTexture.samplingMode) {
  20791. var sampling = parsedTexture.samplingMode;
  20792. if (texture._samplingMode !== sampling) {
  20793. texture.updateSamplingMode(sampling);
  20794. }
  20795. }
  20796. // Animations
  20797. if (parsedTexture.animations) {
  20798. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20799. var parsedAnimation = parsedTexture.animations[animationIndex];
  20800. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20801. }
  20802. }
  20803. return texture;
  20804. };
  20805. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20806. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20807. if (noMipmap === void 0) { noMipmap = false; }
  20808. if (invertY === void 0) { invertY = true; }
  20809. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20810. if (onLoad === void 0) { onLoad = null; }
  20811. if (onError === void 0) { onError = null; }
  20812. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20813. if (name.substr(0, 5) !== "data:") {
  20814. name = "data:" + name;
  20815. }
  20816. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20817. };
  20818. // Constants
  20819. Texture.NEAREST_SAMPLINGMODE = 1;
  20820. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20821. Texture.BILINEAR_SAMPLINGMODE = 2;
  20822. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20823. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20824. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20825. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20826. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20827. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20828. Texture.NEAREST_LINEAR = 7;
  20829. Texture.NEAREST_NEAREST = 8;
  20830. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20831. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20832. Texture.LINEAR_LINEAR = 11;
  20833. Texture.LINEAR_NEAREST = 12;
  20834. Texture.EXPLICIT_MODE = 0;
  20835. Texture.SPHERICAL_MODE = 1;
  20836. Texture.PLANAR_MODE = 2;
  20837. Texture.CUBIC_MODE = 3;
  20838. Texture.PROJECTION_MODE = 4;
  20839. Texture.SKYBOX_MODE = 5;
  20840. Texture.INVCUBIC_MODE = 6;
  20841. Texture.EQUIRECTANGULAR_MODE = 7;
  20842. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20843. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20844. Texture.CLAMP_ADDRESSMODE = 0;
  20845. Texture.WRAP_ADDRESSMODE = 1;
  20846. Texture.MIRROR_ADDRESSMODE = 2;
  20847. __decorate([
  20848. BABYLON.serialize()
  20849. ], Texture.prototype, "url", void 0);
  20850. __decorate([
  20851. BABYLON.serialize()
  20852. ], Texture.prototype, "uOffset", void 0);
  20853. __decorate([
  20854. BABYLON.serialize()
  20855. ], Texture.prototype, "vOffset", void 0);
  20856. __decorate([
  20857. BABYLON.serialize()
  20858. ], Texture.prototype, "uScale", void 0);
  20859. __decorate([
  20860. BABYLON.serialize()
  20861. ], Texture.prototype, "vScale", void 0);
  20862. __decorate([
  20863. BABYLON.serialize()
  20864. ], Texture.prototype, "uAng", void 0);
  20865. __decorate([
  20866. BABYLON.serialize()
  20867. ], Texture.prototype, "vAng", void 0);
  20868. __decorate([
  20869. BABYLON.serialize()
  20870. ], Texture.prototype, "wAng", void 0);
  20871. __decorate([
  20872. BABYLON.serialize()
  20873. ], Texture.prototype, "isBlocking", null);
  20874. return Texture;
  20875. }(BABYLON.BaseTexture));
  20876. BABYLON.Texture = Texture;
  20877. })(BABYLON || (BABYLON = {}));
  20878. //# sourceMappingURL=babylon.texture.js.map
  20879. var BABYLON;
  20880. (function (BABYLON) {
  20881. var _InstancesBatch = (function () {
  20882. function _InstancesBatch() {
  20883. this.mustReturn = false;
  20884. this.visibleInstances = new Array();
  20885. this.renderSelf = new Array();
  20886. }
  20887. return _InstancesBatch;
  20888. }());
  20889. BABYLON._InstancesBatch = _InstancesBatch;
  20890. var Mesh = (function (_super) {
  20891. __extends(Mesh, _super);
  20892. /**
  20893. * @constructor
  20894. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20895. * @param {Scene} scene The scene to add this mesh to.
  20896. * @param {Node} parent The parent of this mesh, if it has one
  20897. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20898. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20899. * When false, achieved by calling a clone(), also passing False.
  20900. * This will make creation of children, recursive.
  20901. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20902. */
  20903. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20904. if (parent === void 0) { parent = null; }
  20905. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20906. var _this = _super.call(this, name, scene) || this;
  20907. // Events
  20908. /**
  20909. * An event triggered before rendering the mesh
  20910. * @type {BABYLON.Observable}
  20911. */
  20912. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20913. /**
  20914. * An event triggered after rendering the mesh
  20915. * @type {BABYLON.Observable}
  20916. */
  20917. _this.onAfterRenderObservable = new BABYLON.Observable();
  20918. /**
  20919. * An event triggered before drawing the mesh
  20920. * @type {BABYLON.Observable}
  20921. */
  20922. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20923. // Members
  20924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20925. _this.instances = new Array();
  20926. _this._LODLevels = new Array();
  20927. _this._visibleInstances = {};
  20928. _this._renderIdForInstances = new Array();
  20929. _this._batchCache = new _InstancesBatch();
  20930. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20931. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20932. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20933. // Will be used to save a source mesh reference, If any
  20934. _this._source = null;
  20935. if (source) {
  20936. // Source mesh
  20937. _this._source = source;
  20938. // Geometry
  20939. if (source._geometry) {
  20940. source._geometry.applyToMesh(_this);
  20941. }
  20942. // Deep copy
  20943. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20944. // Parent
  20945. _this.parent = source.parent;
  20946. // Pivot
  20947. _this.setPivotMatrix(source.getPivotMatrix());
  20948. _this.id = name + "." + source.id;
  20949. // Material
  20950. _this.material = source.material;
  20951. var index;
  20952. if (!doNotCloneChildren) {
  20953. // Children
  20954. for (index = 0; index < scene.meshes.length; index++) {
  20955. var mesh = scene.meshes[index];
  20956. if (mesh.parent === source) {
  20957. // doNotCloneChildren is always going to be False
  20958. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20959. }
  20960. }
  20961. }
  20962. // Physics clone
  20963. var physicsEngine = _this.getScene().getPhysicsEngine();
  20964. if (clonePhysicsImpostor && physicsEngine) {
  20965. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20966. if (impostor) {
  20967. _this.physicsImpostor = impostor.clone(_this);
  20968. }
  20969. }
  20970. // Particles
  20971. for (index = 0; index < scene.particleSystems.length; index++) {
  20972. var system = scene.particleSystems[index];
  20973. if (system.emitter === source) {
  20974. system.clone(system.name, _this);
  20975. }
  20976. }
  20977. _this.computeWorldMatrix(true);
  20978. }
  20979. // Parent
  20980. if (parent !== null) {
  20981. _this.parent = parent;
  20982. }
  20983. return _this;
  20984. }
  20985. Object.defineProperty(Mesh, "FRONTSIDE", {
  20986. /**
  20987. * Mesh side orientation : usually the external or front surface
  20988. */
  20989. get: function () {
  20990. return Mesh._FRONTSIDE;
  20991. },
  20992. enumerable: true,
  20993. configurable: true
  20994. });
  20995. Object.defineProperty(Mesh, "BACKSIDE", {
  20996. /**
  20997. * Mesh side orientation : usually the internal or back surface
  20998. */
  20999. get: function () {
  21000. return Mesh._BACKSIDE;
  21001. },
  21002. enumerable: true,
  21003. configurable: true
  21004. });
  21005. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21006. /**
  21007. * Mesh side orientation : both internal and external or front and back surfaces
  21008. */
  21009. get: function () {
  21010. return Mesh._DOUBLESIDE;
  21011. },
  21012. enumerable: true,
  21013. configurable: true
  21014. });
  21015. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21016. /**
  21017. * Mesh side orientation : by default, `FRONTSIDE`
  21018. */
  21019. get: function () {
  21020. return Mesh._DEFAULTSIDE;
  21021. },
  21022. enumerable: true,
  21023. configurable: true
  21024. });
  21025. Object.defineProperty(Mesh, "NO_CAP", {
  21026. /**
  21027. * Mesh cap setting : no cap
  21028. */
  21029. get: function () {
  21030. return Mesh._NO_CAP;
  21031. },
  21032. enumerable: true,
  21033. configurable: true
  21034. });
  21035. Object.defineProperty(Mesh, "CAP_START", {
  21036. /**
  21037. * Mesh cap setting : one cap at the beginning of the mesh
  21038. */
  21039. get: function () {
  21040. return Mesh._CAP_START;
  21041. },
  21042. enumerable: true,
  21043. configurable: true
  21044. });
  21045. Object.defineProperty(Mesh, "CAP_END", {
  21046. /**
  21047. * Mesh cap setting : one cap at the end of the mesh
  21048. */
  21049. get: function () {
  21050. return Mesh._CAP_END;
  21051. },
  21052. enumerable: true,
  21053. configurable: true
  21054. });
  21055. Object.defineProperty(Mesh, "CAP_ALL", {
  21056. /**
  21057. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21058. */
  21059. get: function () {
  21060. return Mesh._CAP_ALL;
  21061. },
  21062. enumerable: true,
  21063. configurable: true
  21064. });
  21065. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21066. set: function (callback) {
  21067. if (this._onBeforeDrawObserver) {
  21068. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21069. }
  21070. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21071. },
  21072. enumerable: true,
  21073. configurable: true
  21074. });
  21075. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21076. get: function () {
  21077. return this._morphTargetManager;
  21078. },
  21079. set: function (value) {
  21080. if (this._morphTargetManager === value) {
  21081. return;
  21082. }
  21083. this._morphTargetManager = value;
  21084. this._syncGeometryWithMorphTargetManager();
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(Mesh.prototype, "source", {
  21090. get: function () {
  21091. return this._source;
  21092. },
  21093. enumerable: true,
  21094. configurable: true
  21095. });
  21096. // Methods
  21097. /**
  21098. * Returns the string "Mesh".
  21099. */
  21100. Mesh.prototype.getClassName = function () {
  21101. return "Mesh";
  21102. };
  21103. /**
  21104. * Returns a string.
  21105. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21106. */
  21107. Mesh.prototype.toString = function (fullDetails) {
  21108. var ret = _super.prototype.toString.call(this, fullDetails);
  21109. ret += ", n vertices: " + this.getTotalVertices();
  21110. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21111. if (this.animations) {
  21112. for (var i = 0; i < this.animations.length; i++) {
  21113. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21114. }
  21115. }
  21116. if (fullDetails) {
  21117. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21118. }
  21119. return ret;
  21120. };
  21121. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21122. /**
  21123. * True if the mesh has some Levels Of Details (LOD).
  21124. * Returns a boolean.
  21125. */
  21126. get: function () {
  21127. return this._LODLevels.length > 0;
  21128. },
  21129. enumerable: true,
  21130. configurable: true
  21131. });
  21132. Mesh.prototype._sortLODLevels = function () {
  21133. this._LODLevels.sort(function (a, b) {
  21134. if (a.distance < b.distance) {
  21135. return 1;
  21136. }
  21137. if (a.distance > b.distance) {
  21138. return -1;
  21139. }
  21140. return 0;
  21141. });
  21142. };
  21143. /**
  21144. * Add a mesh as LOD level triggered at the given distance.
  21145. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21146. * @param {number} distance The distance from the center of the object to show this level
  21147. * @param {Mesh} mesh The mesh to be added as LOD level
  21148. * @return {Mesh} This mesh (for chaining)
  21149. */
  21150. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21151. if (mesh && mesh._masterMesh) {
  21152. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21153. return this;
  21154. }
  21155. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21156. this._LODLevels.push(level);
  21157. if (mesh) {
  21158. mesh._masterMesh = this;
  21159. }
  21160. this._sortLODLevels();
  21161. return this;
  21162. };
  21163. /**
  21164. * Returns the LOD level mesh at the passed distance or null if not found.
  21165. * It is related to the method `addLODLevel(distance, mesh)`.
  21166. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21167. * Returns an object Mesh or `null`.
  21168. */
  21169. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21170. for (var index = 0; index < this._LODLevels.length; index++) {
  21171. var level = this._LODLevels[index];
  21172. if (level.distance === distance) {
  21173. return level.mesh;
  21174. }
  21175. }
  21176. return null;
  21177. };
  21178. /**
  21179. * Remove a mesh from the LOD array
  21180. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21181. * @param {Mesh} mesh The mesh to be removed.
  21182. * @return {Mesh} This mesh (for chaining)
  21183. */
  21184. Mesh.prototype.removeLODLevel = function (mesh) {
  21185. for (var index = 0; index < this._LODLevels.length; index++) {
  21186. if (this._LODLevels[index].mesh === mesh) {
  21187. this._LODLevels.splice(index, 1);
  21188. if (mesh) {
  21189. mesh._masterMesh = null;
  21190. }
  21191. }
  21192. }
  21193. this._sortLODLevels();
  21194. return this;
  21195. };
  21196. /**
  21197. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21198. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21199. */
  21200. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21201. if (!this._LODLevels || this._LODLevels.length === 0) {
  21202. return this;
  21203. }
  21204. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21205. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21206. if (this.onLODLevelSelection) {
  21207. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21208. }
  21209. return this;
  21210. }
  21211. for (var index = 0; index < this._LODLevels.length; index++) {
  21212. var level = this._LODLevels[index];
  21213. if (level.distance < distanceToCamera) {
  21214. if (level.mesh) {
  21215. level.mesh._preActivate();
  21216. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21217. }
  21218. if (this.onLODLevelSelection) {
  21219. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21220. }
  21221. return level.mesh;
  21222. }
  21223. }
  21224. if (this.onLODLevelSelection) {
  21225. this.onLODLevelSelection(distanceToCamera, this, this);
  21226. }
  21227. return this;
  21228. };
  21229. Object.defineProperty(Mesh.prototype, "geometry", {
  21230. /**
  21231. * Returns the mesh internal Geometry object.
  21232. */
  21233. get: function () {
  21234. return this._geometry;
  21235. },
  21236. enumerable: true,
  21237. configurable: true
  21238. });
  21239. /**
  21240. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21241. */
  21242. Mesh.prototype.getTotalVertices = function () {
  21243. if (!this._geometry) {
  21244. return 0;
  21245. }
  21246. return this._geometry.getTotalVertices();
  21247. };
  21248. /**
  21249. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21250. * 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.
  21251. * You can force the copy with forceCopy === true
  21252. * Returns null if the mesh has no geometry or no vertex buffer.
  21253. * Possible `kind` values :
  21254. * - BABYLON.VertexBuffer.PositionKind
  21255. * - BABYLON.VertexBuffer.UVKind
  21256. * - BABYLON.VertexBuffer.UV2Kind
  21257. * - BABYLON.VertexBuffer.UV3Kind
  21258. * - BABYLON.VertexBuffer.UV4Kind
  21259. * - BABYLON.VertexBuffer.UV5Kind
  21260. * - BABYLON.VertexBuffer.UV6Kind
  21261. * - BABYLON.VertexBuffer.ColorKind
  21262. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21263. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21264. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21265. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21266. */
  21267. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21268. if (!this._geometry) {
  21269. return null;
  21270. }
  21271. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21272. };
  21273. /**
  21274. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21275. * Returns `undefined` if the mesh has no geometry.
  21276. * Possible `kind` values :
  21277. * - BABYLON.VertexBuffer.PositionKind
  21278. * - BABYLON.VertexBuffer.UVKind
  21279. * - BABYLON.VertexBuffer.UV2Kind
  21280. * - BABYLON.VertexBuffer.UV3Kind
  21281. * - BABYLON.VertexBuffer.UV4Kind
  21282. * - BABYLON.VertexBuffer.UV5Kind
  21283. * - BABYLON.VertexBuffer.UV6Kind
  21284. * - BABYLON.VertexBuffer.ColorKind
  21285. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21286. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21287. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21288. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21289. */
  21290. Mesh.prototype.getVertexBuffer = function (kind) {
  21291. if (!this._geometry) {
  21292. return undefined;
  21293. }
  21294. return this._geometry.getVertexBuffer(kind);
  21295. };
  21296. /**
  21297. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21298. * Possible `kind` values :
  21299. * - BABYLON.VertexBuffer.PositionKind
  21300. * - BABYLON.VertexBuffer.UVKind
  21301. * - BABYLON.VertexBuffer.UV2Kind
  21302. * - BABYLON.VertexBuffer.UV3Kind
  21303. * - BABYLON.VertexBuffer.UV4Kind
  21304. * - BABYLON.VertexBuffer.UV5Kind
  21305. * - BABYLON.VertexBuffer.UV6Kind
  21306. * - BABYLON.VertexBuffer.ColorKind
  21307. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21308. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21309. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21310. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21311. */
  21312. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21313. if (!this._geometry) {
  21314. if (this._delayInfo) {
  21315. return this._delayInfo.indexOf(kind) !== -1;
  21316. }
  21317. return false;
  21318. }
  21319. return this._geometry.isVerticesDataPresent(kind);
  21320. };
  21321. /**
  21322. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21323. * Possible `kind` values :
  21324. * - BABYLON.VertexBuffer.PositionKind
  21325. * - BABYLON.VertexBuffer.UVKind
  21326. * - BABYLON.VertexBuffer.UV2Kind
  21327. * - BABYLON.VertexBuffer.UV3Kind
  21328. * - BABYLON.VertexBuffer.UV4Kind
  21329. * - BABYLON.VertexBuffer.UV5Kind
  21330. * - BABYLON.VertexBuffer.UV6Kind
  21331. * - BABYLON.VertexBuffer.ColorKind
  21332. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21333. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21334. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21335. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21336. */
  21337. Mesh.prototype.getVerticesDataKinds = function () {
  21338. if (!this._geometry) {
  21339. var result = [];
  21340. if (this._delayInfo) {
  21341. this._delayInfo.forEach(function (kind, index, array) {
  21342. result.push(kind);
  21343. });
  21344. }
  21345. return result;
  21346. }
  21347. return this._geometry.getVerticesDataKinds();
  21348. };
  21349. /**
  21350. * Returns a positive integer : the total number of indices in this mesh geometry.
  21351. * Returns zero if the mesh has no geometry.
  21352. */
  21353. Mesh.prototype.getTotalIndices = function () {
  21354. if (!this._geometry) {
  21355. return 0;
  21356. }
  21357. return this._geometry.getTotalIndices();
  21358. };
  21359. /**
  21360. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21361. * 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.
  21362. * Returns an empty array if the mesh has no geometry.
  21363. */
  21364. Mesh.prototype.getIndices = function (copyWhenShared) {
  21365. if (!this._geometry) {
  21366. return [];
  21367. }
  21368. return this._geometry.getIndices(copyWhenShared);
  21369. };
  21370. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21371. get: function () {
  21372. return this._masterMesh !== null && this._masterMesh !== undefined;
  21373. },
  21374. enumerable: true,
  21375. configurable: true
  21376. });
  21377. /**
  21378. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21379. */
  21380. Mesh.prototype.isReady = function () {
  21381. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21382. return false;
  21383. }
  21384. return _super.prototype.isReady.call(this);
  21385. };
  21386. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21387. get: function () {
  21388. return this._sideOrientation;
  21389. },
  21390. /**
  21391. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21392. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21393. */
  21394. set: function (sideO) {
  21395. this._sideOrientation = sideO;
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21401. /**
  21402. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21403. * This property is pertinent only for updatable parametric shapes.
  21404. */
  21405. get: function () {
  21406. return this._areNormalsFrozen;
  21407. },
  21408. enumerable: true,
  21409. configurable: true
  21410. });
  21411. /**
  21412. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21413. * It has no effect at all on other shapes.
  21414. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21415. * Returns the Mesh.
  21416. */
  21417. Mesh.prototype.freezeNormals = function () {
  21418. this._areNormalsFrozen = true;
  21419. return this;
  21420. };
  21421. /**
  21422. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21423. * It has no effect at all on other shapes.
  21424. * It reactivates the mesh normals computation if it was previously frozen.
  21425. * Returns the Mesh.
  21426. */
  21427. Mesh.prototype.unfreezeNormals = function () {
  21428. this._areNormalsFrozen = false;
  21429. return this;
  21430. };
  21431. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21432. /**
  21433. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21434. */
  21435. set: function (count) {
  21436. this._overridenInstanceCount = count;
  21437. },
  21438. enumerable: true,
  21439. configurable: true
  21440. });
  21441. // Methods
  21442. Mesh.prototype._preActivate = function () {
  21443. var sceneRenderId = this.getScene().getRenderId();
  21444. if (this._preActivateId === sceneRenderId) {
  21445. return this;
  21446. }
  21447. this._preActivateId = sceneRenderId;
  21448. this._visibleInstances = null;
  21449. return this;
  21450. };
  21451. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21452. if (this._visibleInstances) {
  21453. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21454. }
  21455. return this;
  21456. };
  21457. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21458. if (!this._visibleInstances) {
  21459. this._visibleInstances = {};
  21460. this._visibleInstances.defaultRenderId = renderId;
  21461. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21462. }
  21463. if (!this._visibleInstances[renderId]) {
  21464. this._visibleInstances[renderId] = new Array();
  21465. }
  21466. this._visibleInstances[renderId].push(instance);
  21467. return this;
  21468. };
  21469. /**
  21470. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21471. * This means the mesh underlying bounding box and sphere are recomputed.
  21472. * Returns the Mesh.
  21473. */
  21474. Mesh.prototype.refreshBoundingInfo = function () {
  21475. if (this._boundingInfo.isLocked) {
  21476. return;
  21477. }
  21478. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21479. if (data) {
  21480. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21481. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21482. }
  21483. if (this.subMeshes) {
  21484. for (var index = 0; index < this.subMeshes.length; index++) {
  21485. this.subMeshes[index].refreshBoundingInfo();
  21486. }
  21487. }
  21488. this._updateBoundingInfo();
  21489. return this;
  21490. };
  21491. Mesh.prototype._createGlobalSubMesh = function (force) {
  21492. var totalVertices = this.getTotalVertices();
  21493. if (!totalVertices || !this.getIndices()) {
  21494. return null;
  21495. }
  21496. // Check if we need to recreate the submeshes
  21497. if (this.subMeshes && this.subMeshes.length > 0) {
  21498. var totalIndices = this.getIndices().length;
  21499. var needToRecreate = false;
  21500. if (force) {
  21501. needToRecreate = true;
  21502. }
  21503. else {
  21504. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21505. var submesh = _a[_i];
  21506. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21507. needToRecreate = true;
  21508. break;
  21509. }
  21510. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21511. needToRecreate = true;
  21512. break;
  21513. }
  21514. }
  21515. }
  21516. if (!needToRecreate) {
  21517. return;
  21518. }
  21519. }
  21520. this.releaseSubMeshes();
  21521. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21522. };
  21523. Mesh.prototype.subdivide = function (count) {
  21524. if (count < 1) {
  21525. return;
  21526. }
  21527. var totalIndices = this.getTotalIndices();
  21528. var subdivisionSize = (totalIndices / count) | 0;
  21529. var offset = 0;
  21530. // Ensure that subdivisionSize is a multiple of 3
  21531. while (subdivisionSize % 3 !== 0) {
  21532. subdivisionSize++;
  21533. }
  21534. this.releaseSubMeshes();
  21535. for (var index = 0; index < count; index++) {
  21536. if (offset >= totalIndices) {
  21537. break;
  21538. }
  21539. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21540. offset += subdivisionSize;
  21541. }
  21542. this.synchronizeInstances();
  21543. };
  21544. /**
  21545. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21546. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21547. * The `data` are either a numeric array either a Float32Array.
  21548. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21549. * 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).
  21550. * Note that a new underlying VertexBuffer object is created each call.
  21551. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21552. *
  21553. * Possible `kind` values :
  21554. * - BABYLON.VertexBuffer.PositionKind
  21555. * - BABYLON.VertexBuffer.UVKind
  21556. * - BABYLON.VertexBuffer.UV2Kind
  21557. * - BABYLON.VertexBuffer.UV3Kind
  21558. * - BABYLON.VertexBuffer.UV4Kind
  21559. * - BABYLON.VertexBuffer.UV5Kind
  21560. * - BABYLON.VertexBuffer.UV6Kind
  21561. * - BABYLON.VertexBuffer.ColorKind
  21562. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21563. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21564. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21565. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21566. *
  21567. * Returns the Mesh.
  21568. */
  21569. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21570. if (!this._geometry) {
  21571. var vertexData = new BABYLON.VertexData();
  21572. vertexData.set(data, kind);
  21573. var scene = this.getScene();
  21574. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21575. }
  21576. else {
  21577. this._geometry.setVerticesData(kind, data, updatable, stride);
  21578. }
  21579. return this;
  21580. };
  21581. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21582. if (updatable === void 0) { updatable = true; }
  21583. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21584. return;
  21585. }
  21586. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21587. };
  21588. /**
  21589. * Sets the mesh VertexBuffer.
  21590. * Returns the Mesh.
  21591. */
  21592. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21593. if (!this._geometry) {
  21594. var scene = this.getScene();
  21595. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21596. }
  21597. this._geometry.setVerticesBuffer(buffer);
  21598. return this;
  21599. };
  21600. /**
  21601. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21602. * If the mesh has no geometry, it is simply returned as it is.
  21603. * The `data` are either a numeric array either a Float32Array.
  21604. * No new underlying VertexBuffer object is created.
  21605. * 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.
  21606. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21607. *
  21608. * Possible `kind` values :
  21609. * - BABYLON.VertexBuffer.PositionKind
  21610. * - BABYLON.VertexBuffer.UVKind
  21611. * - BABYLON.VertexBuffer.UV2Kind
  21612. * - BABYLON.VertexBuffer.UV3Kind
  21613. * - BABYLON.VertexBuffer.UV4Kind
  21614. * - BABYLON.VertexBuffer.UV5Kind
  21615. * - BABYLON.VertexBuffer.UV6Kind
  21616. * - BABYLON.VertexBuffer.ColorKind
  21617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21621. *
  21622. * Returns the Mesh.
  21623. */
  21624. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21625. if (!this._geometry) {
  21626. return;
  21627. }
  21628. if (!makeItUnique) {
  21629. this._geometry.updateVerticesData(kind, data, updateExtends);
  21630. }
  21631. else {
  21632. this.makeGeometryUnique();
  21633. this.updateVerticesData(kind, data, updateExtends, false);
  21634. }
  21635. return this;
  21636. };
  21637. /**
  21638. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21639. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21640. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21641. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21642. * Returns the Mesh.
  21643. */
  21644. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21645. if (computeNormals === void 0) { computeNormals = true; }
  21646. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21647. positionFunction(positions);
  21648. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21649. if (computeNormals) {
  21650. var indices = this.getIndices();
  21651. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21652. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21653. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21654. }
  21655. return this;
  21656. };
  21657. /**
  21658. * Creates a un-shared specific occurence of the geometry for the mesh.
  21659. * Returns the Mesh.
  21660. */
  21661. Mesh.prototype.makeGeometryUnique = function () {
  21662. if (!this._geometry) {
  21663. return;
  21664. }
  21665. var oldGeometry = this._geometry;
  21666. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21667. oldGeometry.releaseForMesh(this, true);
  21668. geometry.applyToMesh(this);
  21669. return this;
  21670. };
  21671. /**
  21672. * Sets the mesh indices.
  21673. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21674. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21675. * This method creates a new index buffer each call.
  21676. * Returns the Mesh.
  21677. */
  21678. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21679. if (!this._geometry) {
  21680. var vertexData = new BABYLON.VertexData();
  21681. vertexData.indices = indices;
  21682. var scene = this.getScene();
  21683. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21684. }
  21685. else {
  21686. this._geometry.setIndices(indices, totalVertices);
  21687. }
  21688. return this;
  21689. };
  21690. /**
  21691. * Invert the geometry to move from a right handed system to a left handed one.
  21692. * Returns the Mesh.
  21693. */
  21694. Mesh.prototype.toLeftHanded = function () {
  21695. if (!this._geometry) {
  21696. return;
  21697. }
  21698. this._geometry.toLeftHanded();
  21699. return this;
  21700. };
  21701. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21702. var engine = this.getScene().getEngine();
  21703. // Wireframe
  21704. var indexToBind;
  21705. if (this._unIndexed) {
  21706. indexToBind = null;
  21707. }
  21708. else {
  21709. switch (fillMode) {
  21710. case BABYLON.Material.PointFillMode:
  21711. indexToBind = null;
  21712. break;
  21713. case BABYLON.Material.WireFrameFillMode:
  21714. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21715. break;
  21716. default:
  21717. case BABYLON.Material.TriangleFillMode:
  21718. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21719. break;
  21720. }
  21721. }
  21722. // VBOs
  21723. this._geometry._bind(effect, indexToBind);
  21724. return this;
  21725. };
  21726. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21727. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21728. return this;
  21729. }
  21730. this.onBeforeDrawObservable.notifyObservers(this);
  21731. var engine = this.getScene().getEngine();
  21732. // Draw order
  21733. switch (fillMode) {
  21734. case BABYLON.Material.PointFillMode:
  21735. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21736. break;
  21737. case BABYLON.Material.WireFrameFillMode:
  21738. if (this._unIndexed) {
  21739. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21740. }
  21741. else {
  21742. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21743. }
  21744. break;
  21745. default:
  21746. if (this._unIndexed) {
  21747. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21748. }
  21749. else {
  21750. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21751. }
  21752. }
  21753. return this;
  21754. };
  21755. /**
  21756. * Registers for this mesh a javascript function called just before the rendering process.
  21757. * This function is passed the current mesh.
  21758. * Return the Mesh.
  21759. */
  21760. Mesh.prototype.registerBeforeRender = function (func) {
  21761. this.onBeforeRenderObservable.add(func);
  21762. return this;
  21763. };
  21764. /**
  21765. * Disposes a previously registered javascript function called before the rendering.
  21766. * This function is passed the current mesh.
  21767. * Returns the Mesh.
  21768. */
  21769. Mesh.prototype.unregisterBeforeRender = function (func) {
  21770. this.onBeforeRenderObservable.removeCallback(func);
  21771. return this;
  21772. };
  21773. /**
  21774. * Registers for this mesh a javascript function called just after the rendering is complete.
  21775. * This function is passed the current mesh.
  21776. * Returns the Mesh.
  21777. */
  21778. Mesh.prototype.registerAfterRender = function (func) {
  21779. this.onAfterRenderObservable.add(func);
  21780. return this;
  21781. };
  21782. /**
  21783. * Disposes a previously registered javascript function called after the rendering.
  21784. * This function is passed the current mesh.
  21785. * Return the Mesh.
  21786. */
  21787. Mesh.prototype.unregisterAfterRender = function (func) {
  21788. this.onAfterRenderObservable.removeCallback(func);
  21789. return this;
  21790. };
  21791. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21792. var scene = this.getScene();
  21793. this._batchCache.mustReturn = false;
  21794. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21795. this._batchCache.visibleInstances[subMeshId] = null;
  21796. if (this._visibleInstances) {
  21797. var currentRenderId = scene.getRenderId();
  21798. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21799. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21800. var selfRenderId = this._renderId;
  21801. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21802. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21803. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21804. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21805. }
  21806. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21807. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21808. this._batchCache.mustReturn = true;
  21809. return this._batchCache;
  21810. }
  21811. if (currentRenderId !== selfRenderId) {
  21812. this._batchCache.renderSelf[subMeshId] = false;
  21813. }
  21814. }
  21815. this._renderIdForInstances[subMeshId] = currentRenderId;
  21816. }
  21817. return this._batchCache;
  21818. };
  21819. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21820. var visibleInstances = batch.visibleInstances[subMesh._id];
  21821. var matricesCount = visibleInstances.length + 1;
  21822. var bufferSize = matricesCount * 16 * 4;
  21823. var currentInstancesBufferSize = this._instancesBufferSize;
  21824. var instancesBuffer = this._instancesBuffer;
  21825. while (this._instancesBufferSize < bufferSize) {
  21826. this._instancesBufferSize *= 2;
  21827. }
  21828. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21829. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21830. }
  21831. var offset = 0;
  21832. var instancesCount = 0;
  21833. var world = this.getWorldMatrix();
  21834. if (batch.renderSelf[subMesh._id]) {
  21835. world.copyToArray(this._instancesData, offset);
  21836. offset += 16;
  21837. instancesCount++;
  21838. }
  21839. if (visibleInstances) {
  21840. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21841. var instance = visibleInstances[instanceIndex];
  21842. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21843. offset += 16;
  21844. instancesCount++;
  21845. }
  21846. }
  21847. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21848. if (instancesBuffer) {
  21849. instancesBuffer.dispose();
  21850. }
  21851. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21852. this._instancesBuffer = instancesBuffer;
  21853. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21854. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21855. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21856. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21857. }
  21858. else {
  21859. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21860. }
  21861. this._bind(subMesh, effect, fillMode);
  21862. this._draw(subMesh, fillMode, instancesCount);
  21863. engine.unbindInstanceAttributes();
  21864. return this;
  21865. };
  21866. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21867. var scene = this.getScene();
  21868. var engine = scene.getEngine();
  21869. if (hardwareInstancedRendering) {
  21870. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21871. }
  21872. else {
  21873. if (batch.renderSelf[subMesh._id]) {
  21874. // Draw
  21875. if (onBeforeDraw) {
  21876. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21877. }
  21878. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21879. }
  21880. if (batch.visibleInstances[subMesh._id]) {
  21881. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21882. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21883. // World
  21884. var world = instance.getWorldMatrix();
  21885. if (onBeforeDraw) {
  21886. onBeforeDraw(true, world, effectiveMaterial);
  21887. }
  21888. // Draw
  21889. this._draw(subMesh, fillMode);
  21890. }
  21891. }
  21892. }
  21893. return this;
  21894. };
  21895. /**
  21896. * Triggers the draw call for the mesh.
  21897. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21898. * Returns the Mesh.
  21899. */
  21900. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21901. this.checkOcclusionQuery();
  21902. if (this._isOccluded) {
  21903. return;
  21904. }
  21905. var scene = this.getScene();
  21906. // Managing instances
  21907. var batch = this._getInstancesRenderList(subMesh._id);
  21908. if (batch.mustReturn) {
  21909. return this;
  21910. }
  21911. // Checking geometry state
  21912. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21913. return this;
  21914. }
  21915. var callbackIndex;
  21916. this.onBeforeRenderObservable.notifyObservers(this);
  21917. var engine = scene.getEngine();
  21918. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21919. // Material
  21920. var effectiveMaterial = subMesh.getMaterial();
  21921. if (!effectiveMaterial) {
  21922. return this;
  21923. }
  21924. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21925. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21926. return this;
  21927. }
  21928. }
  21929. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21930. return this;
  21931. }
  21932. // Alpha mode
  21933. if (enableAlphaMode) {
  21934. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21935. }
  21936. // Outline - step 1
  21937. var savedDepthWrite = engine.getDepthWrite();
  21938. if (this.renderOutline) {
  21939. engine.setDepthWrite(false);
  21940. scene.getOutlineRenderer().render(subMesh, batch);
  21941. engine.setDepthWrite(savedDepthWrite);
  21942. }
  21943. var effect;
  21944. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21945. effect = subMesh.effect;
  21946. }
  21947. else {
  21948. effect = effectiveMaterial.getEffect();
  21949. }
  21950. effectiveMaterial._preBind(effect);
  21951. // Bind
  21952. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21953. if (!hardwareInstancedRendering) {
  21954. this._bind(subMesh, effect, fillMode);
  21955. }
  21956. var world = this.getWorldMatrix();
  21957. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21958. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21959. }
  21960. else {
  21961. effectiveMaterial.bind(world, this);
  21962. }
  21963. // Draw
  21964. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21965. // Unbind
  21966. effectiveMaterial.unbind();
  21967. // Outline - step 2
  21968. if (this.renderOutline && savedDepthWrite) {
  21969. engine.setDepthWrite(true);
  21970. engine.setColorWrite(false);
  21971. scene.getOutlineRenderer().render(subMesh, batch);
  21972. engine.setColorWrite(true);
  21973. }
  21974. // Overlay
  21975. if (this.renderOverlay) {
  21976. var currentMode = engine.getAlphaMode();
  21977. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21978. scene.getOutlineRenderer().render(subMesh, batch, true);
  21979. engine.setAlphaMode(currentMode);
  21980. }
  21981. this.onAfterRenderObservable.notifyObservers(this);
  21982. return this;
  21983. };
  21984. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21985. if (isInstance) {
  21986. effectiveMaterial.bindOnlyWorldMatrix(world);
  21987. }
  21988. return this;
  21989. };
  21990. /**
  21991. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21992. */
  21993. Mesh.prototype.getEmittedParticleSystems = function () {
  21994. var results = new Array();
  21995. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21996. var particleSystem = this.getScene().particleSystems[index];
  21997. if (particleSystem.emitter === this) {
  21998. results.push(particleSystem);
  21999. }
  22000. }
  22001. return results;
  22002. };
  22003. /**
  22004. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22005. */
  22006. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22007. var results = new Array();
  22008. var descendants = this.getDescendants();
  22009. descendants.push(this);
  22010. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22011. var particleSystem = this.getScene().particleSystems[index];
  22012. var emitter = particleSystem.emitter;
  22013. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22014. results.push(particleSystem);
  22015. }
  22016. }
  22017. return results;
  22018. };
  22019. Mesh.prototype._checkDelayState = function () {
  22020. var scene = this.getScene();
  22021. if (this._geometry) {
  22022. this._geometry.load(scene);
  22023. }
  22024. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22025. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22026. this._queueLoad(this, scene);
  22027. }
  22028. return this;
  22029. };
  22030. Mesh.prototype._queueLoad = function (mesh, scene) {
  22031. var _this = this;
  22032. scene._addPendingData(mesh);
  22033. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22034. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22035. if (data instanceof ArrayBuffer) {
  22036. _this._delayLoadingFunction(data, _this);
  22037. }
  22038. else {
  22039. _this._delayLoadingFunction(JSON.parse(data), _this);
  22040. }
  22041. _this.instances.forEach(function (instance) {
  22042. instance._syncSubMeshes();
  22043. });
  22044. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22045. scene._removePendingData(_this);
  22046. }, function () { }, scene.database, getBinaryData);
  22047. return this;
  22048. };
  22049. /**
  22050. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22051. */
  22052. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22053. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22054. return false;
  22055. }
  22056. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22057. return false;
  22058. }
  22059. this._checkDelayState();
  22060. return true;
  22061. };
  22062. /**
  22063. * Sets the mesh material by the material or multiMaterial `id` property.
  22064. * The material `id` is a string identifying the material or the multiMaterial.
  22065. * This method returns the Mesh.
  22066. */
  22067. Mesh.prototype.setMaterialByID = function (id) {
  22068. var materials = this.getScene().materials;
  22069. var index;
  22070. for (index = materials.length - 1; index > -1; index--) {
  22071. if (materials[index].id === id) {
  22072. this.material = materials[index];
  22073. return this;
  22074. }
  22075. }
  22076. // Multi
  22077. var multiMaterials = this.getScene().multiMaterials;
  22078. for (index = multiMaterials.length - 1; index > -1; index--) {
  22079. if (multiMaterials[index].id === id) {
  22080. this.material = multiMaterials[index];
  22081. return this;
  22082. }
  22083. }
  22084. return this;
  22085. };
  22086. /**
  22087. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22088. */
  22089. Mesh.prototype.getAnimatables = function () {
  22090. var results = [];
  22091. if (this.material) {
  22092. results.push(this.material);
  22093. }
  22094. if (this.skeleton) {
  22095. results.push(this.skeleton);
  22096. }
  22097. return results;
  22098. };
  22099. /**
  22100. * Modifies the mesh geometry according to the passed transformation matrix.
  22101. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22102. * The mesh normals are modified accordingly the same transformation.
  22103. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22104. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22105. * Returns the Mesh.
  22106. */
  22107. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22108. // Position
  22109. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22110. return this;
  22111. }
  22112. var submeshes = this.subMeshes.splice(0);
  22113. this._resetPointsArrayCache();
  22114. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22115. var temp = [];
  22116. var index;
  22117. for (index = 0; index < data.length; index += 3) {
  22118. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22119. }
  22120. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22121. // Normals
  22122. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22123. return this;
  22124. }
  22125. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22126. temp = [];
  22127. for (index = 0; index < data.length; index += 3) {
  22128. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22129. }
  22130. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22131. // flip faces?
  22132. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22133. this.flipFaces();
  22134. }
  22135. // Restore submeshes
  22136. this.releaseSubMeshes();
  22137. this.subMeshes = submeshes;
  22138. return this;
  22139. };
  22140. /**
  22141. * Modifies the mesh geometry according to its own current World Matrix.
  22142. * The mesh World Matrix is then reset.
  22143. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22144. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22145. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22146. * Returns the Mesh.
  22147. */
  22148. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22149. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22150. this.scaling.copyFromFloats(1, 1, 1);
  22151. this.position.copyFromFloats(0, 0, 0);
  22152. this.rotation.copyFromFloats(0, 0, 0);
  22153. //only if quaternion is already set
  22154. if (this.rotationQuaternion) {
  22155. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22156. }
  22157. this._worldMatrix = BABYLON.Matrix.Identity();
  22158. return this;
  22159. };
  22160. Object.defineProperty(Mesh.prototype, "_positions", {
  22161. // Cache
  22162. get: function () {
  22163. if (this._geometry) {
  22164. return this._geometry._positions;
  22165. }
  22166. return null;
  22167. },
  22168. enumerable: true,
  22169. configurable: true
  22170. });
  22171. Mesh.prototype._resetPointsArrayCache = function () {
  22172. if (this._geometry) {
  22173. this._geometry._resetPointsArrayCache();
  22174. }
  22175. return this;
  22176. };
  22177. Mesh.prototype._generatePointsArray = function () {
  22178. if (this._geometry) {
  22179. return this._geometry._generatePointsArray();
  22180. }
  22181. return false;
  22182. };
  22183. /**
  22184. * Returns a new Mesh object generated from the current mesh properties.
  22185. * This method must not get confused with createInstance().
  22186. * The parameter `name` is a string, the name given to the new mesh.
  22187. * The optional parameter `newParent` can be any Node object (default `null`).
  22188. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22189. * 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.
  22190. */
  22191. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22192. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22193. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22194. };
  22195. /**
  22196. * Disposes the mesh.
  22197. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22198. */
  22199. Mesh.prototype.dispose = function (doNotRecurse) {
  22200. var _this = this;
  22201. this.morphTargetManager = undefined;
  22202. if (this._geometry) {
  22203. this._geometry.releaseForMesh(this, true);
  22204. }
  22205. // Sources
  22206. var meshes = this.getScene().meshes;
  22207. meshes.forEach(function (mesh) {
  22208. if (mesh._source && mesh._source === _this) {
  22209. mesh._source = null;
  22210. }
  22211. });
  22212. this._source = null;
  22213. // Instances
  22214. if (this._instancesBuffer) {
  22215. this._instancesBuffer.dispose();
  22216. this._instancesBuffer = null;
  22217. }
  22218. while (this.instances.length) {
  22219. this.instances[0].dispose();
  22220. }
  22221. // Highlight layers.
  22222. var highlightLayers = this.getScene().highlightLayers;
  22223. for (var i = 0; i < highlightLayers.length; i++) {
  22224. var highlightLayer = highlightLayers[i];
  22225. if (highlightLayer) {
  22226. highlightLayer.removeMesh(this);
  22227. highlightLayer.removeExcludedMesh(this);
  22228. }
  22229. }
  22230. _super.prototype.dispose.call(this, doNotRecurse);
  22231. };
  22232. /**
  22233. * Modifies the mesh geometry according to a displacement map.
  22234. * 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.
  22235. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22236. * This method returns nothing.
  22237. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22238. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22239. * 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.
  22240. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22241. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22242. *
  22243. * Returns the Mesh.
  22244. */
  22245. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22246. var _this = this;
  22247. var scene = this.getScene();
  22248. var onload = function (img) {
  22249. // Getting height map data
  22250. var canvas = document.createElement("canvas");
  22251. var context = canvas.getContext("2d");
  22252. var heightMapWidth = img.width;
  22253. var heightMapHeight = img.height;
  22254. canvas.width = heightMapWidth;
  22255. canvas.height = heightMapHeight;
  22256. context.drawImage(img, 0, 0);
  22257. // Create VertexData from map data
  22258. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22259. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22260. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22261. //execute success callback, if set
  22262. if (onSuccess) {
  22263. onSuccess(_this);
  22264. }
  22265. };
  22266. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22267. return this;
  22268. };
  22269. /**
  22270. * Modifies the mesh geometry according to a displacementMap buffer.
  22271. * 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.
  22272. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22273. * This method returns nothing.
  22274. * 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.
  22275. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22276. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22277. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22278. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22279. *
  22280. * Returns the Mesh.
  22281. */
  22282. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22283. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22284. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22285. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22286. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22287. return this;
  22288. }
  22289. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22290. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22291. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22292. var position = BABYLON.Vector3.Zero();
  22293. var normal = BABYLON.Vector3.Zero();
  22294. var uv = BABYLON.Vector2.Zero();
  22295. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22296. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22297. for (var index = 0; index < positions.length; index += 3) {
  22298. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22299. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22300. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22301. // Compute height
  22302. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22303. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22304. var pos = (u + v * heightMapWidth) * 4;
  22305. var r = buffer[pos] / 255.0;
  22306. var g = buffer[pos + 1] / 255.0;
  22307. var b = buffer[pos + 2] / 255.0;
  22308. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22309. normal.normalize();
  22310. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22311. position = position.add(normal);
  22312. position.toArray(positions, index);
  22313. }
  22314. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22315. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22316. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22317. return this;
  22318. };
  22319. /**
  22320. * Modify the mesh to get a flat shading rendering.
  22321. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22322. * This method returns the Mesh.
  22323. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22324. */
  22325. Mesh.prototype.convertToFlatShadedMesh = function () {
  22326. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22327. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22328. var kinds = this.getVerticesDataKinds();
  22329. var vbs = [];
  22330. var data = [];
  22331. var newdata = [];
  22332. var updatableNormals = false;
  22333. var kindIndex;
  22334. var kind;
  22335. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22336. kind = kinds[kindIndex];
  22337. var vertexBuffer = this.getVertexBuffer(kind);
  22338. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22339. updatableNormals = vertexBuffer.isUpdatable();
  22340. kinds.splice(kindIndex, 1);
  22341. kindIndex--;
  22342. continue;
  22343. }
  22344. vbs[kind] = vertexBuffer;
  22345. data[kind] = vbs[kind].getData();
  22346. newdata[kind] = [];
  22347. }
  22348. // Save previous submeshes
  22349. var previousSubmeshes = this.subMeshes.slice(0);
  22350. var indices = this.getIndices();
  22351. var totalIndices = this.getTotalIndices();
  22352. // Generating unique vertices per face
  22353. var index;
  22354. for (index = 0; index < totalIndices; index++) {
  22355. var vertexIndex = indices[index];
  22356. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22357. kind = kinds[kindIndex];
  22358. var stride = vbs[kind].getStrideSize();
  22359. for (var offset = 0; offset < stride; offset++) {
  22360. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22361. }
  22362. }
  22363. }
  22364. // Updating faces & normal
  22365. var normals = [];
  22366. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22367. for (index = 0; index < totalIndices; index += 3) {
  22368. indices[index] = index;
  22369. indices[index + 1] = index + 1;
  22370. indices[index + 2] = index + 2;
  22371. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22372. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22373. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22374. var p1p2 = p1.subtract(p2);
  22375. var p3p2 = p3.subtract(p2);
  22376. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22377. // Store same normals for every vertex
  22378. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22379. normals.push(normal.x);
  22380. normals.push(normal.y);
  22381. normals.push(normal.z);
  22382. }
  22383. }
  22384. this.setIndices(indices);
  22385. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22386. // Updating vertex buffers
  22387. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22388. kind = kinds[kindIndex];
  22389. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22390. }
  22391. // Updating submeshes
  22392. this.releaseSubMeshes();
  22393. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22394. var previousOne = previousSubmeshes[submeshIndex];
  22395. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22396. }
  22397. this.synchronizeInstances();
  22398. return this;
  22399. };
  22400. /**
  22401. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22402. * In other words, more vertices, no more indices and a single bigger VBO.
  22403. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22404. * Returns the Mesh.
  22405. */
  22406. Mesh.prototype.convertToUnIndexedMesh = function () {
  22407. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22408. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22409. var kinds = this.getVerticesDataKinds();
  22410. var vbs = [];
  22411. var data = [];
  22412. var newdata = [];
  22413. var updatableNormals = false;
  22414. var kindIndex;
  22415. var kind;
  22416. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22417. kind = kinds[kindIndex];
  22418. var vertexBuffer = this.getVertexBuffer(kind);
  22419. vbs[kind] = vertexBuffer;
  22420. data[kind] = vbs[kind].getData();
  22421. newdata[kind] = [];
  22422. }
  22423. // Save previous submeshes
  22424. var previousSubmeshes = this.subMeshes.slice(0);
  22425. var indices = this.getIndices();
  22426. var totalIndices = this.getTotalIndices();
  22427. // Generating unique vertices per face
  22428. var index;
  22429. for (index = 0; index < totalIndices; index++) {
  22430. var vertexIndex = indices[index];
  22431. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22432. kind = kinds[kindIndex];
  22433. var stride = vbs[kind].getStrideSize();
  22434. for (var offset = 0; offset < stride; offset++) {
  22435. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22436. }
  22437. }
  22438. }
  22439. // Updating indices
  22440. for (index = 0; index < totalIndices; index += 3) {
  22441. indices[index] = index;
  22442. indices[index + 1] = index + 1;
  22443. indices[index + 2] = index + 2;
  22444. }
  22445. this.setIndices(indices);
  22446. // Updating vertex buffers
  22447. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22448. kind = kinds[kindIndex];
  22449. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22450. }
  22451. // Updating submeshes
  22452. this.releaseSubMeshes();
  22453. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22454. var previousOne = previousSubmeshes[submeshIndex];
  22455. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22456. }
  22457. this._unIndexed = true;
  22458. this.synchronizeInstances();
  22459. return this;
  22460. };
  22461. /**
  22462. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22463. * This method returns the Mesh.
  22464. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22465. */
  22466. Mesh.prototype.flipFaces = function (flipNormals) {
  22467. if (flipNormals === void 0) { flipNormals = false; }
  22468. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22469. var i;
  22470. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22471. for (i = 0; i < vertex_data.normals.length; i++) {
  22472. vertex_data.normals[i] *= -1;
  22473. }
  22474. }
  22475. var temp;
  22476. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22477. // reassign indices
  22478. temp = vertex_data.indices[i + 1];
  22479. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22480. vertex_data.indices[i + 2] = temp;
  22481. }
  22482. vertex_data.applyToMesh(this);
  22483. return this;
  22484. };
  22485. // Instances
  22486. /**
  22487. * Creates a new InstancedMesh object from the mesh model.
  22488. * An instance shares the same properties and the same material than its model.
  22489. * Only these properties of each instance can then be set individually :
  22490. * - position
  22491. * - rotation
  22492. * - rotationQuaternion
  22493. * - setPivotMatrix
  22494. * - scaling
  22495. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22496. * Warning : this method is not supported for Line mesh and LineSystem
  22497. */
  22498. Mesh.prototype.createInstance = function (name) {
  22499. return new BABYLON.InstancedMesh(name, this);
  22500. };
  22501. /**
  22502. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22503. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22504. * This method returns the Mesh.
  22505. */
  22506. Mesh.prototype.synchronizeInstances = function () {
  22507. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22508. var instance = this.instances[instanceIndex];
  22509. instance._syncSubMeshes();
  22510. }
  22511. return this;
  22512. };
  22513. /**
  22514. * Simplify the mesh according to the given array of settings.
  22515. * Function will return immediately and will simplify async. It returns the Mesh.
  22516. * @param settings a collection of simplification settings.
  22517. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22518. * @param type the type of simplification to run.
  22519. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22520. */
  22521. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22522. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22523. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22524. this.getScene().simplificationQueue.addTask({
  22525. settings: settings,
  22526. parallelProcessing: parallelProcessing,
  22527. mesh: this,
  22528. simplificationType: simplificationType,
  22529. successCallback: successCallback
  22530. });
  22531. return this;
  22532. };
  22533. /**
  22534. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22535. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22536. * This should be used together with the simplification to avoid disappearing triangles.
  22537. * Returns the Mesh.
  22538. * @param successCallback an optional success callback to be called after the optimization finished.
  22539. */
  22540. Mesh.prototype.optimizeIndices = function (successCallback) {
  22541. var _this = this;
  22542. var indices = this.getIndices();
  22543. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22544. var vectorPositions = [];
  22545. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22546. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22547. }
  22548. var dupes = [];
  22549. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22550. var realPos = vectorPositions.length - 1 - iteration;
  22551. var testedPosition = vectorPositions[realPos];
  22552. for (var j = 0; j < realPos; ++j) {
  22553. var againstPosition = vectorPositions[j];
  22554. if (testedPosition.equals(againstPosition)) {
  22555. dupes[realPos] = j;
  22556. break;
  22557. }
  22558. }
  22559. }, function () {
  22560. for (var i = 0; i < indices.length; ++i) {
  22561. indices[i] = dupes[indices[i]] || indices[i];
  22562. }
  22563. //indices are now reordered
  22564. var originalSubMeshes = _this.subMeshes.slice(0);
  22565. _this.setIndices(indices);
  22566. _this.subMeshes = originalSubMeshes;
  22567. if (successCallback) {
  22568. successCallback(_this);
  22569. }
  22570. });
  22571. return this;
  22572. };
  22573. Mesh.prototype.serialize = function (serializationObject) {
  22574. serializationObject.name = this.name;
  22575. serializationObject.id = this.id;
  22576. serializationObject.type = this.getClassName();
  22577. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22578. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22579. }
  22580. serializationObject.position = this.position.asArray();
  22581. if (this.rotationQuaternion) {
  22582. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22583. }
  22584. else if (this.rotation) {
  22585. serializationObject.rotation = this.rotation.asArray();
  22586. }
  22587. serializationObject.scaling = this.scaling.asArray();
  22588. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22589. serializationObject.isEnabled = this.isEnabled();
  22590. serializationObject.isVisible = this.isVisible;
  22591. serializationObject.infiniteDistance = this.infiniteDistance;
  22592. serializationObject.pickable = this.isPickable;
  22593. serializationObject.receiveShadows = this.receiveShadows;
  22594. serializationObject.billboardMode = this.billboardMode;
  22595. serializationObject.visibility = this.visibility;
  22596. serializationObject.checkCollisions = this.checkCollisions;
  22597. serializationObject.isBlocker = this.isBlocker;
  22598. // Parent
  22599. if (this.parent) {
  22600. serializationObject.parentId = this.parent.id;
  22601. }
  22602. // Geometry
  22603. var geometry = this._geometry;
  22604. if (geometry) {
  22605. var geometryId = geometry.id;
  22606. serializationObject.geometryId = geometryId;
  22607. // SubMeshes
  22608. serializationObject.subMeshes = [];
  22609. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22610. var subMesh = this.subMeshes[subIndex];
  22611. serializationObject.subMeshes.push({
  22612. materialIndex: subMesh.materialIndex,
  22613. verticesStart: subMesh.verticesStart,
  22614. verticesCount: subMesh.verticesCount,
  22615. indexStart: subMesh.indexStart,
  22616. indexCount: subMesh.indexCount
  22617. });
  22618. }
  22619. }
  22620. // Material
  22621. if (this.material) {
  22622. serializationObject.materialId = this.material.id;
  22623. }
  22624. else {
  22625. this.material = null;
  22626. }
  22627. // Morph targets
  22628. if (this.morphTargetManager) {
  22629. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22630. }
  22631. // Skeleton
  22632. if (this.skeleton) {
  22633. serializationObject.skeletonId = this.skeleton.id;
  22634. }
  22635. // Physics
  22636. //TODO implement correct serialization for physics impostors.
  22637. if (this.getPhysicsImpostor()) {
  22638. var impostor = this.getPhysicsImpostor();
  22639. serializationObject.physicsMass = impostor.getParam("mass");
  22640. serializationObject.physicsFriction = impostor.getParam("friction");
  22641. serializationObject.physicsRestitution = impostor.getParam("mass");
  22642. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22643. }
  22644. // Metadata
  22645. if (this.metadata) {
  22646. serializationObject.metadata = this.metadata;
  22647. }
  22648. // Instances
  22649. serializationObject.instances = [];
  22650. for (var index = 0; index < this.instances.length; index++) {
  22651. var instance = this.instances[index];
  22652. var serializationInstance = {
  22653. name: instance.name,
  22654. position: instance.position.asArray(),
  22655. scaling: instance.scaling.asArray()
  22656. };
  22657. if (instance.rotationQuaternion) {
  22658. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22659. }
  22660. else if (instance.rotation) {
  22661. serializationInstance.rotation = instance.rotation.asArray();
  22662. }
  22663. serializationObject.instances.push(serializationInstance);
  22664. // Animations
  22665. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22666. serializationInstance.ranges = instance.serializeAnimationRanges();
  22667. }
  22668. //
  22669. // Animations
  22670. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22671. serializationObject.ranges = this.serializeAnimationRanges();
  22672. // Layer mask
  22673. serializationObject.layerMask = this.layerMask;
  22674. // Alpha
  22675. serializationObject.alphaIndex = this.alphaIndex;
  22676. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22677. // Overlay
  22678. serializationObject.overlayAlpha = this.overlayAlpha;
  22679. serializationObject.overlayColor = this.overlayColor.asArray();
  22680. serializationObject.renderOverlay = this.renderOverlay;
  22681. // Fog
  22682. serializationObject.applyFog = this.applyFog;
  22683. // Action Manager
  22684. if (this.actionManager) {
  22685. serializationObject.actions = this.actionManager.serialize(this.name);
  22686. }
  22687. };
  22688. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22689. if (!this.geometry) {
  22690. return;
  22691. }
  22692. this._markSubMeshesAsAttributesDirty();
  22693. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22694. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22695. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22696. this.morphTargetManager = undefined;
  22697. return;
  22698. }
  22699. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22700. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22701. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22702. if (morphTarget.hasNormals) {
  22703. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22704. }
  22705. if (morphTarget.hasTangents) {
  22706. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22707. }
  22708. }
  22709. }
  22710. else {
  22711. var index = 0;
  22712. // Positions
  22713. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22714. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22715. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22716. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22717. }
  22718. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22719. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22720. }
  22721. index++;
  22722. }
  22723. }
  22724. };
  22725. // Statics
  22726. /**
  22727. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22728. * The parameter `parsedMesh` is the mesh to be copied.
  22729. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22730. */
  22731. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22732. var mesh;
  22733. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22734. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22735. }
  22736. else {
  22737. mesh = new Mesh(parsedMesh.name, scene);
  22738. }
  22739. mesh.id = parsedMesh.id;
  22740. if (BABYLON.Tags) {
  22741. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22742. }
  22743. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22744. if (parsedMesh.metadata !== undefined) {
  22745. mesh.metadata = parsedMesh.metadata;
  22746. }
  22747. if (parsedMesh.rotationQuaternion) {
  22748. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22749. }
  22750. else if (parsedMesh.rotation) {
  22751. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22752. }
  22753. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22754. if (parsedMesh.localMatrix) {
  22755. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22756. }
  22757. else if (parsedMesh.pivotMatrix) {
  22758. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22759. }
  22760. mesh.setEnabled(parsedMesh.isEnabled);
  22761. mesh.isVisible = parsedMesh.isVisible;
  22762. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22763. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22764. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22765. if (parsedMesh.applyFog !== undefined) {
  22766. mesh.applyFog = parsedMesh.applyFog;
  22767. }
  22768. if (parsedMesh.pickable !== undefined) {
  22769. mesh.isPickable = parsedMesh.pickable;
  22770. }
  22771. if (parsedMesh.alphaIndex !== undefined) {
  22772. mesh.alphaIndex = parsedMesh.alphaIndex;
  22773. }
  22774. mesh.receiveShadows = parsedMesh.receiveShadows;
  22775. mesh.billboardMode = parsedMesh.billboardMode;
  22776. if (parsedMesh.visibility !== undefined) {
  22777. mesh.visibility = parsedMesh.visibility;
  22778. }
  22779. mesh.checkCollisions = parsedMesh.checkCollisions;
  22780. if (parsedMesh.isBlocker !== undefined) {
  22781. mesh.isBlocker = parsedMesh.isBlocker;
  22782. }
  22783. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22784. // freezeWorldMatrix
  22785. if (parsedMesh.freezeWorldMatrix) {
  22786. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22787. }
  22788. // Parent
  22789. if (parsedMesh.parentId) {
  22790. mesh._waitingParentId = parsedMesh.parentId;
  22791. }
  22792. // Actions
  22793. if (parsedMesh.actions !== undefined) {
  22794. mesh._waitingActions = parsedMesh.actions;
  22795. }
  22796. // Overlay
  22797. if (parsedMesh.overlayAlpha !== undefined) {
  22798. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22799. }
  22800. if (parsedMesh.overlayColor !== undefined) {
  22801. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22802. }
  22803. if (parsedMesh.renderOverlay !== undefined) {
  22804. mesh.renderOverlay = parsedMesh.renderOverlay;
  22805. }
  22806. // Geometry
  22807. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22808. if (parsedMesh.delayLoadingFile) {
  22809. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22810. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22811. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22812. if (parsedMesh._binaryInfo) {
  22813. mesh._binaryInfo = parsedMesh._binaryInfo;
  22814. }
  22815. mesh._delayInfo = [];
  22816. if (parsedMesh.hasUVs) {
  22817. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22818. }
  22819. if (parsedMesh.hasUVs2) {
  22820. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22821. }
  22822. if (parsedMesh.hasUVs3) {
  22823. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22824. }
  22825. if (parsedMesh.hasUVs4) {
  22826. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22827. }
  22828. if (parsedMesh.hasUVs5) {
  22829. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22830. }
  22831. if (parsedMesh.hasUVs6) {
  22832. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22833. }
  22834. if (parsedMesh.hasColors) {
  22835. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22836. }
  22837. if (parsedMesh.hasMatricesIndices) {
  22838. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22839. }
  22840. if (parsedMesh.hasMatricesWeights) {
  22841. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22842. }
  22843. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22844. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22845. mesh._checkDelayState();
  22846. }
  22847. }
  22848. else {
  22849. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22850. }
  22851. // Material
  22852. if (parsedMesh.materialId) {
  22853. mesh.setMaterialByID(parsedMesh.materialId);
  22854. }
  22855. else {
  22856. mesh.material = null;
  22857. }
  22858. // Morph targets
  22859. if (parsedMesh.morphTargetManagerId > -1) {
  22860. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22861. }
  22862. // Skeleton
  22863. if (parsedMesh.skeletonId > -1) {
  22864. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22865. if (parsedMesh.numBoneInfluencers) {
  22866. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22867. }
  22868. }
  22869. // Animations
  22870. if (parsedMesh.animations) {
  22871. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22872. var parsedAnimation = parsedMesh.animations[animationIndex];
  22873. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22874. }
  22875. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22876. }
  22877. if (parsedMesh.autoAnimate) {
  22878. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22879. }
  22880. // Layer Mask
  22881. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22882. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22883. }
  22884. else {
  22885. mesh.layerMask = 0x0FFFFFFF;
  22886. }
  22887. // Physics
  22888. if (parsedMesh.physicsImpostor) {
  22889. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22890. mass: parsedMesh.physicsMass,
  22891. friction: parsedMesh.physicsFriction,
  22892. restitution: parsedMesh.physicsRestitution
  22893. }, scene);
  22894. }
  22895. // Instances
  22896. if (parsedMesh.instances) {
  22897. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22898. var parsedInstance = parsedMesh.instances[index];
  22899. var instance = mesh.createInstance(parsedInstance.name);
  22900. if (BABYLON.Tags) {
  22901. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22902. }
  22903. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22904. if (parsedInstance.parentId) {
  22905. instance._waitingParentId = parsedInstance.parentId;
  22906. }
  22907. if (parsedInstance.rotationQuaternion) {
  22908. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22909. }
  22910. else if (parsedInstance.rotation) {
  22911. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22912. }
  22913. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22914. instance.checkCollisions = mesh.checkCollisions;
  22915. if (parsedMesh.animations) {
  22916. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22917. parsedAnimation = parsedMesh.animations[animationIndex];
  22918. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22919. }
  22920. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22921. }
  22922. }
  22923. }
  22924. return mesh;
  22925. };
  22926. /**
  22927. * Creates a ribbon mesh.
  22928. * Please consider using the same method from the MeshBuilder class instead.
  22929. * 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.
  22930. *
  22931. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22932. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22933. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22934. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22935. * 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.
  22936. * 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.
  22937. * 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
  22938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22939. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22941. */
  22942. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22943. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22944. pathArray: pathArray,
  22945. closeArray: closeArray,
  22946. closePath: closePath,
  22947. offset: offset,
  22948. updatable: updatable,
  22949. sideOrientation: sideOrientation,
  22950. instance: instance
  22951. }, scene);
  22952. };
  22953. /**
  22954. * Creates a plane polygonal mesh. By default, this is a disc.
  22955. * Please consider using the same method from the MeshBuilder class instead.
  22956. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22957. * 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.
  22958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22959. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22961. */
  22962. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22963. var options = {
  22964. radius: radius,
  22965. tessellation: tessellation,
  22966. sideOrientation: sideOrientation,
  22967. updatable: updatable
  22968. };
  22969. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22970. };
  22971. /**
  22972. * Creates a box mesh.
  22973. * Please consider using the same method from the MeshBuilder class instead.
  22974. * The parameter `size` sets the size (float) of each box side (default 1).
  22975. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22976. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22977. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22978. */
  22979. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22980. var options = {
  22981. size: size,
  22982. sideOrientation: sideOrientation,
  22983. updatable: updatable
  22984. };
  22985. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22986. };
  22987. /**
  22988. * Creates a sphere mesh.
  22989. * Please consider using the same method from the MeshBuilder class instead.
  22990. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22991. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22992. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22993. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22994. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22995. */
  22996. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22997. var options = {
  22998. segments: segments,
  22999. diameterX: diameter,
  23000. diameterY: diameter,
  23001. diameterZ: diameter,
  23002. sideOrientation: sideOrientation,
  23003. updatable: updatable
  23004. };
  23005. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23006. };
  23007. /**
  23008. * Creates a cylinder or a cone mesh.
  23009. * Please consider using the same method from the MeshBuilder class instead.
  23010. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23011. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23012. * 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.
  23013. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23014. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23018. */
  23019. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23020. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23021. if (scene !== undefined) {
  23022. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23023. updatable = scene;
  23024. }
  23025. scene = subdivisions;
  23026. subdivisions = 1;
  23027. }
  23028. var options = {
  23029. height: height,
  23030. diameterTop: diameterTop,
  23031. diameterBottom: diameterBottom,
  23032. tessellation: tessellation,
  23033. subdivisions: subdivisions,
  23034. sideOrientation: sideOrientation,
  23035. updatable: updatable
  23036. };
  23037. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23038. };
  23039. // Torus (Code from SharpDX.org)
  23040. /**
  23041. * Creates a torus mesh.
  23042. * Please consider using the same method from the MeshBuilder class instead.
  23043. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23044. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23045. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23049. */
  23050. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23051. var options = {
  23052. diameter: diameter,
  23053. thickness: thickness,
  23054. tessellation: tessellation,
  23055. sideOrientation: sideOrientation,
  23056. updatable: updatable
  23057. };
  23058. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23059. };
  23060. /**
  23061. * Creates a torus knot mesh.
  23062. * Please consider using the same method from the MeshBuilder class instead.
  23063. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23064. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23065. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23066. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23068. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23070. */
  23071. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23072. var options = {
  23073. radius: radius,
  23074. tube: tube,
  23075. radialSegments: radialSegments,
  23076. tubularSegments: tubularSegments,
  23077. p: p,
  23078. q: q,
  23079. sideOrientation: sideOrientation,
  23080. updatable: updatable
  23081. };
  23082. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23083. };
  23084. /**
  23085. * Creates a line mesh.
  23086. * Please consider using the same method from the MeshBuilder class instead.
  23087. * 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.
  23088. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23089. * The parameter `points` is an array successive Vector3.
  23090. * 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
  23091. * When updating an instance, remember that only point positions can change, not the number of points.
  23092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23093. */
  23094. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23095. var options = {
  23096. points: points,
  23097. updatable: updatable,
  23098. instance: instance
  23099. };
  23100. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23101. };
  23102. /**
  23103. * Creates a dashed line mesh.
  23104. * Please consider using the same method from the MeshBuilder class instead.
  23105. * 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.
  23106. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23107. * The parameter `points` is an array successive Vector3.
  23108. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23109. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23110. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23111. * 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
  23112. * When updating an instance, remember that only point positions can change, not the number of points.
  23113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23114. */
  23115. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23116. var options = {
  23117. points: points,
  23118. dashSize: dashSize,
  23119. gapSize: gapSize,
  23120. dashNb: dashNb,
  23121. updatable: updatable,
  23122. instance: instance
  23123. };
  23124. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23125. };
  23126. /**
  23127. * Creates a polygon mesh.
  23128. * Please consider using the same method from the MeshBuilder class instead.
  23129. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23130. * 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.
  23131. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23133. * Remember you can only change the shape positions, not their number when updating a polygon.
  23134. */
  23135. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23136. var options = {
  23137. shape: shape,
  23138. holes: holes,
  23139. updatable: updatable,
  23140. sideOrientation: sideOrientation
  23141. };
  23142. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23143. };
  23144. /**
  23145. * Creates an extruded polygon mesh, with depth in the Y direction.
  23146. * Please consider using the same method from the MeshBuilder class instead.
  23147. */
  23148. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23149. var options = {
  23150. shape: shape,
  23151. holes: holes,
  23152. depth: depth,
  23153. updatable: updatable,
  23154. sideOrientation: sideOrientation
  23155. };
  23156. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23157. };
  23158. /**
  23159. * Creates an extruded shape mesh.
  23160. * 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.
  23161. * Please consider using the same method from the MeshBuilder class instead.
  23162. *
  23163. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23164. * 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
  23165. * extruded along the Z axis.
  23166. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23167. * 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.
  23168. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23169. * 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
  23170. * 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
  23171. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23175. */
  23176. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23177. var options = {
  23178. shape: shape,
  23179. path: path,
  23180. scale: scale,
  23181. rotation: rotation,
  23182. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23183. sideOrientation: sideOrientation,
  23184. instance: instance,
  23185. updatable: updatable
  23186. };
  23187. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23188. };
  23189. /**
  23190. * Creates an custom extruded shape mesh.
  23191. * 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.
  23192. * Please consider using the same method from the MeshBuilder class instead.
  23193. *
  23194. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23195. * 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
  23196. * extruded along the Z axis.
  23197. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23198. * 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
  23199. * and the distance of this point from the begining of the path :
  23200. * ```javascript
  23201. * var rotationFunction = function(i, distance) {
  23202. * // do things
  23203. * return rotationValue; }
  23204. * ```
  23205. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23206. * 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
  23207. * and the distance of this point from the begining of the path :
  23208. * ```javascript
  23209. * var scaleFunction = function(i, distance) {
  23210. * // do things
  23211. * return scaleValue;}
  23212. * ```
  23213. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23214. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23215. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23216. * 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
  23217. * 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
  23218. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23219. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23220. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23222. */
  23223. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23224. var options = {
  23225. shape: shape,
  23226. path: path,
  23227. scaleFunction: scaleFunction,
  23228. rotationFunction: rotationFunction,
  23229. ribbonCloseArray: ribbonCloseArray,
  23230. ribbonClosePath: ribbonClosePath,
  23231. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23232. sideOrientation: sideOrientation,
  23233. instance: instance,
  23234. updatable: updatable
  23235. };
  23236. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23237. };
  23238. /**
  23239. * Creates lathe mesh.
  23240. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23241. * Please consider using the same method from the MeshBuilder class instead.
  23242. * 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
  23243. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23244. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23245. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23247. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23249. */
  23250. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23251. var options = {
  23252. shape: shape,
  23253. radius: radius,
  23254. tessellation: tessellation,
  23255. sideOrientation: sideOrientation,
  23256. updatable: updatable
  23257. };
  23258. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23259. };
  23260. /**
  23261. * Creates a plane mesh.
  23262. * Please consider using the same method from the MeshBuilder class instead.
  23263. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23267. */
  23268. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23269. var options = {
  23270. size: size,
  23271. width: size,
  23272. height: size,
  23273. sideOrientation: sideOrientation,
  23274. updatable: updatable
  23275. };
  23276. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23277. };
  23278. /**
  23279. * Creates a ground mesh.
  23280. * Please consider using the same method from the MeshBuilder class instead.
  23281. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23282. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23284. */
  23285. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23286. var options = {
  23287. width: width,
  23288. height: height,
  23289. subdivisions: subdivisions,
  23290. updatable: updatable
  23291. };
  23292. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23293. };
  23294. /**
  23295. * Creates a tiled ground mesh.
  23296. * Please consider using the same method from the MeshBuilder class instead.
  23297. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23298. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23299. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23300. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23301. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23302. * numbers of subdivisions on the ground width and height of each tile.
  23303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23304. */
  23305. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23306. var options = {
  23307. xmin: xmin,
  23308. zmin: zmin,
  23309. xmax: xmax,
  23310. zmax: zmax,
  23311. subdivisions: subdivisions,
  23312. precision: precision,
  23313. updatable: updatable
  23314. };
  23315. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23316. };
  23317. /**
  23318. * Creates a ground mesh from a height map.
  23319. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23320. * Please consider using the same method from the MeshBuilder class instead.
  23321. * The parameter `url` sets the URL of the height map image resource.
  23322. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23323. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23324. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23325. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23326. * 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).
  23327. * This function is passed the newly built mesh :
  23328. * ```javascript
  23329. * function(mesh) { // do things
  23330. * return; }
  23331. * ```
  23332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23333. */
  23334. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23335. var options = {
  23336. width: width,
  23337. height: height,
  23338. subdivisions: subdivisions,
  23339. minHeight: minHeight,
  23340. maxHeight: maxHeight,
  23341. updatable: updatable,
  23342. onReady: onReady
  23343. };
  23344. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23345. };
  23346. /**
  23347. * Creates a tube mesh.
  23348. * 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.
  23349. * Please consider using the same method from the MeshBuilder class instead.
  23350. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23351. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23352. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23353. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23354. * 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.
  23355. * It must return a radius value (positive float) :
  23356. * ```javascript
  23357. * var radiusFunction = function(i, distance) {
  23358. * // do things
  23359. * return radius; }
  23360. * ```
  23361. * 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
  23362. * 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
  23363. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23364. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23366. */
  23367. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23368. var options = {
  23369. path: path,
  23370. radius: radius,
  23371. tessellation: tessellation,
  23372. radiusFunction: radiusFunction,
  23373. arc: 1,
  23374. cap: cap,
  23375. updatable: updatable,
  23376. sideOrientation: sideOrientation,
  23377. instance: instance
  23378. };
  23379. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23380. };
  23381. /**
  23382. * Creates a polyhedron mesh.
  23383. * Please consider using the same method from the MeshBuilder class instead.
  23384. * 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
  23385. * to choose the wanted type.
  23386. * The parameter `size` (positive float, default 1) sets the polygon size.
  23387. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23388. * 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`.
  23389. * 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
  23390. * 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)`).
  23391. * 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
  23392. * 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.
  23393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23394. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23396. */
  23397. Mesh.CreatePolyhedron = function (name, options, scene) {
  23398. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23399. };
  23400. /**
  23401. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23402. * Please consider using the same method from the MeshBuilder class instead.
  23403. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23404. * 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`).
  23405. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23406. * 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.
  23407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23408. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23410. */
  23411. Mesh.CreateIcoSphere = function (name, options, scene) {
  23412. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23413. };
  23414. /**
  23415. * Creates a decal mesh.
  23416. * Please consider using the same method from the MeshBuilder class instead.
  23417. * 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.
  23418. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23419. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23420. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23421. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23422. */
  23423. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23424. var options = {
  23425. position: position,
  23426. normal: normal,
  23427. size: size,
  23428. angle: angle
  23429. };
  23430. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23431. };
  23432. // Skeletons
  23433. /**
  23434. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23435. */
  23436. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23437. var source;
  23438. if (!this._sourcePositions) {
  23439. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23440. this._sourcePositions = new Float32Array(source);
  23441. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23442. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23443. }
  23444. }
  23445. return this._sourcePositions;
  23446. };
  23447. /**
  23448. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23449. */
  23450. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23451. var source;
  23452. if (!this._sourceNormals) {
  23453. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23454. this._sourceNormals = new Float32Array(source);
  23455. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23456. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23457. }
  23458. }
  23459. return this._sourceNormals;
  23460. };
  23461. /**
  23462. * Updates the vertex buffer by applying transformation from the bones.
  23463. * Returns the Mesh.
  23464. *
  23465. * @param {skeleton} skeleton to apply
  23466. */
  23467. Mesh.prototype.applySkeleton = function (skeleton) {
  23468. if (!this.geometry) {
  23469. return this;
  23470. }
  23471. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23472. return this;
  23473. }
  23474. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23475. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23476. return this;
  23477. }
  23478. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23479. return this;
  23480. }
  23481. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23482. return this;
  23483. }
  23484. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23485. return this;
  23486. }
  23487. if (!this._sourcePositions) {
  23488. var submeshes = this.subMeshes.slice();
  23489. this.setPositionsForCPUSkinning();
  23490. this.subMeshes = submeshes;
  23491. }
  23492. if (!this._sourceNormals) {
  23493. this.setNormalsForCPUSkinning();
  23494. }
  23495. // positionsData checks for not being Float32Array will only pass at most once
  23496. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23497. if (!(positionsData instanceof Float32Array)) {
  23498. positionsData = new Float32Array(positionsData);
  23499. }
  23500. // normalsData checks for not being Float32Array will only pass at most once
  23501. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23502. if (!(normalsData instanceof Float32Array)) {
  23503. normalsData = new Float32Array(normalsData);
  23504. }
  23505. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23506. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23507. var needExtras = this.numBoneInfluencers > 4;
  23508. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23509. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23510. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23511. var tempVector3 = BABYLON.Vector3.Zero();
  23512. var finalMatrix = new BABYLON.Matrix();
  23513. var tempMatrix = new BABYLON.Matrix();
  23514. var matWeightIdx = 0;
  23515. var inf;
  23516. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23517. var weight;
  23518. for (inf = 0; inf < 4; inf++) {
  23519. weight = matricesWeightsData[matWeightIdx + inf];
  23520. if (weight > 0) {
  23521. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23522. finalMatrix.addToSelf(tempMatrix);
  23523. }
  23524. else
  23525. break;
  23526. }
  23527. if (needExtras) {
  23528. for (inf = 0; inf < 4; inf++) {
  23529. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23530. if (weight > 0) {
  23531. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23532. finalMatrix.addToSelf(tempMatrix);
  23533. }
  23534. else
  23535. break;
  23536. }
  23537. }
  23538. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23539. tempVector3.toArray(positionsData, index);
  23540. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23541. tempVector3.toArray(normalsData, index);
  23542. finalMatrix.reset();
  23543. }
  23544. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23545. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23546. return this;
  23547. };
  23548. // Tools
  23549. /**
  23550. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23551. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23552. */
  23553. Mesh.MinMax = function (meshes) {
  23554. var minVector = null;
  23555. var maxVector = null;
  23556. meshes.forEach(function (mesh, index, array) {
  23557. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23558. if (!minVector) {
  23559. minVector = boundingBox.minimumWorld;
  23560. maxVector = boundingBox.maximumWorld;
  23561. }
  23562. else {
  23563. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23564. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23565. }
  23566. });
  23567. return {
  23568. min: minVector,
  23569. max: maxVector
  23570. };
  23571. };
  23572. /**
  23573. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23574. */
  23575. Mesh.Center = function (meshesOrMinMaxVector) {
  23576. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23577. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23578. };
  23579. /**
  23580. * Merge the array of meshes into a single mesh for performance reasons.
  23581. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23582. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23583. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23584. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23585. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23586. */
  23587. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23588. if (disposeSource === void 0) { disposeSource = true; }
  23589. var index;
  23590. if (!allow32BitsIndices) {
  23591. var totalVertices = 0;
  23592. // Counting vertices
  23593. for (index = 0; index < meshes.length; index++) {
  23594. if (meshes[index]) {
  23595. totalVertices += meshes[index].getTotalVertices();
  23596. if (totalVertices > 65536) {
  23597. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23598. return null;
  23599. }
  23600. }
  23601. }
  23602. }
  23603. // Merge
  23604. var vertexData;
  23605. var otherVertexData;
  23606. var indiceArray = new Array();
  23607. var source;
  23608. for (index = 0; index < meshes.length; index++) {
  23609. if (meshes[index]) {
  23610. meshes[index].computeWorldMatrix(true);
  23611. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23612. otherVertexData.transform(meshes[index].getWorldMatrix());
  23613. if (vertexData) {
  23614. vertexData.merge(otherVertexData);
  23615. }
  23616. else {
  23617. vertexData = otherVertexData;
  23618. source = meshes[index];
  23619. }
  23620. if (subdivideWithSubMeshes) {
  23621. indiceArray.push(meshes[index].getTotalIndices());
  23622. }
  23623. }
  23624. }
  23625. if (!meshSubclass) {
  23626. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23627. }
  23628. vertexData.applyToMesh(meshSubclass);
  23629. // Setting properties
  23630. meshSubclass.material = source.material;
  23631. meshSubclass.checkCollisions = source.checkCollisions;
  23632. // Cleaning
  23633. if (disposeSource) {
  23634. for (index = 0; index < meshes.length; index++) {
  23635. if (meshes[index]) {
  23636. meshes[index].dispose();
  23637. }
  23638. }
  23639. }
  23640. // Subdivide
  23641. if (subdivideWithSubMeshes) {
  23642. //-- Suppresions du submesh global
  23643. meshSubclass.releaseSubMeshes();
  23644. index = 0;
  23645. var offset = 0;
  23646. //-- aplique la subdivision en fonction du tableau d'indices
  23647. while (index < indiceArray.length) {
  23648. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23649. offset += indiceArray[index];
  23650. index++;
  23651. }
  23652. }
  23653. return meshSubclass;
  23654. };
  23655. // Consts
  23656. Mesh._FRONTSIDE = 0;
  23657. Mesh._BACKSIDE = 1;
  23658. Mesh._DOUBLESIDE = 2;
  23659. Mesh._DEFAULTSIDE = 0;
  23660. Mesh._NO_CAP = 0;
  23661. Mesh._CAP_START = 1;
  23662. Mesh._CAP_END = 2;
  23663. Mesh._CAP_ALL = 3;
  23664. return Mesh;
  23665. }(BABYLON.AbstractMesh));
  23666. BABYLON.Mesh = Mesh;
  23667. })(BABYLON || (BABYLON = {}));
  23668. //# sourceMappingURL=babylon.mesh.js.map
  23669. var BABYLON;
  23670. (function (BABYLON) {
  23671. var BaseSubMesh = (function () {
  23672. function BaseSubMesh() {
  23673. }
  23674. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23675. get: function () {
  23676. return this._materialEffect;
  23677. },
  23678. enumerable: true,
  23679. configurable: true
  23680. });
  23681. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23682. if (this._materialEffect === effect) {
  23683. if (!effect) {
  23684. this._materialDefines = undefined;
  23685. }
  23686. return;
  23687. }
  23688. this._materialDefines = defines;
  23689. this._materialEffect = effect;
  23690. };
  23691. return BaseSubMesh;
  23692. }());
  23693. BABYLON.BaseSubMesh = BaseSubMesh;
  23694. var SubMesh = (function (_super) {
  23695. __extends(SubMesh, _super);
  23696. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23697. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23698. var _this = _super.call(this) || this;
  23699. _this.materialIndex = materialIndex;
  23700. _this.verticesStart = verticesStart;
  23701. _this.verticesCount = verticesCount;
  23702. _this.indexStart = indexStart;
  23703. _this.indexCount = indexCount;
  23704. _this._renderId = 0;
  23705. _this._mesh = mesh;
  23706. _this._renderingMesh = renderingMesh || mesh;
  23707. mesh.subMeshes.push(_this);
  23708. _this._trianglePlanes = [];
  23709. _this._id = mesh.subMeshes.length - 1;
  23710. if (createBoundingBox) {
  23711. _this.refreshBoundingInfo();
  23712. mesh.computeWorldMatrix(true);
  23713. }
  23714. return _this;
  23715. }
  23716. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23717. get: function () {
  23718. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23719. },
  23720. enumerable: true,
  23721. configurable: true
  23722. });
  23723. /**
  23724. * Returns the submesh BoudingInfo object.
  23725. */
  23726. SubMesh.prototype.getBoundingInfo = function () {
  23727. if (this.IsGlobal) {
  23728. return this._mesh.getBoundingInfo();
  23729. }
  23730. return this._boundingInfo;
  23731. };
  23732. /**
  23733. * Sets the submesh BoundingInfo.
  23734. * Return the SubMesh.
  23735. */
  23736. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23737. this._boundingInfo = boundingInfo;
  23738. return this;
  23739. };
  23740. /**
  23741. * Returns the mesh of the current submesh.
  23742. */
  23743. SubMesh.prototype.getMesh = function () {
  23744. return this._mesh;
  23745. };
  23746. /**
  23747. * Returns the rendering mesh of the submesh.
  23748. */
  23749. SubMesh.prototype.getRenderingMesh = function () {
  23750. return this._renderingMesh;
  23751. };
  23752. /**
  23753. * Returns the submesh material.
  23754. */
  23755. SubMesh.prototype.getMaterial = function () {
  23756. var rootMaterial = this._renderingMesh.material;
  23757. if (rootMaterial && rootMaterial.getSubMaterial) {
  23758. var multiMaterial = rootMaterial;
  23759. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23760. if (this._currentMaterial !== effectiveMaterial) {
  23761. this._currentMaterial = effectiveMaterial;
  23762. this._materialDefines = undefined;
  23763. }
  23764. return effectiveMaterial;
  23765. }
  23766. if (!rootMaterial) {
  23767. return this._mesh.getScene().defaultMaterial;
  23768. }
  23769. return rootMaterial;
  23770. };
  23771. // Methods
  23772. /**
  23773. * Sets a new updated BoundingInfo object to the submesh.
  23774. * Returns the SubMesh.
  23775. */
  23776. SubMesh.prototype.refreshBoundingInfo = function () {
  23777. this._lastColliderWorldVertices = null;
  23778. if (this.IsGlobal) {
  23779. return;
  23780. }
  23781. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23782. if (!data) {
  23783. this._boundingInfo = this._mesh._boundingInfo;
  23784. return;
  23785. }
  23786. var indices = this._renderingMesh.getIndices();
  23787. var extend;
  23788. //is this the only submesh?
  23789. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23790. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23791. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23792. }
  23793. else {
  23794. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23795. }
  23796. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23797. return this;
  23798. };
  23799. SubMesh.prototype._checkCollision = function (collider) {
  23800. return this.getBoundingInfo()._checkCollision(collider);
  23801. };
  23802. /**
  23803. * Updates the submesh BoundingInfo.
  23804. * Returns the Submesh.
  23805. */
  23806. SubMesh.prototype.updateBoundingInfo = function (world) {
  23807. if (!this.getBoundingInfo()) {
  23808. this.refreshBoundingInfo();
  23809. }
  23810. this.getBoundingInfo().update(world);
  23811. return this;
  23812. };
  23813. /**
  23814. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23815. * Boolean returned.
  23816. */
  23817. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23818. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23819. };
  23820. /**
  23821. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23822. * Boolean returned.
  23823. */
  23824. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23825. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23826. };
  23827. /**
  23828. * Renders the submesh.
  23829. * Returns it.
  23830. */
  23831. SubMesh.prototype.render = function (enableAlphaMode) {
  23832. this._renderingMesh.render(this, enableAlphaMode);
  23833. return this;
  23834. };
  23835. /**
  23836. * Returns a new Index Buffer.
  23837. * Type returned : WebGLBuffer.
  23838. */
  23839. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23840. if (!this._linesIndexBuffer) {
  23841. var linesIndices = [];
  23842. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23843. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23844. }
  23845. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23846. this.linesIndexCount = linesIndices.length;
  23847. }
  23848. return this._linesIndexBuffer;
  23849. };
  23850. /**
  23851. * True is the passed Ray intersects the submesh bounding box.
  23852. * Boolean returned.
  23853. */
  23854. SubMesh.prototype.canIntersects = function (ray) {
  23855. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23856. };
  23857. /**
  23858. * Returns an object IntersectionInfo.
  23859. */
  23860. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23861. var intersectInfo = null;
  23862. // LineMesh first as it's also a Mesh...
  23863. if (this._mesh instanceof BABYLON.LinesMesh) {
  23864. var lineMesh = this._mesh;
  23865. // Line test
  23866. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23867. var p0 = positions[indices[index]];
  23868. var p1 = positions[indices[index + 1]];
  23869. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23870. if (length < 0) {
  23871. continue;
  23872. }
  23873. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23874. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23875. if (fastCheck) {
  23876. break;
  23877. }
  23878. }
  23879. }
  23880. }
  23881. else {
  23882. // Triangles test
  23883. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23884. var p0 = positions[indices[index]];
  23885. var p1 = positions[indices[index + 1]];
  23886. var p2 = positions[indices[index + 2]];
  23887. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23888. if (currentIntersectInfo) {
  23889. if (currentIntersectInfo.distance < 0) {
  23890. continue;
  23891. }
  23892. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23893. intersectInfo = currentIntersectInfo;
  23894. intersectInfo.faceId = index / 3;
  23895. if (fastCheck) {
  23896. break;
  23897. }
  23898. }
  23899. }
  23900. }
  23901. }
  23902. return intersectInfo;
  23903. };
  23904. SubMesh.prototype._rebuild = function () {
  23905. if (this._linesIndexBuffer) {
  23906. this._linesIndexBuffer = null;
  23907. }
  23908. };
  23909. // Clone
  23910. /**
  23911. * Creates a new Submesh from the passed Mesh.
  23912. */
  23913. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23914. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23915. if (!this.IsGlobal) {
  23916. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23917. }
  23918. return result;
  23919. };
  23920. // Dispose
  23921. /**
  23922. * Disposes the Submesh.
  23923. * Returns nothing.
  23924. */
  23925. SubMesh.prototype.dispose = function () {
  23926. if (this._linesIndexBuffer) {
  23927. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23928. this._linesIndexBuffer = null;
  23929. }
  23930. // Remove from mesh
  23931. var index = this._mesh.subMeshes.indexOf(this);
  23932. this._mesh.subMeshes.splice(index, 1);
  23933. };
  23934. // Statics
  23935. /**
  23936. * Creates a new Submesh from the passed parameters :
  23937. * - materialIndex (integer) : the index of the main mesh material.
  23938. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23939. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23940. * - mesh (Mesh) : the main mesh to create the submesh from.
  23941. * - renderingMesh (optional Mesh) : rendering mesh.
  23942. */
  23943. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23944. var minVertexIndex = Number.MAX_VALUE;
  23945. var maxVertexIndex = -Number.MAX_VALUE;
  23946. renderingMesh = renderingMesh || mesh;
  23947. var indices = renderingMesh.getIndices();
  23948. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23949. var vertexIndex = indices[index];
  23950. if (vertexIndex < minVertexIndex)
  23951. minVertexIndex = vertexIndex;
  23952. if (vertexIndex > maxVertexIndex)
  23953. maxVertexIndex = vertexIndex;
  23954. }
  23955. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23956. };
  23957. return SubMesh;
  23958. }(BaseSubMesh));
  23959. BABYLON.SubMesh = SubMesh;
  23960. })(BABYLON || (BABYLON = {}));
  23961. //# sourceMappingURL=babylon.subMesh.js.map
  23962. var BABYLON;
  23963. (function (BABYLON) {
  23964. var EffectFallbacks = (function () {
  23965. function EffectFallbacks() {
  23966. this._defines = {};
  23967. this._currentRank = 32;
  23968. this._maxRank = -1;
  23969. }
  23970. EffectFallbacks.prototype.unBindMesh = function () {
  23971. this._mesh = null;
  23972. };
  23973. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23974. if (!this._defines[rank]) {
  23975. if (rank < this._currentRank) {
  23976. this._currentRank = rank;
  23977. }
  23978. if (rank > this._maxRank) {
  23979. this._maxRank = rank;
  23980. }
  23981. this._defines[rank] = new Array();
  23982. }
  23983. this._defines[rank].push(define);
  23984. };
  23985. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23986. this._meshRank = rank;
  23987. this._mesh = mesh;
  23988. if (rank < this._currentRank) {
  23989. this._currentRank = rank;
  23990. }
  23991. if (rank > this._maxRank) {
  23992. this._maxRank = rank;
  23993. }
  23994. };
  23995. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23996. get: function () {
  23997. return this._currentRank <= this._maxRank;
  23998. },
  23999. enumerable: true,
  24000. configurable: true
  24001. });
  24002. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24003. // First we try to switch to CPU skinning
  24004. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24005. this._mesh.computeBonesUsingShaders = false;
  24006. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24007. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24008. var scene = this._mesh.getScene();
  24009. for (var index = 0; index < scene.meshes.length; index++) {
  24010. var otherMesh = scene.meshes[index];
  24011. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24012. otherMesh.computeBonesUsingShaders = false;
  24013. }
  24014. }
  24015. }
  24016. else {
  24017. var currentFallbacks = this._defines[this._currentRank];
  24018. if (currentFallbacks) {
  24019. for (var index = 0; index < currentFallbacks.length; index++) {
  24020. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24021. }
  24022. }
  24023. this._currentRank++;
  24024. }
  24025. return currentDefines;
  24026. };
  24027. return EffectFallbacks;
  24028. }());
  24029. BABYLON.EffectFallbacks = EffectFallbacks;
  24030. var EffectCreationOptions = (function () {
  24031. function EffectCreationOptions() {
  24032. }
  24033. return EffectCreationOptions;
  24034. }());
  24035. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24036. var Effect = (function () {
  24037. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24038. var _this = this;
  24039. this.uniqueId = 0;
  24040. this.onCompileObservable = new BABYLON.Observable();
  24041. this.onErrorObservable = new BABYLON.Observable();
  24042. this.onBindObservable = new BABYLON.Observable();
  24043. this._uniformBuffersNames = {};
  24044. this._isReady = false;
  24045. this._compilationError = "";
  24046. this.name = baseName;
  24047. if (attributesNamesOrOptions.attributes) {
  24048. var options = attributesNamesOrOptions;
  24049. this._engine = uniformsNamesOrEngine;
  24050. this._attributesNames = options.attributes;
  24051. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24052. this._samplers = options.samplers;
  24053. this.defines = options.defines;
  24054. this.onError = options.onError;
  24055. this.onCompiled = options.onCompiled;
  24056. this._fallbacks = options.fallbacks;
  24057. this._indexParameters = options.indexParameters;
  24058. if (options.uniformBuffersNames) {
  24059. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24060. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24061. }
  24062. }
  24063. }
  24064. else {
  24065. this._engine = engine;
  24066. this.defines = defines;
  24067. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24068. this._samplers = samplers;
  24069. this._attributesNames = attributesNamesOrOptions;
  24070. this.onError = onError;
  24071. this.onCompiled = onCompiled;
  24072. this._indexParameters = indexParameters;
  24073. this._fallbacks = fallbacks;
  24074. }
  24075. this.uniqueId = Effect._uniqueIdSeed++;
  24076. var vertexSource;
  24077. var fragmentSource;
  24078. if (baseName.vertexElement) {
  24079. vertexSource = document.getElementById(baseName.vertexElement);
  24080. if (!vertexSource) {
  24081. vertexSource = baseName.vertexElement;
  24082. }
  24083. }
  24084. else {
  24085. vertexSource = baseName.vertex || baseName;
  24086. }
  24087. if (baseName.fragmentElement) {
  24088. fragmentSource = document.getElementById(baseName.fragmentElement);
  24089. if (!fragmentSource) {
  24090. fragmentSource = baseName.fragmentElement;
  24091. }
  24092. }
  24093. else {
  24094. fragmentSource = baseName.fragment || baseName;
  24095. }
  24096. this._loadVertexShader(vertexSource, function (vertexCode) {
  24097. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24098. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24099. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24100. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24101. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24102. if (baseName) {
  24103. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24104. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24105. }
  24106. else {
  24107. _this._vertexSourceCode = migratedVertexCode;
  24108. _this._fragmentSourceCode = migratedFragmentCode;
  24109. }
  24110. _this._prepareEffect();
  24111. });
  24112. });
  24113. });
  24114. });
  24115. });
  24116. });
  24117. }
  24118. Object.defineProperty(Effect.prototype, "key", {
  24119. get: function () {
  24120. return this._key;
  24121. },
  24122. enumerable: true,
  24123. configurable: true
  24124. });
  24125. // Properties
  24126. Effect.prototype.isReady = function () {
  24127. return this._isReady;
  24128. };
  24129. Effect.prototype.getEngine = function () {
  24130. return this._engine;
  24131. };
  24132. Effect.prototype.getProgram = function () {
  24133. return this._program;
  24134. };
  24135. Effect.prototype.getAttributesNames = function () {
  24136. return this._attributesNames;
  24137. };
  24138. Effect.prototype.getAttributeLocation = function (index) {
  24139. return this._attributes[index];
  24140. };
  24141. Effect.prototype.getAttributeLocationByName = function (name) {
  24142. var index = this._attributesNames.indexOf(name);
  24143. return this._attributes[index];
  24144. };
  24145. Effect.prototype.getAttributesCount = function () {
  24146. return this._attributes.length;
  24147. };
  24148. Effect.prototype.getUniformIndex = function (uniformName) {
  24149. return this._uniformsNames.indexOf(uniformName);
  24150. };
  24151. Effect.prototype.getUniform = function (uniformName) {
  24152. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24153. };
  24154. Effect.prototype.getSamplers = function () {
  24155. return this._samplers;
  24156. };
  24157. Effect.prototype.getCompilationError = function () {
  24158. return this._compilationError;
  24159. };
  24160. // Methods
  24161. Effect.prototype.executeWhenCompiled = function (func) {
  24162. if (this.isReady()) {
  24163. func(this);
  24164. return;
  24165. }
  24166. this.onCompileObservable.add(function (effect) {
  24167. func(effect);
  24168. });
  24169. };
  24170. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24171. // DOM element ?
  24172. if (vertex instanceof HTMLElement) {
  24173. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24174. callback(vertexCode);
  24175. return;
  24176. }
  24177. // Base64 encoded ?
  24178. if (vertex.substr(0, 7) === "base64:") {
  24179. var vertexBinary = window.atob(vertex.substr(7));
  24180. callback(vertexBinary);
  24181. return;
  24182. }
  24183. // Is in local store ?
  24184. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24185. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24186. return;
  24187. }
  24188. var vertexShaderUrl;
  24189. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24190. vertexShaderUrl = vertex;
  24191. }
  24192. else {
  24193. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24194. }
  24195. // Vertex shader
  24196. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24197. };
  24198. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24199. // DOM element ?
  24200. if (fragment instanceof HTMLElement) {
  24201. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24202. callback(fragmentCode);
  24203. return;
  24204. }
  24205. // Base64 encoded ?
  24206. if (fragment.substr(0, 7) === "base64:") {
  24207. var fragmentBinary = window.atob(fragment.substr(7));
  24208. callback(fragmentBinary);
  24209. return;
  24210. }
  24211. // Is in local store ?
  24212. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24213. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24214. return;
  24215. }
  24216. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24217. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24218. return;
  24219. }
  24220. var fragmentShaderUrl;
  24221. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24222. fragmentShaderUrl = fragment;
  24223. }
  24224. else {
  24225. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24226. }
  24227. // Fragment shader
  24228. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24229. };
  24230. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24231. // Rebuild shaders source code
  24232. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24233. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24234. vertexCode = prefix + vertexCode;
  24235. fragmentCode = prefix + fragmentCode;
  24236. // Number lines of shaders source code
  24237. var i = 2;
  24238. var regex = /\n/gm;
  24239. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24240. i = 2;
  24241. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24242. // Dump shaders name and formatted source code
  24243. if (this.name.vertexElement) {
  24244. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24245. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24246. }
  24247. else if (this.name.vertex) {
  24248. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24249. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24250. }
  24251. else {
  24252. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24253. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24254. }
  24255. };
  24256. ;
  24257. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24258. var preparedSourceCode = this._processPrecision(sourceCode);
  24259. if (this._engine.webGLVersion == 1) {
  24260. callback(preparedSourceCode);
  24261. return;
  24262. }
  24263. // Already converted
  24264. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24265. callback(preparedSourceCode.replace("#version 300 es", ""));
  24266. return;
  24267. }
  24268. // Remove extensions
  24269. // #extension GL_OES_standard_derivatives : enable
  24270. // #extension GL_EXT_shader_texture_lod : enable
  24271. // #extension GL_EXT_frag_depth : enable
  24272. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24273. var result = preparedSourceCode.replace(regex, "");
  24274. // Migrate to GLSL v300
  24275. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24276. result = result.replace(/attribute[ \t]/g, "in ");
  24277. result = result.replace(/[ \t]attribute/g, " in");
  24278. if (isFragment) {
  24279. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24280. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24281. result = result.replace(/texture2D\(/g, "texture(");
  24282. result = result.replace(/textureCube\(/g, "texture(");
  24283. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24284. result = result.replace(/gl_FragColor/g, "glFragColor");
  24285. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24286. }
  24287. callback(result);
  24288. };
  24289. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24290. var _this = this;
  24291. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24292. var match = regex.exec(sourceCode);
  24293. var returnValue = new String(sourceCode);
  24294. while (match != null) {
  24295. var includeFile = match[1];
  24296. // Uniform declaration
  24297. if (includeFile.indexOf("__decl__") !== -1) {
  24298. includeFile = includeFile.replace(/__decl__/, "");
  24299. if (this._engine.supportsUniformBuffers) {
  24300. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24301. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24302. }
  24303. includeFile = includeFile + "Declaration";
  24304. }
  24305. if (Effect.IncludesShadersStore[includeFile]) {
  24306. // Substitution
  24307. var includeContent = Effect.IncludesShadersStore[includeFile];
  24308. if (match[2]) {
  24309. var splits = match[3].split(",");
  24310. for (var index = 0; index < splits.length; index += 2) {
  24311. var source = new RegExp(splits[index], "g");
  24312. var dest = splits[index + 1];
  24313. includeContent = includeContent.replace(source, dest);
  24314. }
  24315. }
  24316. if (match[4]) {
  24317. var indexString = match[5];
  24318. if (indexString.indexOf("..") !== -1) {
  24319. var indexSplits = indexString.split("..");
  24320. var minIndex = parseInt(indexSplits[0]);
  24321. var maxIndex = parseInt(indexSplits[1]);
  24322. var sourceIncludeContent = includeContent.slice(0);
  24323. includeContent = "";
  24324. if (isNaN(maxIndex)) {
  24325. maxIndex = this._indexParameters[indexSplits[1]];
  24326. }
  24327. for (var i = minIndex; i < maxIndex; i++) {
  24328. if (!this._engine.supportsUniformBuffers) {
  24329. // Ubo replacement
  24330. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24331. return p1 + "{X}";
  24332. });
  24333. }
  24334. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24335. }
  24336. }
  24337. else {
  24338. if (!this._engine.supportsUniformBuffers) {
  24339. // Ubo replacement
  24340. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24341. return p1 + "{X}";
  24342. });
  24343. }
  24344. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24345. }
  24346. }
  24347. // Replace
  24348. returnValue = returnValue.replace(match[0], includeContent);
  24349. }
  24350. else {
  24351. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24352. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24353. Effect.IncludesShadersStore[includeFile] = fileContent;
  24354. _this._processIncludes(returnValue, callback);
  24355. });
  24356. return;
  24357. }
  24358. match = regex.exec(sourceCode);
  24359. }
  24360. callback(returnValue);
  24361. };
  24362. Effect.prototype._processPrecision = function (source) {
  24363. if (source.indexOf("precision highp float") === -1) {
  24364. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24365. source = "precision mediump float;\n" + source;
  24366. }
  24367. else {
  24368. source = "precision highp float;\n" + source;
  24369. }
  24370. }
  24371. else {
  24372. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24373. source = source.replace("precision highp float", "precision mediump float");
  24374. }
  24375. }
  24376. return source;
  24377. };
  24378. Effect.prototype._prepareEffect = function () {
  24379. var attributesNames = this._attributesNames;
  24380. var defines = this.defines;
  24381. var fallbacks = this._fallbacks;
  24382. this._valueCache = {};
  24383. try {
  24384. var engine = this._engine;
  24385. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24386. if (engine.webGLVersion > 1) {
  24387. for (var name in this._uniformBuffersNames) {
  24388. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24389. }
  24390. }
  24391. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24392. this._attributes = engine.getAttributes(this._program, attributesNames);
  24393. var index;
  24394. for (index = 0; index < this._samplers.length; index++) {
  24395. var sampler = this.getUniform(this._samplers[index]);
  24396. if (sampler == null) {
  24397. this._samplers.splice(index, 1);
  24398. index--;
  24399. }
  24400. }
  24401. engine.bindSamplers(this);
  24402. this._compilationError = "";
  24403. this._isReady = true;
  24404. if (this.onCompiled) {
  24405. this.onCompiled(this);
  24406. }
  24407. this.onCompileObservable.notifyObservers(this);
  24408. this.onCompileObservable.clear();
  24409. // Unbind mesh reference in fallbacks
  24410. if (this._fallbacks) {
  24411. this._fallbacks.unBindMesh();
  24412. }
  24413. }
  24414. catch (e) {
  24415. this._compilationError = e.message;
  24416. // Let's go through fallbacks then
  24417. BABYLON.Tools.Error("Unable to compile effect:");
  24418. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24419. return " " + uniform;
  24420. }));
  24421. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24422. return " " + attribute;
  24423. }));
  24424. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24425. BABYLON.Tools.Error("Error: " + this._compilationError);
  24426. if (fallbacks && fallbacks.isMoreFallbacks) {
  24427. BABYLON.Tools.Error("Trying next fallback.");
  24428. this.defines = fallbacks.reduce(this.defines);
  24429. this._prepareEffect();
  24430. }
  24431. else {
  24432. if (this.onError) {
  24433. this.onError(this, this._compilationError);
  24434. }
  24435. this.onErrorObservable.notifyObservers(this);
  24436. this.onErrorObservable.clear();
  24437. // Unbind mesh reference in fallbacks
  24438. if (this._fallbacks) {
  24439. this._fallbacks.unBindMesh();
  24440. }
  24441. }
  24442. }
  24443. };
  24444. Object.defineProperty(Effect.prototype, "isSupported", {
  24445. get: function () {
  24446. return this._compilationError === "";
  24447. },
  24448. enumerable: true,
  24449. configurable: true
  24450. });
  24451. Effect.prototype._bindTexture = function (channel, texture) {
  24452. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24453. };
  24454. Effect.prototype.setTexture = function (channel, texture) {
  24455. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24456. };
  24457. Effect.prototype.setTextureArray = function (channel, textures) {
  24458. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24459. var initialPos = this._samplers.indexOf(channel);
  24460. for (var index = 1; index < textures.length; index++) {
  24461. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24462. }
  24463. }
  24464. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24465. };
  24466. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24467. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24468. };
  24469. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24470. var cache = this._valueCache[uniformName];
  24471. var flag = matrix.updateFlag;
  24472. if (cache !== undefined && cache === flag) {
  24473. return false;
  24474. }
  24475. this._valueCache[uniformName] = flag;
  24476. return true;
  24477. };
  24478. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24479. var cache = this._valueCache[uniformName];
  24480. if (!cache) {
  24481. cache = [x, y];
  24482. this._valueCache[uniformName] = cache;
  24483. return true;
  24484. }
  24485. var changed = false;
  24486. if (cache[0] !== x) {
  24487. cache[0] = x;
  24488. changed = true;
  24489. }
  24490. if (cache[1] !== y) {
  24491. cache[1] = y;
  24492. changed = true;
  24493. }
  24494. return changed;
  24495. };
  24496. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24497. var cache = this._valueCache[uniformName];
  24498. if (!cache) {
  24499. cache = [x, y, z];
  24500. this._valueCache[uniformName] = cache;
  24501. return true;
  24502. }
  24503. var changed = false;
  24504. if (cache[0] !== x) {
  24505. cache[0] = x;
  24506. changed = true;
  24507. }
  24508. if (cache[1] !== y) {
  24509. cache[1] = y;
  24510. changed = true;
  24511. }
  24512. if (cache[2] !== z) {
  24513. cache[2] = z;
  24514. changed = true;
  24515. }
  24516. return changed;
  24517. };
  24518. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24519. var cache = this._valueCache[uniformName];
  24520. if (!cache) {
  24521. cache = [x, y, z, w];
  24522. this._valueCache[uniformName] = cache;
  24523. return true;
  24524. }
  24525. var changed = false;
  24526. if (cache[0] !== x) {
  24527. cache[0] = x;
  24528. changed = true;
  24529. }
  24530. if (cache[1] !== y) {
  24531. cache[1] = y;
  24532. changed = true;
  24533. }
  24534. if (cache[2] !== z) {
  24535. cache[2] = z;
  24536. changed = true;
  24537. }
  24538. if (cache[3] !== w) {
  24539. cache[3] = w;
  24540. changed = true;
  24541. }
  24542. return changed;
  24543. };
  24544. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24545. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24546. return;
  24547. }
  24548. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24549. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24550. };
  24551. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24552. this._engine.bindUniformBlock(this._program, blockName, index);
  24553. };
  24554. Effect.prototype.setIntArray = function (uniformName, array) {
  24555. this._valueCache[uniformName] = null;
  24556. this._engine.setIntArray(this.getUniform(uniformName), array);
  24557. return this;
  24558. };
  24559. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24560. this._valueCache[uniformName] = null;
  24561. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24562. return this;
  24563. };
  24564. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24565. this._valueCache[uniformName] = null;
  24566. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24567. return this;
  24568. };
  24569. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24570. this._valueCache[uniformName] = null;
  24571. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24572. return this;
  24573. };
  24574. Effect.prototype.setFloatArray = function (uniformName, array) {
  24575. this._valueCache[uniformName] = null;
  24576. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24577. return this;
  24578. };
  24579. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24580. this._valueCache[uniformName] = null;
  24581. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24582. return this;
  24583. };
  24584. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24585. this._valueCache[uniformName] = null;
  24586. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24587. return this;
  24588. };
  24589. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24590. this._valueCache[uniformName] = null;
  24591. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24592. return this;
  24593. };
  24594. Effect.prototype.setArray = function (uniformName, array) {
  24595. this._valueCache[uniformName] = null;
  24596. this._engine.setArray(this.getUniform(uniformName), array);
  24597. return this;
  24598. };
  24599. Effect.prototype.setArray2 = function (uniformName, array) {
  24600. this._valueCache[uniformName] = null;
  24601. this._engine.setArray2(this.getUniform(uniformName), array);
  24602. return this;
  24603. };
  24604. Effect.prototype.setArray3 = function (uniformName, array) {
  24605. this._valueCache[uniformName] = null;
  24606. this._engine.setArray3(this.getUniform(uniformName), array);
  24607. return this;
  24608. };
  24609. Effect.prototype.setArray4 = function (uniformName, array) {
  24610. this._valueCache[uniformName] = null;
  24611. this._engine.setArray4(this.getUniform(uniformName), array);
  24612. return this;
  24613. };
  24614. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24615. if (!matrices) {
  24616. return;
  24617. }
  24618. this._valueCache[uniformName] = null;
  24619. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24620. return this;
  24621. };
  24622. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24623. if (this._cacheMatrix(uniformName, matrix)) {
  24624. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24625. }
  24626. return this;
  24627. };
  24628. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24629. this._valueCache[uniformName] = null;
  24630. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24631. return this;
  24632. };
  24633. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24634. this._valueCache[uniformName] = null;
  24635. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24636. return this;
  24637. };
  24638. Effect.prototype.setFloat = function (uniformName, value) {
  24639. var cache = this._valueCache[uniformName];
  24640. if (cache !== undefined && cache === value)
  24641. return this;
  24642. this._valueCache[uniformName] = value;
  24643. this._engine.setFloat(this.getUniform(uniformName), value);
  24644. return this;
  24645. };
  24646. Effect.prototype.setBool = function (uniformName, bool) {
  24647. var cache = this._valueCache[uniformName];
  24648. if (cache !== undefined && cache === bool)
  24649. return this;
  24650. this._valueCache[uniformName] = bool;
  24651. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24652. return this;
  24653. };
  24654. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24655. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24656. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24657. }
  24658. return this;
  24659. };
  24660. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24661. if (this._cacheFloat2(uniformName, x, y)) {
  24662. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24663. }
  24664. return this;
  24665. };
  24666. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24667. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24668. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24669. }
  24670. return this;
  24671. };
  24672. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24673. if (this._cacheFloat3(uniformName, x, y, z)) {
  24674. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24675. }
  24676. return this;
  24677. };
  24678. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24679. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24680. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24681. }
  24682. return this;
  24683. };
  24684. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24685. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24686. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24687. }
  24688. return this;
  24689. };
  24690. Effect.prototype.setColor3 = function (uniformName, color3) {
  24691. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24692. this._engine.setColor3(this.getUniform(uniformName), color3);
  24693. }
  24694. return this;
  24695. };
  24696. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24697. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24698. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24699. }
  24700. return this;
  24701. };
  24702. Effect.ResetCache = function () {
  24703. Effect._baseCache = {};
  24704. };
  24705. Effect._uniqueIdSeed = 0;
  24706. Effect._baseCache = {};
  24707. // Statics
  24708. Effect.ShadersStore = {};
  24709. Effect.IncludesShadersStore = {};
  24710. return Effect;
  24711. }());
  24712. BABYLON.Effect = Effect;
  24713. })(BABYLON || (BABYLON = {}));
  24714. //# sourceMappingURL=babylon.effect.js.map
  24715. var BABYLON;
  24716. (function (BABYLON) {
  24717. var MaterialHelper = (function () {
  24718. function MaterialHelper() {
  24719. }
  24720. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24721. defines._needUVs = true;
  24722. defines[key] = true;
  24723. if (texture.getTextureMatrix().isIdentity(true)) {
  24724. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24725. if (texture.coordinatesIndex === 0) {
  24726. defines["MAINUV1"] = true;
  24727. }
  24728. else {
  24729. defines["MAINUV2"] = true;
  24730. }
  24731. }
  24732. else {
  24733. defines[key + "DIRECTUV"] = 0;
  24734. }
  24735. };
  24736. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24737. var matrix = texture.getTextureMatrix();
  24738. if (!matrix.isIdentity(true)) {
  24739. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24740. }
  24741. };
  24742. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24743. if (defines._areMiscDirty) {
  24744. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24745. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24746. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24747. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24748. }
  24749. };
  24750. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24751. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24752. var changed = false;
  24753. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24754. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24755. changed = true;
  24756. }
  24757. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24758. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24759. changed = true;
  24760. }
  24761. if (defines["INSTANCES"] !== useInstances) {
  24762. defines["INSTANCES"] = useInstances;
  24763. changed = true;
  24764. }
  24765. if (changed) {
  24766. defines.markAsUnprocessed();
  24767. }
  24768. };
  24769. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24770. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24771. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24772. return false;
  24773. }
  24774. defines._normals = defines._needNormals;
  24775. defines._uvs = defines._needUVs;
  24776. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24777. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24778. defines["TANGENT"] = true;
  24779. }
  24780. if (defines._needUVs) {
  24781. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24782. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24783. }
  24784. else {
  24785. defines["UV1"] = false;
  24786. defines["UV2"] = false;
  24787. }
  24788. if (useVertexColor) {
  24789. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24790. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24791. }
  24792. if (useBones) {
  24793. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24794. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24795. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24796. }
  24797. else {
  24798. defines["NUM_BONE_INFLUENCERS"] = 0;
  24799. defines["BonesPerMesh"] = 0;
  24800. }
  24801. }
  24802. if (useMorphTargets) {
  24803. if (mesh.morphTargetManager) {
  24804. var manager = mesh.morphTargetManager;
  24805. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24806. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24807. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24808. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24809. }
  24810. else {
  24811. defines["MORPHTARGETS_TANGENT"] = false;
  24812. defines["MORPHTARGETS_NORMAL"] = false;
  24813. defines["MORPHTARGETS"] = false;
  24814. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24815. }
  24816. }
  24817. return true;
  24818. };
  24819. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24820. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24821. if (disableLighting === void 0) { disableLighting = false; }
  24822. if (!defines._areLightsDirty) {
  24823. return defines._needNormals;
  24824. }
  24825. var lightIndex = 0;
  24826. var needNormals = false;
  24827. var needRebuild = false;
  24828. var lightmapMode = false;
  24829. var shadowEnabled = false;
  24830. var specularEnabled = false;
  24831. if (scene.lightsEnabled && !disableLighting) {
  24832. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24833. var light = _a[_i];
  24834. needNormals = true;
  24835. if (defines["LIGHT" + lightIndex] === undefined) {
  24836. needRebuild = true;
  24837. }
  24838. defines["LIGHT" + lightIndex] = true;
  24839. defines["SPOTLIGHT" + lightIndex] = false;
  24840. defines["HEMILIGHT" + lightIndex] = false;
  24841. defines["POINTLIGHT" + lightIndex] = false;
  24842. defines["DIRLIGHT" + lightIndex] = false;
  24843. var type;
  24844. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24845. type = "SPOTLIGHT" + lightIndex;
  24846. }
  24847. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24848. type = "HEMILIGHT" + lightIndex;
  24849. }
  24850. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24851. type = "POINTLIGHT" + lightIndex;
  24852. }
  24853. else {
  24854. type = "DIRLIGHT" + lightIndex;
  24855. }
  24856. defines[type] = true;
  24857. // Specular
  24858. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24859. specularEnabled = true;
  24860. }
  24861. // Shadows
  24862. defines["SHADOW" + lightIndex] = false;
  24863. defines["SHADOWPCF" + lightIndex] = false;
  24864. defines["SHADOWESM" + lightIndex] = false;
  24865. defines["SHADOWCUBE" + lightIndex] = false;
  24866. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24867. var shadowGenerator = light.getShadowGenerator();
  24868. if (shadowGenerator) {
  24869. shadowEnabled = true;
  24870. shadowGenerator.prepareDefines(defines, lightIndex);
  24871. }
  24872. }
  24873. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24874. lightmapMode = true;
  24875. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24876. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24877. }
  24878. else {
  24879. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24880. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24881. }
  24882. lightIndex++;
  24883. if (lightIndex === maxSimultaneousLights)
  24884. break;
  24885. }
  24886. }
  24887. defines["SPECULARTERM"] = specularEnabled;
  24888. defines["SHADOWS"] = shadowEnabled;
  24889. // Resetting all other lights if any
  24890. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24891. if (defines["LIGHT" + index] !== undefined) {
  24892. defines["LIGHT" + index] = false;
  24893. defines["HEMILIGHT" + lightIndex] = false;
  24894. defines["POINTLIGHT" + lightIndex] = false;
  24895. defines["DIRLIGHT" + lightIndex] = false;
  24896. defines["SPOTLIGHT" + lightIndex] = false;
  24897. defines["SHADOW" + lightIndex] = false;
  24898. }
  24899. }
  24900. var caps = scene.getEngine().getCaps();
  24901. if (defines["SHADOWFLOAT"] === undefined) {
  24902. needRebuild = true;
  24903. }
  24904. defines["SHADOWFLOAT"] = shadowEnabled &&
  24905. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24906. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24907. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24908. if (needRebuild) {
  24909. defines.rebuild();
  24910. }
  24911. return needNormals;
  24912. };
  24913. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24914. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24915. var uniformsList, uniformBuffersList, samplersList, defines;
  24916. if (uniformsListOrOptions.uniformsNames) {
  24917. var options = uniformsListOrOptions;
  24918. uniformsList = options.uniformsNames;
  24919. uniformBuffersList = options.uniformBuffersNames;
  24920. samplersList = options.samplers;
  24921. defines = options.defines;
  24922. maxSimultaneousLights = options.maxSimultaneousLights;
  24923. }
  24924. else {
  24925. uniformsList = uniformsListOrOptions;
  24926. }
  24927. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24928. if (!defines["LIGHT" + lightIndex]) {
  24929. break;
  24930. }
  24931. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24932. if (uniformBuffersList) {
  24933. uniformBuffersList.push("Light" + lightIndex);
  24934. }
  24935. samplersList.push("shadowSampler" + lightIndex);
  24936. }
  24937. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24938. uniformsList.push("morphTargetInfluences");
  24939. }
  24940. };
  24941. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24942. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24943. if (!defines["SHADOWS"]) {
  24944. return;
  24945. }
  24946. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24947. if (!defines["LIGHT" + lightIndex]) {
  24948. break;
  24949. }
  24950. if (lightIndex > 0) {
  24951. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24952. }
  24953. if (defines["SHADOW" + lightIndex]) {
  24954. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24955. }
  24956. if (defines["SHADOWPCF" + lightIndex]) {
  24957. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24958. }
  24959. if (defines["SHADOWESM" + lightIndex]) {
  24960. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24961. }
  24962. }
  24963. };
  24964. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24965. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24966. if (influencers > 0) {
  24967. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24968. var manager = mesh.morphTargetManager;
  24969. var normal = manager.supportsNormals && defines["NORMAL"];
  24970. var tangent = manager.supportsTangents && defines["TANGENT"];
  24971. for (var index = 0; index < influencers; index++) {
  24972. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24973. if (normal) {
  24974. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24975. }
  24976. if (tangent) {
  24977. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24978. }
  24979. if (attribs.length > maxAttributesCount) {
  24980. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24981. }
  24982. }
  24983. }
  24984. };
  24985. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24986. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24987. fallbacks.addCPUSkinningFallback(0, mesh);
  24988. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24989. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24990. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24991. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24992. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24993. }
  24994. }
  24995. };
  24996. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24997. if (defines["INSTANCES"]) {
  24998. attribs.push("world0");
  24999. attribs.push("world1");
  25000. attribs.push("world2");
  25001. attribs.push("world3");
  25002. }
  25003. };
  25004. // Bindings
  25005. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25006. if (light.shadowEnabled && mesh.receiveShadows) {
  25007. var shadowGenerator = light.getShadowGenerator();
  25008. if (shadowGenerator) {
  25009. shadowGenerator.bindShadowLight(lightIndex, effect);
  25010. }
  25011. }
  25012. };
  25013. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25014. light.transferToEffect(effect, lightIndex + "");
  25015. };
  25016. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25017. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25018. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25019. var lightIndex = 0;
  25020. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25021. var light = _a[_i];
  25022. var scaledIntensity = light.getScaledIntensity();
  25023. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25024. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25025. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25026. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25027. if (defines["SPECULARTERM"]) {
  25028. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25029. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25030. }
  25031. // Shadows
  25032. if (scene.shadowsEnabled) {
  25033. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25034. }
  25035. light._uniformBuffer.update();
  25036. lightIndex++;
  25037. if (lightIndex === maxSimultaneousLights)
  25038. break;
  25039. }
  25040. };
  25041. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25042. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25043. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25044. effect.setColor3("vFogColor", scene.fogColor);
  25045. }
  25046. };
  25047. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25048. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25049. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25050. if (matrices) {
  25051. effect.setMatrices("mBones", matrices);
  25052. }
  25053. }
  25054. };
  25055. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25056. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25057. return;
  25058. }
  25059. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25060. };
  25061. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25062. if (defines["LOGARITHMICDEPTH"]) {
  25063. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25064. }
  25065. };
  25066. MaterialHelper.BindClipPlane = function (effect, scene) {
  25067. if (scene.clipPlane) {
  25068. var clipPlane = scene.clipPlane;
  25069. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25070. }
  25071. };
  25072. return MaterialHelper;
  25073. }());
  25074. BABYLON.MaterialHelper = MaterialHelper;
  25075. })(BABYLON || (BABYLON = {}));
  25076. //# sourceMappingURL=babylon.materialHelper.js.map
  25077. var BABYLON;
  25078. (function (BABYLON) {
  25079. var MaterialDefines = (function () {
  25080. function MaterialDefines() {
  25081. this._isDirty = true;
  25082. this._areLightsDirty = true;
  25083. this._areAttributesDirty = true;
  25084. this._areTexturesDirty = true;
  25085. this._areFresnelDirty = true;
  25086. this._areMiscDirty = true;
  25087. this._areImageProcessingDirty = true;
  25088. this._normals = false;
  25089. this._uvs = false;
  25090. this._needNormals = false;
  25091. this._needUVs = false;
  25092. }
  25093. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25094. get: function () {
  25095. return this._isDirty;
  25096. },
  25097. enumerable: true,
  25098. configurable: true
  25099. });
  25100. MaterialDefines.prototype.markAsProcessed = function () {
  25101. this._isDirty = false;
  25102. this._areAttributesDirty = false;
  25103. this._areTexturesDirty = false;
  25104. this._areFresnelDirty = false;
  25105. this._areLightsDirty = false;
  25106. this._areMiscDirty = false;
  25107. this._areImageProcessingDirty = false;
  25108. };
  25109. MaterialDefines.prototype.markAsUnprocessed = function () {
  25110. this._isDirty = true;
  25111. };
  25112. MaterialDefines.prototype.markAllAsDirty = function () {
  25113. this._areTexturesDirty = true;
  25114. this._areAttributesDirty = true;
  25115. this._areLightsDirty = true;
  25116. this._areFresnelDirty = true;
  25117. this._areMiscDirty = true;
  25118. this._areImageProcessingDirty = true;
  25119. this._isDirty = true;
  25120. };
  25121. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25122. this._areImageProcessingDirty = true;
  25123. this._isDirty = true;
  25124. };
  25125. MaterialDefines.prototype.markAsLightDirty = function () {
  25126. this._areLightsDirty = true;
  25127. this._isDirty = true;
  25128. };
  25129. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25130. this._areAttributesDirty = true;
  25131. this._isDirty = true;
  25132. };
  25133. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25134. this._areTexturesDirty = true;
  25135. this._isDirty = true;
  25136. };
  25137. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25138. this._areFresnelDirty = true;
  25139. this._isDirty = true;
  25140. };
  25141. MaterialDefines.prototype.markAsMiscDirty = function () {
  25142. this._areMiscDirty = true;
  25143. this._isDirty = true;
  25144. };
  25145. MaterialDefines.prototype.rebuild = function () {
  25146. if (this._keys) {
  25147. delete this._keys;
  25148. }
  25149. this._keys = [];
  25150. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25151. var key = _a[_i];
  25152. if (key[0] === "_") {
  25153. continue;
  25154. }
  25155. this._keys.push(key);
  25156. }
  25157. };
  25158. MaterialDefines.prototype.isEqual = function (other) {
  25159. if (this._keys.length !== other._keys.length) {
  25160. return false;
  25161. }
  25162. for (var index = 0; index < this._keys.length; index++) {
  25163. var prop = this._keys[index];
  25164. if (this[prop] !== other[prop]) {
  25165. return false;
  25166. }
  25167. }
  25168. return true;
  25169. };
  25170. MaterialDefines.prototype.cloneTo = function (other) {
  25171. if (this._keys.length !== other._keys.length) {
  25172. other._keys = this._keys.slice(0);
  25173. }
  25174. for (var index = 0; index < this._keys.length; index++) {
  25175. var prop = this._keys[index];
  25176. other[prop] = this[prop];
  25177. }
  25178. };
  25179. MaterialDefines.prototype.reset = function () {
  25180. for (var index = 0; index < this._keys.length; index++) {
  25181. var prop = this._keys[index];
  25182. if (typeof (this[prop]) === "number") {
  25183. this[prop] = 0;
  25184. }
  25185. else {
  25186. this[prop] = false;
  25187. }
  25188. }
  25189. };
  25190. MaterialDefines.prototype.toString = function () {
  25191. var result = "";
  25192. for (var index = 0; index < this._keys.length; index++) {
  25193. var prop = this._keys[index];
  25194. var value = this[prop];
  25195. if (typeof (value) === "number") {
  25196. result += "#define " + prop + " " + this[prop] + "\n";
  25197. }
  25198. else if (value) {
  25199. result += "#define " + prop + "\n";
  25200. }
  25201. }
  25202. return result;
  25203. };
  25204. return MaterialDefines;
  25205. }());
  25206. BABYLON.MaterialDefines = MaterialDefines;
  25207. var Material = (function () {
  25208. function Material(name, scene, doNotAdd) {
  25209. this.checkReadyOnEveryCall = false;
  25210. this.checkReadyOnlyOnce = false;
  25211. this.state = "";
  25212. this.alpha = 1.0;
  25213. this._backFaceCulling = true;
  25214. this.doNotSerialize = false;
  25215. this.storeEffectOnSubMeshes = false;
  25216. /**
  25217. * An event triggered when the material is disposed.
  25218. * @type {BABYLON.Observable}
  25219. */
  25220. this.onDisposeObservable = new BABYLON.Observable();
  25221. /**
  25222. * An event triggered when the material is bound.
  25223. * @type {BABYLON.Observable}
  25224. */
  25225. this.onBindObservable = new BABYLON.Observable();
  25226. /**
  25227. * An event triggered when the material is unbound.
  25228. * @type {BABYLON.Observable}
  25229. */
  25230. this.onUnBindObservable = new BABYLON.Observable();
  25231. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25232. this.disableDepthWrite = false;
  25233. this._fogEnabled = true;
  25234. this.pointSize = 1.0;
  25235. this.zOffset = 0;
  25236. this._wasPreviouslyReady = false;
  25237. this._fillMode = Material.TriangleFillMode;
  25238. this.name = name;
  25239. this.id = name || BABYLON.Tools.RandomId();
  25240. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25241. if (this._scene.useRightHandedSystem) {
  25242. this.sideOrientation = Material.ClockWiseSideOrientation;
  25243. }
  25244. else {
  25245. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25246. }
  25247. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25248. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25249. if (!doNotAdd) {
  25250. this._scene.materials.push(this);
  25251. }
  25252. }
  25253. Object.defineProperty(Material, "TriangleFillMode", {
  25254. get: function () {
  25255. return Material._TriangleFillMode;
  25256. },
  25257. enumerable: true,
  25258. configurable: true
  25259. });
  25260. Object.defineProperty(Material, "WireFrameFillMode", {
  25261. get: function () {
  25262. return Material._WireFrameFillMode;
  25263. },
  25264. enumerable: true,
  25265. configurable: true
  25266. });
  25267. Object.defineProperty(Material, "PointFillMode", {
  25268. get: function () {
  25269. return Material._PointFillMode;
  25270. },
  25271. enumerable: true,
  25272. configurable: true
  25273. });
  25274. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25275. get: function () {
  25276. return Material._ClockWiseSideOrientation;
  25277. },
  25278. enumerable: true,
  25279. configurable: true
  25280. });
  25281. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25282. get: function () {
  25283. return Material._CounterClockWiseSideOrientation;
  25284. },
  25285. enumerable: true,
  25286. configurable: true
  25287. });
  25288. Object.defineProperty(Material, "TextureDirtyFlag", {
  25289. get: function () {
  25290. return Material._TextureDirtyFlag;
  25291. },
  25292. enumerable: true,
  25293. configurable: true
  25294. });
  25295. Object.defineProperty(Material, "LightDirtyFlag", {
  25296. get: function () {
  25297. return Material._LightDirtyFlag;
  25298. },
  25299. enumerable: true,
  25300. configurable: true
  25301. });
  25302. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25303. get: function () {
  25304. return Material._FresnelDirtyFlag;
  25305. },
  25306. enumerable: true,
  25307. configurable: true
  25308. });
  25309. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25310. get: function () {
  25311. return Material._AttributesDirtyFlag;
  25312. },
  25313. enumerable: true,
  25314. configurable: true
  25315. });
  25316. Object.defineProperty(Material, "MiscDirtyFlag", {
  25317. get: function () {
  25318. return Material._MiscDirtyFlag;
  25319. },
  25320. enumerable: true,
  25321. configurable: true
  25322. });
  25323. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25324. get: function () {
  25325. return this._backFaceCulling;
  25326. },
  25327. set: function (value) {
  25328. if (this._backFaceCulling === value) {
  25329. return;
  25330. }
  25331. this._backFaceCulling = value;
  25332. this.markAsDirty(Material.TextureDirtyFlag);
  25333. },
  25334. enumerable: true,
  25335. configurable: true
  25336. });
  25337. Object.defineProperty(Material.prototype, "onDispose", {
  25338. set: function (callback) {
  25339. if (this._onDisposeObserver) {
  25340. this.onDisposeObservable.remove(this._onDisposeObserver);
  25341. }
  25342. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25343. },
  25344. enumerable: true,
  25345. configurable: true
  25346. });
  25347. Object.defineProperty(Material.prototype, "onBind", {
  25348. set: function (callback) {
  25349. if (this._onBindObserver) {
  25350. this.onBindObservable.remove(this._onBindObserver);
  25351. }
  25352. this._onBindObserver = this.onBindObservable.add(callback);
  25353. },
  25354. enumerable: true,
  25355. configurable: true
  25356. });
  25357. Object.defineProperty(Material.prototype, "fogEnabled", {
  25358. get: function () {
  25359. return this._fogEnabled;
  25360. },
  25361. set: function (value) {
  25362. if (this._fogEnabled === value) {
  25363. return;
  25364. }
  25365. this._fogEnabled = value;
  25366. this.markAsDirty(Material.MiscDirtyFlag);
  25367. },
  25368. enumerable: true,
  25369. configurable: true
  25370. });
  25371. Object.defineProperty(Material.prototype, "wireframe", {
  25372. get: function () {
  25373. return this._fillMode === Material.WireFrameFillMode;
  25374. },
  25375. set: function (value) {
  25376. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25377. },
  25378. enumerable: true,
  25379. configurable: true
  25380. });
  25381. Object.defineProperty(Material.prototype, "pointsCloud", {
  25382. get: function () {
  25383. return this._fillMode === Material.PointFillMode;
  25384. },
  25385. set: function (value) {
  25386. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25387. },
  25388. enumerable: true,
  25389. configurable: true
  25390. });
  25391. Object.defineProperty(Material.prototype, "fillMode", {
  25392. get: function () {
  25393. return this._fillMode;
  25394. },
  25395. set: function (value) {
  25396. if (this._fillMode === value) {
  25397. return;
  25398. }
  25399. this._fillMode = value;
  25400. this.markAsDirty(Material.MiscDirtyFlag);
  25401. },
  25402. enumerable: true,
  25403. configurable: true
  25404. });
  25405. /**
  25406. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25407. * subclasses should override adding information pertainent to themselves
  25408. */
  25409. Material.prototype.toString = function (fullDetails) {
  25410. var ret = "Name: " + this.name;
  25411. if (fullDetails) {
  25412. }
  25413. return ret;
  25414. };
  25415. /**
  25416. * Child classes can use it to update shaders
  25417. */
  25418. Material.prototype.getClassName = function () {
  25419. return "Material";
  25420. };
  25421. Object.defineProperty(Material.prototype, "isFrozen", {
  25422. get: function () {
  25423. return this.checkReadyOnlyOnce;
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. Material.prototype.freeze = function () {
  25429. this.checkReadyOnlyOnce = true;
  25430. };
  25431. Material.prototype.unfreeze = function () {
  25432. this.checkReadyOnlyOnce = false;
  25433. };
  25434. Material.prototype.isReady = function (mesh, useInstances) {
  25435. return true;
  25436. };
  25437. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25438. return false;
  25439. };
  25440. Material.prototype.getEffect = function () {
  25441. return this._effect;
  25442. };
  25443. Material.prototype.getScene = function () {
  25444. return this._scene;
  25445. };
  25446. Material.prototype.needAlphaBlending = function () {
  25447. return (this.alpha < 1.0);
  25448. };
  25449. Material.prototype.needAlphaTesting = function () {
  25450. return false;
  25451. };
  25452. Material.prototype.getAlphaTestTexture = function () {
  25453. return null;
  25454. };
  25455. Material.prototype.markDirty = function () {
  25456. this._wasPreviouslyReady = false;
  25457. };
  25458. Material.prototype._preBind = function (effect) {
  25459. var engine = this._scene.getEngine();
  25460. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25461. engine.enableEffect(effect ? effect : this._effect);
  25462. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25463. };
  25464. Material.prototype.bind = function (world, mesh) {
  25465. };
  25466. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25467. };
  25468. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25469. };
  25470. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25471. sceneUbo.bindToEffect(effect, "Scene");
  25472. };
  25473. Material.prototype.bindView = function (effect) {
  25474. if (!this._useUBO) {
  25475. effect.setMatrix("view", this.getScene().getViewMatrix());
  25476. }
  25477. else {
  25478. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25479. }
  25480. };
  25481. Material.prototype.bindViewProjection = function (effect) {
  25482. if (!this._useUBO) {
  25483. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25484. }
  25485. else {
  25486. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25487. }
  25488. };
  25489. Material.prototype._afterBind = function (mesh) {
  25490. this._scene._cachedMaterial = this;
  25491. if (mesh) {
  25492. this._scene._cachedVisibility = mesh.visibility;
  25493. }
  25494. else {
  25495. this._scene._cachedVisibility = 1;
  25496. }
  25497. this.onBindObservable.notifyObservers(mesh);
  25498. if (this.disableDepthWrite) {
  25499. var engine = this._scene.getEngine();
  25500. this._cachedDepthWriteState = engine.getDepthWrite();
  25501. engine.setDepthWrite(false);
  25502. }
  25503. };
  25504. Material.prototype.unbind = function () {
  25505. this.onUnBindObservable.notifyObservers(this);
  25506. if (this.disableDepthWrite) {
  25507. var engine = this._scene.getEngine();
  25508. engine.setDepthWrite(this._cachedDepthWriteState);
  25509. }
  25510. };
  25511. Material.prototype.getActiveTextures = function () {
  25512. return [];
  25513. };
  25514. Material.prototype.hasTexture = function (texture) {
  25515. return false;
  25516. };
  25517. Material.prototype.clone = function (name) {
  25518. return null;
  25519. };
  25520. Material.prototype.getBindedMeshes = function () {
  25521. var result = new Array();
  25522. for (var index = 0; index < this._scene.meshes.length; index++) {
  25523. var mesh = this._scene.meshes[index];
  25524. if (mesh.material === this) {
  25525. result.push(mesh);
  25526. }
  25527. }
  25528. return result;
  25529. };
  25530. /**
  25531. * Force shader compilation including textures ready check
  25532. */
  25533. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25534. var _this = this;
  25535. var subMesh = new BABYLON.BaseSubMesh();
  25536. var scene = this.getScene();
  25537. var engine = scene.getEngine();
  25538. var checkReady = function () {
  25539. if (!_this._scene || !_this._scene.getEngine()) {
  25540. return;
  25541. }
  25542. if (subMesh._materialDefines) {
  25543. subMesh._materialDefines._renderId = -1;
  25544. }
  25545. var alphaTestState = engine.getAlphaTesting();
  25546. var clipPlaneState = scene.clipPlane;
  25547. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25548. if (options && options.clipPlane) {
  25549. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25550. }
  25551. if (_this.storeEffectOnSubMeshes) {
  25552. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25553. if (onCompiled) {
  25554. onCompiled(_this);
  25555. }
  25556. }
  25557. else {
  25558. setTimeout(checkReady, 16);
  25559. }
  25560. }
  25561. else {
  25562. if (_this.isReady(mesh)) {
  25563. if (onCompiled) {
  25564. onCompiled(_this);
  25565. }
  25566. }
  25567. else {
  25568. setTimeout(checkReady, 16);
  25569. }
  25570. }
  25571. engine.setAlphaTesting(alphaTestState);
  25572. if (options && options.clipPlane) {
  25573. scene.clipPlane = clipPlaneState;
  25574. }
  25575. };
  25576. checkReady();
  25577. };
  25578. Material.prototype.markAsDirty = function (flag) {
  25579. if (flag & Material.TextureDirtyFlag) {
  25580. this._markAllSubMeshesAsTexturesDirty();
  25581. }
  25582. if (flag & Material.LightDirtyFlag) {
  25583. this._markAllSubMeshesAsLightsDirty();
  25584. }
  25585. if (flag & Material.FresnelDirtyFlag) {
  25586. this._markAllSubMeshesAsFresnelDirty();
  25587. }
  25588. if (flag & Material.AttributesDirtyFlag) {
  25589. this._markAllSubMeshesAsAttributesDirty();
  25590. }
  25591. if (flag & Material.MiscDirtyFlag) {
  25592. this._markAllSubMeshesAsMiscDirty();
  25593. }
  25594. this.getScene().resetCachedMaterial();
  25595. };
  25596. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25597. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25598. var mesh = _a[_i];
  25599. if (!mesh.subMeshes) {
  25600. continue;
  25601. }
  25602. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25603. var subMesh = _c[_b];
  25604. if (subMesh.getMaterial() !== this) {
  25605. continue;
  25606. }
  25607. if (!subMesh._materialDefines) {
  25608. continue;
  25609. }
  25610. func(subMesh._materialDefines);
  25611. }
  25612. }
  25613. };
  25614. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25615. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25616. };
  25617. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25618. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25619. };
  25620. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25621. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25622. };
  25623. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25624. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25625. };
  25626. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25627. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25628. };
  25629. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25630. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25631. };
  25632. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25633. // Animations
  25634. this.getScene().stopAnimation(this);
  25635. // Remove from scene
  25636. var index = this._scene.materials.indexOf(this);
  25637. if (index >= 0) {
  25638. this._scene.materials.splice(index, 1);
  25639. }
  25640. // Remove from meshes
  25641. for (index = 0; index < this._scene.meshes.length; index++) {
  25642. var mesh = this._scene.meshes[index];
  25643. if (mesh.material === this) {
  25644. mesh.material = null;
  25645. if (mesh.geometry) {
  25646. var geometry = mesh.geometry;
  25647. if (this.storeEffectOnSubMeshes) {
  25648. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25649. var subMesh = _a[_i];
  25650. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25651. }
  25652. }
  25653. else {
  25654. geometry._releaseVertexArrayObject(this._effect);
  25655. }
  25656. }
  25657. }
  25658. }
  25659. this._uniformBuffer.dispose();
  25660. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25661. if (forceDisposeEffect && this._effect) {
  25662. if (this.storeEffectOnSubMeshes) {
  25663. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25664. var subMesh = _c[_b];
  25665. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25666. }
  25667. }
  25668. else {
  25669. this._scene.getEngine()._releaseEffect(this._effect);
  25670. }
  25671. this._effect = null;
  25672. }
  25673. // Callback
  25674. this.onDisposeObservable.notifyObservers(this);
  25675. this.onDisposeObservable.clear();
  25676. this.onBindObservable.clear();
  25677. this.onUnBindObservable.clear();
  25678. };
  25679. Material.prototype.serialize = function () {
  25680. return BABYLON.SerializationHelper.Serialize(this);
  25681. };
  25682. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25683. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25684. multiMaterial.id = parsedMultiMaterial.id;
  25685. if (BABYLON.Tags) {
  25686. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25687. }
  25688. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25689. var subMatId = parsedMultiMaterial.materials[matIndex];
  25690. if (subMatId) {
  25691. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25692. }
  25693. else {
  25694. multiMaterial.subMaterials.push(null);
  25695. }
  25696. }
  25697. return multiMaterial;
  25698. };
  25699. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25700. if (!parsedMaterial.customType) {
  25701. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25702. }
  25703. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25704. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25705. if (!BABYLON.LegacyPBRMaterial) {
  25706. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25707. return;
  25708. }
  25709. }
  25710. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25711. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25712. ;
  25713. };
  25714. Material._TriangleFillMode = 0;
  25715. Material._WireFrameFillMode = 1;
  25716. Material._PointFillMode = 2;
  25717. Material._ClockWiseSideOrientation = 0;
  25718. Material._CounterClockWiseSideOrientation = 1;
  25719. Material._TextureDirtyFlag = 1;
  25720. Material._LightDirtyFlag = 2;
  25721. Material._FresnelDirtyFlag = 4;
  25722. Material._AttributesDirtyFlag = 8;
  25723. Material._MiscDirtyFlag = 16;
  25724. __decorate([
  25725. BABYLON.serialize()
  25726. ], Material.prototype, "id", void 0);
  25727. __decorate([
  25728. BABYLON.serialize()
  25729. ], Material.prototype, "name", void 0);
  25730. __decorate([
  25731. BABYLON.serialize()
  25732. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25733. __decorate([
  25734. BABYLON.serialize()
  25735. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25736. __decorate([
  25737. BABYLON.serialize()
  25738. ], Material.prototype, "state", void 0);
  25739. __decorate([
  25740. BABYLON.serialize()
  25741. ], Material.prototype, "alpha", void 0);
  25742. __decorate([
  25743. BABYLON.serialize("backFaceCulling")
  25744. ], Material.prototype, "_backFaceCulling", void 0);
  25745. __decorate([
  25746. BABYLON.serialize()
  25747. ], Material.prototype, "sideOrientation", void 0);
  25748. __decorate([
  25749. BABYLON.serialize()
  25750. ], Material.prototype, "alphaMode", void 0);
  25751. __decorate([
  25752. BABYLON.serialize()
  25753. ], Material.prototype, "disableDepthWrite", void 0);
  25754. __decorate([
  25755. BABYLON.serialize("fogEnabled")
  25756. ], Material.prototype, "_fogEnabled", void 0);
  25757. __decorate([
  25758. BABYLON.serialize()
  25759. ], Material.prototype, "pointSize", void 0);
  25760. __decorate([
  25761. BABYLON.serialize()
  25762. ], Material.prototype, "zOffset", void 0);
  25763. __decorate([
  25764. BABYLON.serialize()
  25765. ], Material.prototype, "wireframe", null);
  25766. __decorate([
  25767. BABYLON.serialize()
  25768. ], Material.prototype, "pointsCloud", null);
  25769. __decorate([
  25770. BABYLON.serialize()
  25771. ], Material.prototype, "fillMode", null);
  25772. return Material;
  25773. }());
  25774. BABYLON.Material = Material;
  25775. })(BABYLON || (BABYLON = {}));
  25776. //# sourceMappingURL=babylon.material.js.map
  25777. var BABYLON;
  25778. (function (BABYLON) {
  25779. var UniformBuffer = (function () {
  25780. /**
  25781. * Uniform buffer objects.
  25782. *
  25783. * Handles blocks of uniform on the GPU.
  25784. *
  25785. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25786. *
  25787. * For more information, please refer to :
  25788. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25789. */
  25790. function UniformBuffer(engine, data, dynamic) {
  25791. this._engine = engine;
  25792. this._noUBO = !engine.supportsUniformBuffers;
  25793. this._dynamic = dynamic;
  25794. this._data = data || [];
  25795. this._uniformLocations = {};
  25796. this._uniformSizes = {};
  25797. this._uniformLocationPointer = 0;
  25798. this._needSync = false;
  25799. if (this._noUBO) {
  25800. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25801. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25802. this.updateFloat = this._updateFloatForEffect;
  25803. this.updateFloat2 = this._updateFloat2ForEffect;
  25804. this.updateFloat3 = this._updateFloat3ForEffect;
  25805. this.updateFloat4 = this._updateFloat4ForEffect;
  25806. this.updateMatrix = this._updateMatrixForEffect;
  25807. this.updateVector3 = this._updateVector3ForEffect;
  25808. this.updateVector4 = this._updateVector4ForEffect;
  25809. this.updateColor3 = this._updateColor3ForEffect;
  25810. this.updateColor4 = this._updateColor4ForEffect;
  25811. }
  25812. else {
  25813. this._engine._uniformBuffers.push(this);
  25814. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25815. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25816. this.updateFloat = this._updateFloatForUniform;
  25817. this.updateFloat2 = this._updateFloat2ForUniform;
  25818. this.updateFloat3 = this._updateFloat3ForUniform;
  25819. this.updateFloat4 = this._updateFloat4ForUniform;
  25820. this.updateMatrix = this._updateMatrixForUniform;
  25821. this.updateVector3 = this._updateVector3ForUniform;
  25822. this.updateVector4 = this._updateVector4ForUniform;
  25823. this.updateColor3 = this._updateColor3ForUniform;
  25824. this.updateColor4 = this._updateColor4ForUniform;
  25825. }
  25826. }
  25827. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25828. // Properties
  25829. /**
  25830. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25831. * or just falling back on setUniformXXX calls.
  25832. */
  25833. get: function () {
  25834. return !this._noUBO;
  25835. },
  25836. enumerable: true,
  25837. configurable: true
  25838. });
  25839. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25840. /**
  25841. * Indicates if the WebGL underlying uniform buffer is in sync
  25842. * with the javascript cache data.
  25843. */
  25844. get: function () {
  25845. return !this._needSync;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. /**
  25851. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25852. * Also, a dynamic UniformBuffer will disable cache verification and always
  25853. * update the underlying WebGL uniform buffer to the GPU.
  25854. */
  25855. UniformBuffer.prototype.isDynamic = function () {
  25856. return this._dynamic;
  25857. };
  25858. /**
  25859. * The data cache on JS side.
  25860. */
  25861. UniformBuffer.prototype.getData = function () {
  25862. return this._bufferData;
  25863. };
  25864. /**
  25865. * The underlying WebGL Uniform buffer.
  25866. */
  25867. UniformBuffer.prototype.getBuffer = function () {
  25868. return this._buffer;
  25869. };
  25870. /**
  25871. * std140 layout specifies how to align data within an UBO structure.
  25872. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25873. * for specs.
  25874. */
  25875. UniformBuffer.prototype._fillAlignment = function (size) {
  25876. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25877. // and 4x4 matrices
  25878. // TODO : change if other types are used
  25879. var alignment;
  25880. if (size <= 2) {
  25881. alignment = size;
  25882. }
  25883. else {
  25884. alignment = 4;
  25885. }
  25886. if ((this._uniformLocationPointer % alignment) !== 0) {
  25887. var oldPointer = this._uniformLocationPointer;
  25888. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25889. var diff = this._uniformLocationPointer - oldPointer;
  25890. for (var i = 0; i < diff; i++) {
  25891. this._data.push(0);
  25892. }
  25893. }
  25894. };
  25895. /**
  25896. * Adds an uniform in the buffer.
  25897. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25898. * for the layout to be correct !
  25899. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25900. * @param {number|number[]} size Data size, or data directly.
  25901. */
  25902. UniformBuffer.prototype.addUniform = function (name, size) {
  25903. if (this._noUBO) {
  25904. return;
  25905. }
  25906. if (this._uniformLocations[name] !== undefined) {
  25907. // Already existing uniform
  25908. return;
  25909. }
  25910. // This function must be called in the order of the shader layout !
  25911. // size can be the size of the uniform, or data directly
  25912. var data;
  25913. if (size instanceof Array) {
  25914. data = size;
  25915. size = data.length;
  25916. }
  25917. else {
  25918. size = size;
  25919. data = [];
  25920. // Fill with zeros
  25921. for (var i = 0; i < size; i++) {
  25922. data.push(0);
  25923. }
  25924. }
  25925. this._fillAlignment(size);
  25926. this._uniformSizes[name] = size;
  25927. this._uniformLocations[name] = this._uniformLocationPointer;
  25928. this._uniformLocationPointer += size;
  25929. for (var i = 0; i < size; i++) {
  25930. this._data.push(data[i]);
  25931. }
  25932. this._needSync = true;
  25933. };
  25934. /**
  25935. * Wrapper for addUniform.
  25936. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25937. * @param {Matrix} mat A 4x4 matrix.
  25938. */
  25939. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25940. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25941. };
  25942. /**
  25943. * Wrapper for addUniform.
  25944. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25945. * @param {number} x
  25946. * @param {number} y
  25947. */
  25948. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25949. var temp = [x, y];
  25950. this.addUniform(name, temp);
  25951. };
  25952. /**
  25953. * Wrapper for addUniform.
  25954. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25955. * @param {number} x
  25956. * @param {number} y
  25957. * @param {number} z
  25958. */
  25959. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25960. var temp = [x, y, z];
  25961. this.addUniform(name, temp);
  25962. };
  25963. /**
  25964. * Wrapper for addUniform.
  25965. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25966. * @param {Color3} color
  25967. */
  25968. UniformBuffer.prototype.addColor3 = function (name, color) {
  25969. var temp = [];
  25970. color.toArray(temp);
  25971. this.addUniform(name, temp);
  25972. };
  25973. /**
  25974. * Wrapper for addUniform.
  25975. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25976. * @param {Color3} color
  25977. * @param {number} alpha
  25978. */
  25979. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25980. var temp = [];
  25981. color.toArray(temp);
  25982. temp.push(alpha);
  25983. this.addUniform(name, temp);
  25984. };
  25985. /**
  25986. * Wrapper for addUniform.
  25987. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25988. * @param {Vector3} vector
  25989. */
  25990. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25991. var temp = [];
  25992. vector.toArray(temp);
  25993. this.addUniform(name, temp);
  25994. };
  25995. /**
  25996. * Wrapper for addUniform.
  25997. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25998. */
  25999. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26000. this.addUniform(name, 12);
  26001. };
  26002. /**
  26003. * Wrapper for addUniform.
  26004. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26005. */
  26006. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26007. this.addUniform(name, 8);
  26008. };
  26009. /**
  26010. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26011. */
  26012. UniformBuffer.prototype.create = function () {
  26013. if (this._noUBO) {
  26014. return;
  26015. }
  26016. if (this._buffer) {
  26017. return; // nothing to do
  26018. }
  26019. // See spec, alignment must be filled as a vec4
  26020. this._fillAlignment(4);
  26021. this._bufferData = new Float32Array(this._data);
  26022. this._rebuild();
  26023. this._needSync = true;
  26024. };
  26025. UniformBuffer.prototype._rebuild = function () {
  26026. if (this._noUBO) {
  26027. return;
  26028. }
  26029. if (this._dynamic) {
  26030. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26031. }
  26032. else {
  26033. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26034. }
  26035. };
  26036. /**
  26037. * Updates the WebGL Uniform Buffer on the GPU.
  26038. * If the `dynamic` flag is set to true, no cache comparison is done.
  26039. * Otherwise, the buffer will be updated only if the cache differs.
  26040. */
  26041. UniformBuffer.prototype.update = function () {
  26042. if (!this._buffer) {
  26043. this.create();
  26044. return;
  26045. }
  26046. if (!this._dynamic && !this._needSync) {
  26047. return;
  26048. }
  26049. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26050. this._needSync = false;
  26051. };
  26052. /**
  26053. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26054. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26055. * @param {number[]|Float32Array} data Flattened data
  26056. * @param {number} size Size of the data.
  26057. */
  26058. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26059. var location = this._uniformLocations[uniformName];
  26060. if (location === undefined) {
  26061. if (this._buffer) {
  26062. // Cannot add an uniform if the buffer is already created
  26063. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26064. return;
  26065. }
  26066. this.addUniform(uniformName, size);
  26067. location = this._uniformLocations[uniformName];
  26068. }
  26069. if (!this._buffer) {
  26070. this.create();
  26071. }
  26072. if (!this._dynamic) {
  26073. // Cache for static uniform buffers
  26074. var changed = false;
  26075. for (var i = 0; i < size; i++) {
  26076. if (this._bufferData[location + i] !== data[i]) {
  26077. changed = true;
  26078. this._bufferData[location + i] = data[i];
  26079. }
  26080. }
  26081. this._needSync = this._needSync || changed;
  26082. }
  26083. else {
  26084. // No cache for dynamic
  26085. for (var i = 0; i < size; i++) {
  26086. this._bufferData[location + i] = data[i];
  26087. }
  26088. }
  26089. };
  26090. // Update methods
  26091. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26092. // To match std140, matrix must be realigned
  26093. for (var i = 0; i < 3; i++) {
  26094. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26095. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26096. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26097. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26098. }
  26099. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26100. };
  26101. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26102. this._currentEffect.setMatrix3x3(name, matrix);
  26103. };
  26104. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26105. this._currentEffect.setMatrix2x2(name, matrix);
  26106. };
  26107. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26108. // To match std140, matrix must be realigned
  26109. for (var i = 0; i < 2; i++) {
  26110. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26111. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26112. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26113. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26114. }
  26115. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26116. };
  26117. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26118. this._currentEffect.setFloat(name, x);
  26119. };
  26120. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26121. UniformBuffer._tempBuffer[0] = x;
  26122. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26123. };
  26124. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26125. if (suffix === void 0) { suffix = ""; }
  26126. this._currentEffect.setFloat2(name + suffix, x, y);
  26127. };
  26128. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26129. if (suffix === void 0) { suffix = ""; }
  26130. UniformBuffer._tempBuffer[0] = x;
  26131. UniformBuffer._tempBuffer[1] = y;
  26132. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26133. };
  26134. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26135. if (suffix === void 0) { suffix = ""; }
  26136. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26137. };
  26138. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26139. if (suffix === void 0) { suffix = ""; }
  26140. UniformBuffer._tempBuffer[0] = x;
  26141. UniformBuffer._tempBuffer[1] = y;
  26142. UniformBuffer._tempBuffer[2] = z;
  26143. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26144. };
  26145. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26146. if (suffix === void 0) { suffix = ""; }
  26147. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26148. };
  26149. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26150. if (suffix === void 0) { suffix = ""; }
  26151. UniformBuffer._tempBuffer[0] = x;
  26152. UniformBuffer._tempBuffer[1] = y;
  26153. UniformBuffer._tempBuffer[2] = z;
  26154. UniformBuffer._tempBuffer[3] = w;
  26155. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26156. };
  26157. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26158. this._currentEffect.setMatrix(name, mat);
  26159. };
  26160. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26161. this.updateUniform(name, mat.toArray(), 16);
  26162. };
  26163. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26164. this._currentEffect.setVector3(name, vector);
  26165. };
  26166. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26167. vector.toArray(UniformBuffer._tempBuffer);
  26168. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26169. };
  26170. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26171. this._currentEffect.setVector4(name, vector);
  26172. };
  26173. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26174. vector.toArray(UniformBuffer._tempBuffer);
  26175. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26176. };
  26177. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26178. if (suffix === void 0) { suffix = ""; }
  26179. this._currentEffect.setColor3(name + suffix, color);
  26180. };
  26181. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26182. if (suffix === void 0) { suffix = ""; }
  26183. color.toArray(UniformBuffer._tempBuffer);
  26184. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26185. };
  26186. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26187. if (suffix === void 0) { suffix = ""; }
  26188. this._currentEffect.setColor4(name + suffix, color, alpha);
  26189. };
  26190. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26191. if (suffix === void 0) { suffix = ""; }
  26192. color.toArray(UniformBuffer._tempBuffer);
  26193. UniformBuffer._tempBuffer[3] = alpha;
  26194. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26195. };
  26196. /**
  26197. * Sets a sampler uniform on the effect.
  26198. * @param {string} name Name of the sampler.
  26199. * @param {Texture} texture
  26200. */
  26201. UniformBuffer.prototype.setTexture = function (name, texture) {
  26202. this._currentEffect.setTexture(name, texture);
  26203. };
  26204. /**
  26205. * Directly updates the value of the uniform in the cache AND on the GPU.
  26206. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26207. * @param {number[]|Float32Array} data Flattened data
  26208. */
  26209. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26210. this.updateUniform(uniformName, data, data.length);
  26211. this.update();
  26212. };
  26213. /**
  26214. * Binds this uniform buffer to an effect.
  26215. * @param {Effect} effect
  26216. * @param {string} name Name of the uniform block in the shader.
  26217. */
  26218. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26219. this._currentEffect = effect;
  26220. if (this._noUBO) {
  26221. return;
  26222. }
  26223. effect.bindUniformBuffer(this._buffer, name);
  26224. };
  26225. /**
  26226. * Disposes the uniform buffer.
  26227. */
  26228. UniformBuffer.prototype.dispose = function () {
  26229. if (this._noUBO) {
  26230. return;
  26231. }
  26232. var index = this._engine._uniformBuffers.indexOf(this);
  26233. if (index !== -1) {
  26234. this._engine._uniformBuffers.splice(index, 1);
  26235. }
  26236. if (!this._buffer) {
  26237. return;
  26238. }
  26239. if (this._engine._releaseBuffer(this._buffer)) {
  26240. this._buffer = null;
  26241. }
  26242. };
  26243. // Pool for avoiding memory leaks
  26244. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26245. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26246. return UniformBuffer;
  26247. }());
  26248. BABYLON.UniformBuffer = UniformBuffer;
  26249. })(BABYLON || (BABYLON = {}));
  26250. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26251. var BABYLON;
  26252. (function (BABYLON) {
  26253. var PushMaterial = (function (_super) {
  26254. __extends(PushMaterial, _super);
  26255. function PushMaterial(name, scene) {
  26256. var _this = _super.call(this, name, scene) || this;
  26257. _this.storeEffectOnSubMeshes = true;
  26258. return _this;
  26259. }
  26260. PushMaterial.prototype.getEffect = function () {
  26261. return this._activeEffect;
  26262. };
  26263. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26264. if (!mesh) {
  26265. return false;
  26266. }
  26267. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26268. return true;
  26269. }
  26270. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26271. };
  26272. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26273. this._activeEffect.setMatrix("world", world);
  26274. };
  26275. PushMaterial.prototype.bind = function (world, mesh) {
  26276. if (!mesh) {
  26277. return;
  26278. }
  26279. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26280. };
  26281. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26282. _super.prototype._afterBind.call(this, mesh);
  26283. this.getScene()._cachedEffect = effect;
  26284. };
  26285. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26286. if (visibility === void 0) { visibility = 1; }
  26287. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26288. };
  26289. return PushMaterial;
  26290. }(BABYLON.Material));
  26291. BABYLON.PushMaterial = PushMaterial;
  26292. })(BABYLON || (BABYLON = {}));
  26293. //# sourceMappingURL=babylon.pushMaterial.js.map
  26294. var BABYLON;
  26295. (function (BABYLON) {
  26296. var VertexData = (function () {
  26297. function VertexData() {
  26298. }
  26299. VertexData.prototype.set = function (data, kind) {
  26300. switch (kind) {
  26301. case BABYLON.VertexBuffer.PositionKind:
  26302. this.positions = data;
  26303. break;
  26304. case BABYLON.VertexBuffer.NormalKind:
  26305. this.normals = data;
  26306. break;
  26307. case BABYLON.VertexBuffer.TangentKind:
  26308. this.tangents = data;
  26309. break;
  26310. case BABYLON.VertexBuffer.UVKind:
  26311. this.uvs = data;
  26312. break;
  26313. case BABYLON.VertexBuffer.UV2Kind:
  26314. this.uvs2 = data;
  26315. break;
  26316. case BABYLON.VertexBuffer.UV3Kind:
  26317. this.uvs3 = data;
  26318. break;
  26319. case BABYLON.VertexBuffer.UV4Kind:
  26320. this.uvs4 = data;
  26321. break;
  26322. case BABYLON.VertexBuffer.UV5Kind:
  26323. this.uvs5 = data;
  26324. break;
  26325. case BABYLON.VertexBuffer.UV6Kind:
  26326. this.uvs6 = data;
  26327. break;
  26328. case BABYLON.VertexBuffer.ColorKind:
  26329. this.colors = data;
  26330. break;
  26331. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26332. this.matricesIndices = data;
  26333. break;
  26334. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26335. this.matricesWeights = data;
  26336. break;
  26337. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26338. this.matricesIndicesExtra = data;
  26339. break;
  26340. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26341. this.matricesWeightsExtra = data;
  26342. break;
  26343. }
  26344. };
  26345. /**
  26346. * Associates the vertexData to the passed Mesh.
  26347. * Sets it as updatable or not (default `false`).
  26348. * Returns the VertexData.
  26349. */
  26350. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26351. this._applyTo(mesh, updatable);
  26352. return this;
  26353. };
  26354. /**
  26355. * Associates the vertexData to the passed Geometry.
  26356. * Sets it as updatable or not (default `false`).
  26357. * Returns the VertexData.
  26358. */
  26359. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26360. this._applyTo(geometry, updatable);
  26361. return this;
  26362. };
  26363. /**
  26364. * Updates the associated mesh.
  26365. * Returns the VertexData.
  26366. */
  26367. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26368. this._update(mesh);
  26369. return this;
  26370. };
  26371. /**
  26372. * Updates the associated geometry.
  26373. * Returns the VertexData.
  26374. */
  26375. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26376. this._update(geometry);
  26377. return this;
  26378. };
  26379. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26380. if (this.positions) {
  26381. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26382. }
  26383. if (this.normals) {
  26384. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26385. }
  26386. if (this.tangents) {
  26387. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26388. }
  26389. if (this.uvs) {
  26390. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26391. }
  26392. if (this.uvs2) {
  26393. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26394. }
  26395. if (this.uvs3) {
  26396. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26397. }
  26398. if (this.uvs4) {
  26399. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26400. }
  26401. if (this.uvs5) {
  26402. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26403. }
  26404. if (this.uvs6) {
  26405. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26406. }
  26407. if (this.colors) {
  26408. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26409. }
  26410. if (this.matricesIndices) {
  26411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26412. }
  26413. if (this.matricesWeights) {
  26414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26415. }
  26416. if (this.matricesIndicesExtra) {
  26417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26418. }
  26419. if (this.matricesWeightsExtra) {
  26420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26421. }
  26422. if (this.indices) {
  26423. meshOrGeometry.setIndices(this.indices);
  26424. }
  26425. return this;
  26426. };
  26427. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26428. if (this.positions) {
  26429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26430. }
  26431. if (this.normals) {
  26432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26433. }
  26434. if (this.tangents) {
  26435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26436. }
  26437. if (this.uvs) {
  26438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26439. }
  26440. if (this.uvs2) {
  26441. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26442. }
  26443. if (this.uvs3) {
  26444. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26445. }
  26446. if (this.uvs4) {
  26447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26448. }
  26449. if (this.uvs5) {
  26450. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26451. }
  26452. if (this.uvs6) {
  26453. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26454. }
  26455. if (this.colors) {
  26456. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26457. }
  26458. if (this.matricesIndices) {
  26459. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26460. }
  26461. if (this.matricesWeights) {
  26462. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26463. }
  26464. if (this.matricesIndicesExtra) {
  26465. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26466. }
  26467. if (this.matricesWeightsExtra) {
  26468. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26469. }
  26470. if (this.indices) {
  26471. meshOrGeometry.setIndices(this.indices);
  26472. }
  26473. return this;
  26474. };
  26475. /**
  26476. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26477. * Returns the VertexData.
  26478. */
  26479. VertexData.prototype.transform = function (matrix) {
  26480. var transformed = BABYLON.Vector3.Zero();
  26481. var index;
  26482. if (this.positions) {
  26483. var position = BABYLON.Vector3.Zero();
  26484. for (index = 0; index < this.positions.length; index += 3) {
  26485. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26486. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26487. this.positions[index] = transformed.x;
  26488. this.positions[index + 1] = transformed.y;
  26489. this.positions[index + 2] = transformed.z;
  26490. }
  26491. }
  26492. if (this.normals) {
  26493. var normal = BABYLON.Vector3.Zero();
  26494. for (index = 0; index < this.normals.length; index += 3) {
  26495. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26496. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26497. this.normals[index] = transformed.x;
  26498. this.normals[index + 1] = transformed.y;
  26499. this.normals[index + 2] = transformed.z;
  26500. }
  26501. }
  26502. if (this.tangents) {
  26503. var tangent = BABYLON.Vector4.Zero();
  26504. var tangentTransformed = BABYLON.Vector4.Zero();
  26505. for (index = 0; index < this.tangents.length; index += 4) {
  26506. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26507. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26508. this.tangents[index] = tangentTransformed.x;
  26509. this.tangents[index + 1] = tangentTransformed.y;
  26510. this.tangents[index + 2] = tangentTransformed.z;
  26511. this.tangents[index + 3] = tangentTransformed.w;
  26512. }
  26513. }
  26514. return this;
  26515. };
  26516. /**
  26517. * Merges the passed VertexData into the current one.
  26518. * Returns the modified VertexData.
  26519. */
  26520. VertexData.prototype.merge = function (other) {
  26521. if (other.indices) {
  26522. if (!this.indices) {
  26523. this.indices = [];
  26524. }
  26525. var offset = this.positions ? this.positions.length / 3 : 0;
  26526. for (var index = 0; index < other.indices.length; index++) {
  26527. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26528. this.indices.push(other.indices[index] + offset);
  26529. }
  26530. }
  26531. this.positions = this._mergeElement(this.positions, other.positions);
  26532. this.normals = this._mergeElement(this.normals, other.normals);
  26533. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26534. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26535. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26536. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26537. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26538. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26539. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26540. this.colors = this._mergeElement(this.colors, other.colors);
  26541. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26542. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26543. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26544. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26545. return this;
  26546. };
  26547. VertexData.prototype._mergeElement = function (source, other) {
  26548. if (!other)
  26549. return source;
  26550. if (!source)
  26551. return other;
  26552. var len = other.length + source.length;
  26553. var isSrcTypedArray = source instanceof Float32Array;
  26554. var isOthTypedArray = other instanceof Float32Array;
  26555. // use non-loop method when the source is Float32Array
  26556. if (isSrcTypedArray) {
  26557. var ret32 = new Float32Array(len);
  26558. ret32.set(source);
  26559. ret32.set(other, source.length);
  26560. return ret32;
  26561. // source is number[], when other is also use concat
  26562. }
  26563. else if (!isOthTypedArray) {
  26564. return source.concat(other);
  26565. // source is a number[], but other is a Float32Array, loop required
  26566. }
  26567. else {
  26568. var ret = source.slice(0); // copy source to a separate array
  26569. for (var i = 0, len = other.length; i < len; i++) {
  26570. ret.push(other[i]);
  26571. }
  26572. return ret;
  26573. }
  26574. };
  26575. /**
  26576. * Serializes the VertexData.
  26577. * Returns a serialized object.
  26578. */
  26579. VertexData.prototype.serialize = function () {
  26580. var serializationObject = this.serialize();
  26581. if (this.positions) {
  26582. serializationObject.positions = this.positions;
  26583. }
  26584. if (this.normals) {
  26585. serializationObject.normals = this.normals;
  26586. }
  26587. if (this.tangents) {
  26588. serializationObject.tangents = this.tangents;
  26589. }
  26590. if (this.uvs) {
  26591. serializationObject.uvs = this.uvs;
  26592. }
  26593. if (this.uvs2) {
  26594. serializationObject.uvs2 = this.uvs2;
  26595. }
  26596. if (this.uvs3) {
  26597. serializationObject.uvs3 = this.uvs3;
  26598. }
  26599. if (this.uvs4) {
  26600. serializationObject.uvs4 = this.uvs4;
  26601. }
  26602. if (this.uvs5) {
  26603. serializationObject.uvs5 = this.uvs5;
  26604. }
  26605. if (this.uvs6) {
  26606. serializationObject.uvs6 = this.uvs6;
  26607. }
  26608. if (this.colors) {
  26609. serializationObject.colors = this.colors;
  26610. }
  26611. if (this.matricesIndices) {
  26612. serializationObject.matricesIndices = this.matricesIndices;
  26613. serializationObject.matricesIndices._isExpanded = true;
  26614. }
  26615. if (this.matricesWeights) {
  26616. serializationObject.matricesWeights = this.matricesWeights;
  26617. }
  26618. if (this.matricesIndicesExtra) {
  26619. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26620. serializationObject.matricesIndicesExtra._isExpanded = true;
  26621. }
  26622. if (this.matricesWeightsExtra) {
  26623. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26624. }
  26625. serializationObject.indices = this.indices;
  26626. return serializationObject;
  26627. };
  26628. // Statics
  26629. /**
  26630. * Returns the object VertexData associated to the passed mesh.
  26631. */
  26632. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26633. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26634. };
  26635. /**
  26636. * Returns the object VertexData associated to the passed geometry.
  26637. */
  26638. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26639. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26640. };
  26641. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26642. var result = new VertexData();
  26643. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26644. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26645. }
  26646. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26647. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26648. }
  26649. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26650. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26651. }
  26652. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26653. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26654. }
  26655. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26656. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26657. }
  26658. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26659. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26660. }
  26661. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26662. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26663. }
  26664. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26665. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26666. }
  26667. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26668. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26669. }
  26670. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26671. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26672. }
  26673. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26674. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26675. }
  26676. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26677. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26678. }
  26679. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26680. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26681. }
  26682. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26683. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26684. }
  26685. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26686. return result;
  26687. };
  26688. /**
  26689. * Creates the vertexData of the Ribbon.
  26690. */
  26691. VertexData.CreateRibbon = function (options) {
  26692. var pathArray = options.pathArray;
  26693. var closeArray = options.closeArray || false;
  26694. var closePath = options.closePath || false;
  26695. var invertUV = options.invertUV || false;
  26696. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26697. var offset = options.offset || defaultOffset;
  26698. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26699. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26700. var customUV = options.uvs;
  26701. var customColors = options.colors;
  26702. var positions = [];
  26703. var indices = [];
  26704. var normals = [];
  26705. var uvs = [];
  26706. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26707. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26708. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26709. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26710. var minlg; // minimal length among all paths from pathArray
  26711. var lg = []; // array of path lengths : nb of vertex per path
  26712. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26713. var p; // path iterator
  26714. var i; // point iterator
  26715. var j; // point iterator
  26716. // if single path in pathArray
  26717. if (pathArray.length < 2) {
  26718. var ar1 = [];
  26719. var ar2 = [];
  26720. for (i = 0; i < pathArray[0].length - offset; i++) {
  26721. ar1.push(pathArray[0][i]);
  26722. ar2.push(pathArray[0][i + offset]);
  26723. }
  26724. pathArray = [ar1, ar2];
  26725. }
  26726. // positions and horizontal distances (u)
  26727. var idc = 0;
  26728. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26729. var path;
  26730. var l;
  26731. minlg = pathArray[0].length;
  26732. var vectlg;
  26733. var dist;
  26734. for (p = 0; p < pathArray.length; p++) {
  26735. uTotalDistance[p] = 0;
  26736. us[p] = [0];
  26737. path = pathArray[p];
  26738. l = path.length;
  26739. minlg = (minlg < l) ? minlg : l;
  26740. j = 0;
  26741. while (j < l) {
  26742. positions.push(path[j].x, path[j].y, path[j].z);
  26743. if (j > 0) {
  26744. vectlg = path[j].subtract(path[j - 1]).length();
  26745. dist = vectlg + uTotalDistance[p];
  26746. us[p].push(dist);
  26747. uTotalDistance[p] = dist;
  26748. }
  26749. j++;
  26750. }
  26751. if (closePath) {
  26752. j--;
  26753. positions.push(path[0].x, path[0].y, path[0].z);
  26754. vectlg = path[j].subtract(path[0]).length();
  26755. dist = vectlg + uTotalDistance[p];
  26756. us[p].push(dist);
  26757. uTotalDistance[p] = dist;
  26758. }
  26759. lg[p] = l + closePathCorr;
  26760. idx[p] = idc;
  26761. idc += (l + closePathCorr);
  26762. }
  26763. // vertical distances (v)
  26764. var path1;
  26765. var path2;
  26766. var vertex1;
  26767. var vertex2;
  26768. for (i = 0; i < minlg + closePathCorr; i++) {
  26769. vTotalDistance[i] = 0;
  26770. vs[i] = [0];
  26771. for (p = 0; p < pathArray.length - 1; p++) {
  26772. path1 = pathArray[p];
  26773. path2 = pathArray[p + 1];
  26774. if (i === minlg) {
  26775. vertex1 = path1[0];
  26776. vertex2 = path2[0];
  26777. }
  26778. else {
  26779. vertex1 = path1[i];
  26780. vertex2 = path2[i];
  26781. }
  26782. vectlg = vertex2.subtract(vertex1).length();
  26783. dist = vectlg + vTotalDistance[i];
  26784. vs[i].push(dist);
  26785. vTotalDistance[i] = dist;
  26786. }
  26787. if (closeArray) {
  26788. path1 = pathArray[p];
  26789. path2 = pathArray[0];
  26790. if (i === minlg) {
  26791. vertex2 = path2[0];
  26792. }
  26793. vectlg = vertex2.subtract(vertex1).length();
  26794. dist = vectlg + vTotalDistance[i];
  26795. vTotalDistance[i] = dist;
  26796. }
  26797. }
  26798. // uvs
  26799. var u;
  26800. var v;
  26801. if (customUV) {
  26802. for (p = 0; p < customUV.length; p++) {
  26803. uvs.push(customUV[p].x, customUV[p].y);
  26804. }
  26805. }
  26806. else {
  26807. for (p = 0; p < pathArray.length; p++) {
  26808. for (i = 0; i < minlg + closePathCorr; i++) {
  26809. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26810. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26811. if (invertUV) {
  26812. uvs.push(v, u);
  26813. }
  26814. else {
  26815. uvs.push(u, v);
  26816. }
  26817. }
  26818. }
  26819. }
  26820. // indices
  26821. p = 0; // path index
  26822. var pi = 0; // positions array index
  26823. var l1 = lg[p] - 1; // path1 length
  26824. var l2 = lg[p + 1] - 1; // path2 length
  26825. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26826. var shft = idx[1] - idx[0]; // shift
  26827. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26828. while (pi <= min && p < path1nb) {
  26829. // 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
  26830. indices.push(pi, pi + shft, pi + 1);
  26831. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26832. pi += 1;
  26833. if (pi === min) {
  26834. p++;
  26835. if (p === lg.length - 1) {
  26836. shft = idx[0] - idx[p];
  26837. l1 = lg[p] - 1;
  26838. l2 = lg[0] - 1;
  26839. }
  26840. else {
  26841. shft = idx[p + 1] - idx[p];
  26842. l1 = lg[p] - 1;
  26843. l2 = lg[p + 1] - 1;
  26844. }
  26845. pi = idx[p];
  26846. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26847. }
  26848. }
  26849. // normals
  26850. VertexData.ComputeNormals(positions, indices, normals);
  26851. if (closePath) {
  26852. var indexFirst = 0;
  26853. var indexLast = 0;
  26854. for (p = 0; p < pathArray.length; p++) {
  26855. indexFirst = idx[p] * 3;
  26856. if (p + 1 < pathArray.length) {
  26857. indexLast = (idx[p + 1] - 1) * 3;
  26858. }
  26859. else {
  26860. indexLast = normals.length - 3;
  26861. }
  26862. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26863. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26864. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26865. normals[indexLast] = normals[indexFirst];
  26866. normals[indexLast + 1] = normals[indexFirst + 1];
  26867. normals[indexLast + 2] = normals[indexFirst + 2];
  26868. }
  26869. }
  26870. // sides
  26871. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26872. // Colors
  26873. if (customColors) {
  26874. var colors = new Float32Array(customColors.length * 4);
  26875. for (var c = 0; c < customColors.length; c++) {
  26876. colors[c * 4] = customColors[c].r;
  26877. colors[c * 4 + 1] = customColors[c].g;
  26878. colors[c * 4 + 2] = customColors[c].b;
  26879. colors[c * 4 + 3] = customColors[c].a;
  26880. }
  26881. }
  26882. // Result
  26883. var vertexData = new VertexData();
  26884. var positions32 = new Float32Array(positions);
  26885. var normals32 = new Float32Array(normals);
  26886. var uvs32 = new Float32Array(uvs);
  26887. vertexData.indices = indices;
  26888. vertexData.positions = positions32;
  26889. vertexData.normals = normals32;
  26890. vertexData.uvs = uvs32;
  26891. if (customColors) {
  26892. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26893. }
  26894. if (closePath) {
  26895. vertexData._idx = idx;
  26896. }
  26897. return vertexData;
  26898. };
  26899. /**
  26900. * Creates the VertexData of the Box.
  26901. */
  26902. VertexData.CreateBox = function (options) {
  26903. var normalsSource = [
  26904. new BABYLON.Vector3(0, 0, 1),
  26905. new BABYLON.Vector3(0, 0, -1),
  26906. new BABYLON.Vector3(1, 0, 0),
  26907. new BABYLON.Vector3(-1, 0, 0),
  26908. new BABYLON.Vector3(0, 1, 0),
  26909. new BABYLON.Vector3(0, -1, 0)
  26910. ];
  26911. var indices = [];
  26912. var positions = [];
  26913. var normals = [];
  26914. var uvs = [];
  26915. var width = options.width || options.size || 1;
  26916. var height = options.height || options.size || 1;
  26917. var depth = options.depth || options.size || 1;
  26918. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26919. var faceUV = options.faceUV || new Array(6);
  26920. var faceColors = options.faceColors;
  26921. var colors = [];
  26922. // default face colors and UV if undefined
  26923. for (var f = 0; f < 6; f++) {
  26924. if (faceUV[f] === undefined) {
  26925. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26926. }
  26927. if (faceColors && faceColors[f] === undefined) {
  26928. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26929. }
  26930. }
  26931. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26932. // Create each face in turn.
  26933. for (var index = 0; index < normalsSource.length; index++) {
  26934. var normal = normalsSource[index];
  26935. // Get two vectors perpendicular to the face normal and to each other.
  26936. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26937. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26938. // Six indices (two triangles) per face.
  26939. var verticesLength = positions.length / 3;
  26940. indices.push(verticesLength);
  26941. indices.push(verticesLength + 1);
  26942. indices.push(verticesLength + 2);
  26943. indices.push(verticesLength);
  26944. indices.push(verticesLength + 2);
  26945. indices.push(verticesLength + 3);
  26946. // Four vertices per face.
  26947. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26948. positions.push(vertex.x, vertex.y, vertex.z);
  26949. normals.push(normal.x, normal.y, normal.z);
  26950. uvs.push(faceUV[index].z, faceUV[index].w);
  26951. if (faceColors) {
  26952. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26953. }
  26954. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26955. positions.push(vertex.x, vertex.y, vertex.z);
  26956. normals.push(normal.x, normal.y, normal.z);
  26957. uvs.push(faceUV[index].x, faceUV[index].w);
  26958. if (faceColors) {
  26959. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26960. }
  26961. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26962. positions.push(vertex.x, vertex.y, vertex.z);
  26963. normals.push(normal.x, normal.y, normal.z);
  26964. uvs.push(faceUV[index].x, faceUV[index].y);
  26965. if (faceColors) {
  26966. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26967. }
  26968. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26969. positions.push(vertex.x, vertex.y, vertex.z);
  26970. normals.push(normal.x, normal.y, normal.z);
  26971. uvs.push(faceUV[index].z, faceUV[index].y);
  26972. if (faceColors) {
  26973. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26974. }
  26975. }
  26976. // sides
  26977. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26978. // Result
  26979. var vertexData = new VertexData();
  26980. vertexData.indices = indices;
  26981. vertexData.positions = positions;
  26982. vertexData.normals = normals;
  26983. vertexData.uvs = uvs;
  26984. if (faceColors) {
  26985. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26986. vertexData.colors = totalColors;
  26987. }
  26988. return vertexData;
  26989. };
  26990. /**
  26991. * Creates the VertexData of the Sphere.
  26992. */
  26993. VertexData.CreateSphere = function (options) {
  26994. var segments = options.segments || 32;
  26995. var diameterX = options.diameterX || options.diameter || 1;
  26996. var diameterY = options.diameterY || options.diameter || 1;
  26997. var diameterZ = options.diameterZ || options.diameter || 1;
  26998. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26999. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27000. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27001. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27002. var totalZRotationSteps = 2 + segments;
  27003. var totalYRotationSteps = 2 * totalZRotationSteps;
  27004. var indices = [];
  27005. var positions = [];
  27006. var normals = [];
  27007. var uvs = [];
  27008. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27009. var normalizedZ = zRotationStep / totalZRotationSteps;
  27010. var angleZ = normalizedZ * Math.PI * slice;
  27011. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27012. var normalizedY = yRotationStep / totalYRotationSteps;
  27013. var angleY = normalizedY * Math.PI * 2 * arc;
  27014. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27015. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27016. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27017. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27018. var vertex = complete.multiply(radius);
  27019. var normal = complete.divide(radius).normalize();
  27020. positions.push(vertex.x, vertex.y, vertex.z);
  27021. normals.push(normal.x, normal.y, normal.z);
  27022. uvs.push(normalizedY, normalizedZ);
  27023. }
  27024. if (zRotationStep > 0) {
  27025. var verticesCount = positions.length / 3;
  27026. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27027. indices.push((firstIndex));
  27028. indices.push((firstIndex + 1));
  27029. indices.push(firstIndex + totalYRotationSteps + 1);
  27030. indices.push((firstIndex + totalYRotationSteps + 1));
  27031. indices.push((firstIndex + 1));
  27032. indices.push((firstIndex + totalYRotationSteps + 2));
  27033. }
  27034. }
  27035. }
  27036. // Sides
  27037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27038. // Result
  27039. var vertexData = new VertexData();
  27040. vertexData.indices = indices;
  27041. vertexData.positions = positions;
  27042. vertexData.normals = normals;
  27043. vertexData.uvs = uvs;
  27044. return vertexData;
  27045. };
  27046. /**
  27047. * Creates the VertexData of the Cylinder or Cone.
  27048. */
  27049. VertexData.CreateCylinder = function (options) {
  27050. var height = options.height || 2;
  27051. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27052. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27053. var tessellation = options.tessellation || 24;
  27054. var subdivisions = options.subdivisions || 1;
  27055. var hasRings = options.hasRings;
  27056. var enclose = options.enclose;
  27057. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27058. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27059. var faceUV = options.faceUV || new Array(3);
  27060. var faceColors = options.faceColors;
  27061. // default face colors and UV if undefined
  27062. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27063. var ringNb = (hasRings) ? subdivisions : 1;
  27064. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27065. var f;
  27066. for (f = 0; f < surfaceNb; f++) {
  27067. if (faceColors && faceColors[f] === undefined) {
  27068. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27069. }
  27070. }
  27071. for (f = 0; f < surfaceNb; f++) {
  27072. if (faceUV && faceUV[f] === undefined) {
  27073. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27074. }
  27075. }
  27076. var indices = [];
  27077. var positions = [];
  27078. var normals = [];
  27079. var uvs = [];
  27080. var colors = [];
  27081. var angle_step = Math.PI * 2 * arc / tessellation;
  27082. var angle;
  27083. var h;
  27084. var radius;
  27085. var tan = (diameterBottom - diameterTop) / 2 / height;
  27086. var ringVertex = BABYLON.Vector3.Zero();
  27087. var ringNormal = BABYLON.Vector3.Zero();
  27088. var ringFirstVertex = BABYLON.Vector3.Zero();
  27089. var ringFirstNormal = BABYLON.Vector3.Zero();
  27090. var quadNormal = BABYLON.Vector3.Zero();
  27091. var Y = BABYLON.Axis.Y;
  27092. // positions, normals, uvs
  27093. var i;
  27094. var j;
  27095. var r;
  27096. var ringIdx = 1;
  27097. var s = 1; // surface index
  27098. var cs = 0;
  27099. var v = 0;
  27100. for (i = 0; i <= subdivisions; i++) {
  27101. h = i / subdivisions;
  27102. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27103. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27104. for (r = 0; r < ringIdx; r++) {
  27105. if (hasRings) {
  27106. s += r;
  27107. }
  27108. if (enclose) {
  27109. s += 2 * r;
  27110. }
  27111. for (j = 0; j <= tessellation; j++) {
  27112. angle = j * angle_step;
  27113. // position
  27114. ringVertex.x = Math.cos(-angle) * radius;
  27115. ringVertex.y = -height / 2 + h * height;
  27116. ringVertex.z = Math.sin(-angle) * radius;
  27117. // normal
  27118. if (diameterTop === 0 && i === subdivisions) {
  27119. // if no top cap, reuse former normals
  27120. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27121. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27122. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27123. }
  27124. else {
  27125. ringNormal.x = ringVertex.x;
  27126. ringNormal.z = ringVertex.z;
  27127. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27128. ringNormal.normalize();
  27129. }
  27130. // keep first ring vertex values for enclose
  27131. if (j === 0) {
  27132. ringFirstVertex.copyFrom(ringVertex);
  27133. ringFirstNormal.copyFrom(ringNormal);
  27134. }
  27135. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27136. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27137. if (hasRings) {
  27138. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27139. }
  27140. else {
  27141. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27142. }
  27143. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27144. if (faceColors) {
  27145. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27146. }
  27147. }
  27148. // if enclose, add four vertices and their dedicated normals
  27149. if (arc !== 1 && enclose) {
  27150. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27151. positions.push(0, ringVertex.y, 0);
  27152. positions.push(0, ringVertex.y, 0);
  27153. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27154. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27155. quadNormal.normalize();
  27156. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27157. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27158. quadNormal.normalize();
  27159. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27160. if (hasRings) {
  27161. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27162. }
  27163. else {
  27164. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27165. }
  27166. uvs.push(faceUV[s + 1].x, v);
  27167. uvs.push(faceUV[s + 1].z, v);
  27168. if (hasRings) {
  27169. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27170. }
  27171. else {
  27172. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27173. }
  27174. uvs.push(faceUV[s + 2].x, v);
  27175. uvs.push(faceUV[s + 2].z, v);
  27176. if (faceColors) {
  27177. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27178. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27179. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27180. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27181. }
  27182. }
  27183. if (cs !== s) {
  27184. cs = s;
  27185. }
  27186. }
  27187. }
  27188. // indices
  27189. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27190. var s;
  27191. i = 0;
  27192. for (s = 0; s < subdivisions; s++) {
  27193. for (j = 0; j < tessellation; j++) {
  27194. var i0 = i * (e + 1) + j;
  27195. var i1 = (i + 1) * (e + 1) + j;
  27196. var i2 = i * (e + 1) + (j + 1);
  27197. var i3 = (i + 1) * (e + 1) + (j + 1);
  27198. indices.push(i0, i1, i2);
  27199. indices.push(i3, i2, i1);
  27200. }
  27201. if (arc !== 1 && enclose) {
  27202. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27203. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27204. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27205. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27206. }
  27207. i = (hasRings) ? (i + 2) : (i + 1);
  27208. }
  27209. // Caps
  27210. var createCylinderCap = function (isTop) {
  27211. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27212. if (radius === 0) {
  27213. return;
  27214. }
  27215. // Cap positions, normals & uvs
  27216. var angle;
  27217. var circleVector;
  27218. var i;
  27219. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27220. var c;
  27221. if (faceColors) {
  27222. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27223. }
  27224. // cap center
  27225. var vbase = positions.length / 3;
  27226. var offset = isTop ? height / 2 : -height / 2;
  27227. var center = new BABYLON.Vector3(0, offset, 0);
  27228. positions.push(center.x, center.y, center.z);
  27229. normals.push(0, isTop ? 1 : -1, 0);
  27230. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27231. if (faceColors) {
  27232. colors.push(c.r, c.g, c.b, c.a);
  27233. }
  27234. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27235. for (i = 0; i <= tessellation; i++) {
  27236. angle = Math.PI * 2 * i * arc / tessellation;
  27237. var cos = Math.cos(-angle);
  27238. var sin = Math.sin(-angle);
  27239. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27240. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27241. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27242. normals.push(0, isTop ? 1 : -1, 0);
  27243. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27244. if (faceColors) {
  27245. colors.push(c.r, c.g, c.b, c.a);
  27246. }
  27247. }
  27248. // Cap indices
  27249. for (i = 0; i < tessellation; i++) {
  27250. if (!isTop) {
  27251. indices.push(vbase);
  27252. indices.push(vbase + (i + 1));
  27253. indices.push(vbase + (i + 2));
  27254. }
  27255. else {
  27256. indices.push(vbase);
  27257. indices.push(vbase + (i + 2));
  27258. indices.push(vbase + (i + 1));
  27259. }
  27260. }
  27261. };
  27262. // add caps to geometry
  27263. createCylinderCap(false);
  27264. createCylinderCap(true);
  27265. // Sides
  27266. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27267. var vertexData = new VertexData();
  27268. vertexData.indices = indices;
  27269. vertexData.positions = positions;
  27270. vertexData.normals = normals;
  27271. vertexData.uvs = uvs;
  27272. if (faceColors) {
  27273. vertexData.colors = colors;
  27274. }
  27275. return vertexData;
  27276. };
  27277. /**
  27278. * Creates the VertexData of the Torus.
  27279. */
  27280. VertexData.CreateTorus = function (options) {
  27281. var indices = [];
  27282. var positions = [];
  27283. var normals = [];
  27284. var uvs = [];
  27285. var diameter = options.diameter || 1;
  27286. var thickness = options.thickness || 0.5;
  27287. var tessellation = options.tessellation || 16;
  27288. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27289. var stride = tessellation + 1;
  27290. for (var i = 0; i <= tessellation; i++) {
  27291. var u = i / tessellation;
  27292. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27293. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27294. for (var j = 0; j <= tessellation; j++) {
  27295. var v = 1 - j / tessellation;
  27296. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27297. var dx = Math.cos(innerAngle);
  27298. var dy = Math.sin(innerAngle);
  27299. // Create a vertex.
  27300. var normal = new BABYLON.Vector3(dx, dy, 0);
  27301. var position = normal.scale(thickness / 2);
  27302. var textureCoordinate = new BABYLON.Vector2(u, v);
  27303. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27304. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27305. positions.push(position.x, position.y, position.z);
  27306. normals.push(normal.x, normal.y, normal.z);
  27307. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27308. // And create indices for two triangles.
  27309. var nextI = (i + 1) % stride;
  27310. var nextJ = (j + 1) % stride;
  27311. indices.push(i * stride + j);
  27312. indices.push(i * stride + nextJ);
  27313. indices.push(nextI * stride + j);
  27314. indices.push(i * stride + nextJ);
  27315. indices.push(nextI * stride + nextJ);
  27316. indices.push(nextI * stride + j);
  27317. }
  27318. }
  27319. // Sides
  27320. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27321. // Result
  27322. var vertexData = new VertexData();
  27323. vertexData.indices = indices;
  27324. vertexData.positions = positions;
  27325. vertexData.normals = normals;
  27326. vertexData.uvs = uvs;
  27327. return vertexData;
  27328. };
  27329. /**
  27330. * Creates the VertexData of the LineSystem.
  27331. */
  27332. VertexData.CreateLineSystem = function (options) {
  27333. var indices = [];
  27334. var positions = [];
  27335. var lines = options.lines;
  27336. var idx = 0;
  27337. for (var l = 0; l < lines.length; l++) {
  27338. var points = lines[l];
  27339. for (var index = 0; index < points.length; index++) {
  27340. positions.push(points[index].x, points[index].y, points[index].z);
  27341. if (index > 0) {
  27342. indices.push(idx - 1);
  27343. indices.push(idx);
  27344. }
  27345. idx++;
  27346. }
  27347. }
  27348. var vertexData = new VertexData();
  27349. vertexData.indices = indices;
  27350. vertexData.positions = positions;
  27351. return vertexData;
  27352. };
  27353. /**
  27354. * Create the VertexData of the DashedLines.
  27355. */
  27356. VertexData.CreateDashedLines = function (options) {
  27357. var dashSize = options.dashSize || 3;
  27358. var gapSize = options.gapSize || 1;
  27359. var dashNb = options.dashNb || 200;
  27360. var points = options.points;
  27361. var positions = new Array();
  27362. var indices = new Array();
  27363. var curvect = BABYLON.Vector3.Zero();
  27364. var lg = 0;
  27365. var nb = 0;
  27366. var shft = 0;
  27367. var dashshft = 0;
  27368. var curshft = 0;
  27369. var idx = 0;
  27370. var i = 0;
  27371. for (i = 0; i < points.length - 1; i++) {
  27372. points[i + 1].subtractToRef(points[i], curvect);
  27373. lg += curvect.length();
  27374. }
  27375. shft = lg / dashNb;
  27376. dashshft = dashSize * shft / (dashSize + gapSize);
  27377. for (i = 0; i < points.length - 1; i++) {
  27378. points[i + 1].subtractToRef(points[i], curvect);
  27379. nb = Math.floor(curvect.length() / shft);
  27380. curvect.normalize();
  27381. for (var j = 0; j < nb; j++) {
  27382. curshft = shft * j;
  27383. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27384. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27385. indices.push(idx, idx + 1);
  27386. idx += 2;
  27387. }
  27388. }
  27389. // Result
  27390. var vertexData = new VertexData();
  27391. vertexData.positions = positions;
  27392. vertexData.indices = indices;
  27393. return vertexData;
  27394. };
  27395. /**
  27396. * Creates the VertexData of the Ground.
  27397. */
  27398. VertexData.CreateGround = function (options) {
  27399. var indices = [];
  27400. var positions = [];
  27401. var normals = [];
  27402. var uvs = [];
  27403. var row, col;
  27404. var width = options.width || 1;
  27405. var height = options.height || 1;
  27406. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27407. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27408. for (row = 0; row <= subdivisionsY; row++) {
  27409. for (col = 0; col <= subdivisionsX; col++) {
  27410. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27411. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27412. positions.push(position.x, position.y, position.z);
  27413. normals.push(normal.x, normal.y, normal.z);
  27414. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27415. }
  27416. }
  27417. for (row = 0; row < subdivisionsY; row++) {
  27418. for (col = 0; col < subdivisionsX; col++) {
  27419. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27420. indices.push(col + 1 + row * (subdivisionsX + 1));
  27421. indices.push(col + row * (subdivisionsX + 1));
  27422. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27423. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27424. indices.push(col + row * (subdivisionsX + 1));
  27425. }
  27426. }
  27427. // Result
  27428. var vertexData = new VertexData();
  27429. vertexData.indices = indices;
  27430. vertexData.positions = positions;
  27431. vertexData.normals = normals;
  27432. vertexData.uvs = uvs;
  27433. return vertexData;
  27434. };
  27435. /**
  27436. * Creates the VertexData of the TiledGround.
  27437. */
  27438. VertexData.CreateTiledGround = function (options) {
  27439. var xmin = options.xmin || -1.0;
  27440. var zmin = options.zmin || -1.0;
  27441. var xmax = options.xmax || 1.0;
  27442. var zmax = options.zmax || 1.0;
  27443. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27444. var precision = options.precision || { w: 1, h: 1 };
  27445. var indices = [];
  27446. var positions = [];
  27447. var normals = [];
  27448. var uvs = [];
  27449. var row, col, tileRow, tileCol;
  27450. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27451. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27452. precision.w = (precision.w < 1) ? 1 : precision.w;
  27453. precision.h = (precision.h < 1) ? 1 : precision.h;
  27454. var tileSize = {
  27455. 'w': (xmax - xmin) / subdivisions.w,
  27456. 'h': (zmax - zmin) / subdivisions.h
  27457. };
  27458. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27459. // Indices
  27460. var base = positions.length / 3;
  27461. var rowLength = precision.w + 1;
  27462. for (row = 0; row < precision.h; row++) {
  27463. for (col = 0; col < precision.w; col++) {
  27464. var square = [
  27465. base + col + row * rowLength,
  27466. base + (col + 1) + row * rowLength,
  27467. base + (col + 1) + (row + 1) * rowLength,
  27468. base + col + (row + 1) * rowLength
  27469. ];
  27470. indices.push(square[1]);
  27471. indices.push(square[2]);
  27472. indices.push(square[3]);
  27473. indices.push(square[0]);
  27474. indices.push(square[1]);
  27475. indices.push(square[3]);
  27476. }
  27477. }
  27478. // Position, normals and uvs
  27479. var position = BABYLON.Vector3.Zero();
  27480. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27481. for (row = 0; row <= precision.h; row++) {
  27482. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27483. for (col = 0; col <= precision.w; col++) {
  27484. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27485. position.y = 0;
  27486. positions.push(position.x, position.y, position.z);
  27487. normals.push(normal.x, normal.y, normal.z);
  27488. uvs.push(col / precision.w, row / precision.h);
  27489. }
  27490. }
  27491. }
  27492. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27493. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27494. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27495. }
  27496. }
  27497. // Result
  27498. var vertexData = new VertexData();
  27499. vertexData.indices = indices;
  27500. vertexData.positions = positions;
  27501. vertexData.normals = normals;
  27502. vertexData.uvs = uvs;
  27503. return vertexData;
  27504. };
  27505. /**
  27506. * Creates the VertexData of the Ground designed from a heightmap.
  27507. */
  27508. VertexData.CreateGroundFromHeightMap = function (options) {
  27509. var indices = [];
  27510. var positions = [];
  27511. var normals = [];
  27512. var uvs = [];
  27513. var row, col;
  27514. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27515. // Vertices
  27516. for (row = 0; row <= options.subdivisions; row++) {
  27517. for (col = 0; col <= options.subdivisions; col++) {
  27518. 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));
  27519. // Compute height
  27520. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27521. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27522. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27523. var r = options.buffer[pos] / 255.0;
  27524. var g = options.buffer[pos + 1] / 255.0;
  27525. var b = options.buffer[pos + 2] / 255.0;
  27526. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27527. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27528. // Add vertex
  27529. positions.push(position.x, position.y, position.z);
  27530. normals.push(0, 0, 0);
  27531. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27532. }
  27533. }
  27534. // Indices
  27535. for (row = 0; row < options.subdivisions; row++) {
  27536. for (col = 0; col < options.subdivisions; col++) {
  27537. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27538. indices.push(col + 1 + row * (options.subdivisions + 1));
  27539. indices.push(col + row * (options.subdivisions + 1));
  27540. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27541. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27542. indices.push(col + row * (options.subdivisions + 1));
  27543. }
  27544. }
  27545. // Normals
  27546. VertexData.ComputeNormals(positions, indices, normals);
  27547. // Result
  27548. var vertexData = new VertexData();
  27549. vertexData.indices = indices;
  27550. vertexData.positions = positions;
  27551. vertexData.normals = normals;
  27552. vertexData.uvs = uvs;
  27553. return vertexData;
  27554. };
  27555. /**
  27556. * Creates the VertexData of the Plane.
  27557. */
  27558. VertexData.CreatePlane = function (options) {
  27559. var indices = [];
  27560. var positions = [];
  27561. var normals = [];
  27562. var uvs = [];
  27563. var width = options.width || options.size || 1;
  27564. var height = options.height || options.size || 1;
  27565. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27566. // Vertices
  27567. var halfWidth = width / 2.0;
  27568. var halfHeight = height / 2.0;
  27569. positions.push(-halfWidth, -halfHeight, 0);
  27570. normals.push(0, 0, -1.0);
  27571. uvs.push(0.0, 0.0);
  27572. positions.push(halfWidth, -halfHeight, 0);
  27573. normals.push(0, 0, -1.0);
  27574. uvs.push(1.0, 0.0);
  27575. positions.push(halfWidth, halfHeight, 0);
  27576. normals.push(0, 0, -1.0);
  27577. uvs.push(1.0, 1.0);
  27578. positions.push(-halfWidth, halfHeight, 0);
  27579. normals.push(0, 0, -1.0);
  27580. uvs.push(0.0, 1.0);
  27581. // Indices
  27582. indices.push(0);
  27583. indices.push(1);
  27584. indices.push(2);
  27585. indices.push(0);
  27586. indices.push(2);
  27587. indices.push(3);
  27588. // Sides
  27589. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27590. // Result
  27591. var vertexData = new VertexData();
  27592. vertexData.indices = indices;
  27593. vertexData.positions = positions;
  27594. vertexData.normals = normals;
  27595. vertexData.uvs = uvs;
  27596. return vertexData;
  27597. };
  27598. /**
  27599. * Creates the VertexData of the Disc or regular Polygon.
  27600. */
  27601. VertexData.CreateDisc = function (options) {
  27602. var positions = [];
  27603. var indices = [];
  27604. var normals = [];
  27605. var uvs = [];
  27606. var radius = options.radius || 0.5;
  27607. var tessellation = options.tessellation || 64;
  27608. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27609. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27610. // positions and uvs
  27611. positions.push(0, 0, 0); // disc center first
  27612. uvs.push(0.5, 0.5);
  27613. var theta = Math.PI * 2 * arc;
  27614. var step = theta / tessellation;
  27615. for (var a = 0; a < theta; a += step) {
  27616. var x = Math.cos(a);
  27617. var y = Math.sin(a);
  27618. var u = (x + 1) / 2;
  27619. var v = (1 - y) / 2;
  27620. positions.push(radius * x, radius * y, 0);
  27621. uvs.push(u, v);
  27622. }
  27623. if (arc === 1) {
  27624. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27625. uvs.push(uvs[2], uvs[3]);
  27626. }
  27627. //indices
  27628. var vertexNb = positions.length / 3;
  27629. for (var i = 1; i < vertexNb - 1; i++) {
  27630. indices.push(i + 1, 0, i);
  27631. }
  27632. // result
  27633. VertexData.ComputeNormals(positions, indices, normals);
  27634. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27635. var vertexData = new VertexData();
  27636. vertexData.indices = indices;
  27637. vertexData.positions = positions;
  27638. vertexData.normals = normals;
  27639. vertexData.uvs = uvs;
  27640. return vertexData;
  27641. };
  27642. /**
  27643. * Re-creates the VertexData of the Polygon for sideOrientation.
  27644. */
  27645. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27646. var faceUV = fUV || new Array(3);
  27647. var faceColors = fColors;
  27648. var colors = [];
  27649. // default face colors and UV if undefined
  27650. for (var f = 0; f < 3; f++) {
  27651. if (faceUV[f] === undefined) {
  27652. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27653. }
  27654. if (faceColors && faceColors[f] === undefined) {
  27655. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27656. }
  27657. }
  27658. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27659. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27660. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27661. var indices = polygon.getIndices();
  27662. // set face colours and textures
  27663. var idx = 0;
  27664. var face = 0;
  27665. for (var index = 0; index < normals.length; index += 3) {
  27666. //Edge Face no. 1
  27667. if (Math.abs(normals[index + 1]) < 0.001) {
  27668. face = 1;
  27669. }
  27670. //Top Face no. 0
  27671. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27672. face = 0;
  27673. }
  27674. //Bottom Face no. 2
  27675. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27676. face = 2;
  27677. }
  27678. idx = index / 3;
  27679. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27680. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27681. if (faceColors) {
  27682. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27683. }
  27684. }
  27685. // sides
  27686. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27687. // Result
  27688. var vertexData = new VertexData();
  27689. vertexData.indices = indices;
  27690. vertexData.positions = positions;
  27691. vertexData.normals = normals;
  27692. vertexData.uvs = uvs;
  27693. if (faceColors) {
  27694. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27695. vertexData.colors = totalColors;
  27696. }
  27697. return vertexData;
  27698. };
  27699. /**
  27700. * Creates the VertexData of the IcoSphere.
  27701. */
  27702. VertexData.CreateIcoSphere = function (options) {
  27703. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27704. var radius = options.radius || 1;
  27705. var flat = (options.flat === undefined) ? true : options.flat;
  27706. var subdivisions = options.subdivisions || 4;
  27707. var radiusX = options.radiusX || radius;
  27708. var radiusY = options.radiusY || radius;
  27709. var radiusZ = options.radiusZ || radius;
  27710. var t = (1 + Math.sqrt(5)) / 2;
  27711. // 12 vertex x,y,z
  27712. var ico_vertices = [
  27713. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27714. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27715. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27716. ];
  27717. // index of 3 vertex makes a face of icopshere
  27718. var ico_indices = [
  27719. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27720. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27721. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27722. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27723. ];
  27724. // vertex for uv have aliased position, not for UV
  27725. var vertices_unalias_id = [
  27726. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27727. // vertex alias
  27728. 0,
  27729. 2,
  27730. 3,
  27731. 3,
  27732. 3,
  27733. 4,
  27734. 7,
  27735. 8,
  27736. 9,
  27737. 9,
  27738. 10,
  27739. 11 // 23: B + 12
  27740. ];
  27741. // uv as integer step (not pixels !)
  27742. var ico_vertexuv = [
  27743. 5, 1, 3, 1, 6, 4, 0, 0,
  27744. 5, 3, 4, 2, 2, 2, 4, 0,
  27745. 2, 0, 1, 1, 6, 0, 6, 2,
  27746. // vertex alias (for same vertex on different faces)
  27747. 0, 4,
  27748. 3, 3,
  27749. 4, 4,
  27750. 3, 1,
  27751. 4, 2,
  27752. 4, 4,
  27753. 0, 2,
  27754. 1, 1,
  27755. 2, 2,
  27756. 3, 3,
  27757. 1, 3,
  27758. 2, 4 // 23: B + 12
  27759. ];
  27760. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27761. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27762. // First island of uv mapping
  27763. // v = 4h 3+ 2
  27764. // v = 3h 9+ 4
  27765. // v = 2h 9+ 5 B
  27766. // v = 1h 9 1 0
  27767. // v = 0h 3 8 7 A
  27768. // u = 0 1 2 3 4 5 6 *a
  27769. // Second island of uv mapping
  27770. // v = 4h 0+ B+ 4+
  27771. // v = 3h A+ 2+
  27772. // v = 2h 7+ 6 3+
  27773. // v = 1h 8+ 3+
  27774. // v = 0h
  27775. // u = 0 1 2 3 4 5 6 *a
  27776. // Face layout on texture UV mapping
  27777. // ============
  27778. // \ 4 /\ 16 / ======
  27779. // \ / \ / /\ 11 /
  27780. // \/ 7 \/ / \ /
  27781. // ======= / 10 \/
  27782. // /\ 17 /\ =======
  27783. // / \ / \ \ 15 /\
  27784. // / 8 \/ 12 \ \ / \
  27785. // ============ \/ 6 \
  27786. // \ 18 /\ ============
  27787. // \ / \ \ 5 /\ 0 /
  27788. // \/ 13 \ \ / \ /
  27789. // ======= \/ 1 \/
  27790. // =============
  27791. // /\ 19 /\ 2 /\
  27792. // / \ / \ / \
  27793. // / 14 \/ 9 \/ 3 \
  27794. // ===================
  27795. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27796. var ustep = 138 / 1024;
  27797. var vstep = 239 / 1024;
  27798. var uoffset = 60 / 1024;
  27799. var voffset = 26 / 1024;
  27800. // Second island should have margin, not to touch the first island
  27801. // avoid any borderline artefact in pixel rounding
  27802. var island_u_offset = -40 / 1024;
  27803. var island_v_offset = +20 / 1024;
  27804. // face is either island 0 or 1 :
  27805. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27806. var island = [
  27807. 0, 0, 0, 0, 1,
  27808. 0, 0, 1, 1, 0,
  27809. 0, 0, 1, 1, 0,
  27810. 0, 1, 1, 1, 0 // 15 - 19
  27811. ];
  27812. var indices = [];
  27813. var positions = [];
  27814. var normals = [];
  27815. var uvs = [];
  27816. var current_indice = 0;
  27817. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27818. var face_vertex_pos = new Array(3);
  27819. var face_vertex_uv = new Array(3);
  27820. var v012;
  27821. for (v012 = 0; v012 < 3; v012++) {
  27822. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27823. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27824. }
  27825. // create all with normals
  27826. for (var face = 0; face < 20; face++) {
  27827. // 3 vertex per face
  27828. for (v012 = 0; v012 < 3; v012++) {
  27829. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27830. var v_id = ico_indices[3 * face + v012];
  27831. // vertex have 3D position (x,y,z)
  27832. 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]);
  27833. // Normalize to get normal, then scale to radius
  27834. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27835. // uv Coordinates from vertex ID
  27836. 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);
  27837. }
  27838. // Subdivide the face (interpolate pos, norm, uv)
  27839. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27840. // - norm is linear interpolation of vertex corner normal
  27841. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27842. // - uv is linear interpolation
  27843. //
  27844. // Topology is as below for sub-divide by 2
  27845. // vertex shown as v0,v1,v2
  27846. // interp index is i1 to progress in range [v0,v1[
  27847. // interp index is i2 to progress in range [v0,v2[
  27848. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27849. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27850. //
  27851. //
  27852. // i2 v2
  27853. // ^ ^
  27854. // / / \
  27855. // / / \
  27856. // / / \
  27857. // / / (0,1) \
  27858. // / #---------\
  27859. // / / \ (0,0)'/ \
  27860. // / / \ / \
  27861. // / / \ / \
  27862. // / / (0,0) \ / (1,0) \
  27863. // / #---------#---------\
  27864. // v0 v1
  27865. //
  27866. // --------------------> i1
  27867. //
  27868. // interp of (i1,i2):
  27869. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27870. // along i1 : lerp(x0,x1, i1/(S-i2))
  27871. //
  27872. // centroid of triangle is needed to get help normal computation
  27873. // (c1,c2) are used for centroid location
  27874. var interp_vertex = function (i1, i2, c1, c2) {
  27875. // vertex is interpolated from
  27876. // - face_vertex_pos[0..2]
  27877. // - face_vertex_uv[0..2]
  27878. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27879. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27880. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27881. pos_interp.normalize();
  27882. var vertex_normal;
  27883. if (flat) {
  27884. // in flat mode, recalculate normal as face centroid normal
  27885. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27886. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27887. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27888. }
  27889. else {
  27890. // in smooth mode, recalculate normal from each single vertex position
  27891. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27892. }
  27893. // Vertex normal need correction due to X,Y,Z radius scaling
  27894. vertex_normal.x /= radiusX;
  27895. vertex_normal.y /= radiusY;
  27896. vertex_normal.z /= radiusZ;
  27897. vertex_normal.normalize();
  27898. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27899. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27900. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27901. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27902. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27903. uvs.push(uv_interp.x, uv_interp.y);
  27904. // push each vertex has member of a face
  27905. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27906. indices.push(current_indice);
  27907. current_indice++;
  27908. };
  27909. for (var i2 = 0; i2 < subdivisions; i2++) {
  27910. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27911. // face : (i1,i2) for /\ :
  27912. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27913. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27914. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27915. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27916. if (i1 + i2 + 1 < subdivisions) {
  27917. // face : (i1,i2)' for \/ :
  27918. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27919. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27920. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27921. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27922. }
  27923. }
  27924. }
  27925. }
  27926. // Sides
  27927. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27928. // Result
  27929. var vertexData = new VertexData();
  27930. vertexData.indices = indices;
  27931. vertexData.positions = positions;
  27932. vertexData.normals = normals;
  27933. vertexData.uvs = uvs;
  27934. return vertexData;
  27935. };
  27936. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27937. /**
  27938. * Creates the VertexData of the Polyhedron.
  27939. */
  27940. VertexData.CreatePolyhedron = function (options) {
  27941. // provided polyhedron types :
  27942. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27943. // 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)
  27944. var polyhedra = [];
  27945. 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]] };
  27946. 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]] };
  27947. polyhedra[2] = {
  27948. 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]],
  27949. 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]]
  27950. };
  27951. polyhedra[3] = {
  27952. 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]],
  27953. 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]]
  27954. };
  27955. polyhedra[4] = {
  27956. 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]],
  27957. 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]]
  27958. };
  27959. 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]] };
  27960. 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]] };
  27961. 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]] };
  27962. 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]] };
  27963. 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]] };
  27964. 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]] };
  27965. 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]] };
  27966. 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]] };
  27967. 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]] };
  27968. polyhedra[14] = {
  27969. 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]],
  27970. 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]]
  27971. };
  27972. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27973. var size = options.size;
  27974. var sizeX = options.sizeX || size || 1;
  27975. var sizeY = options.sizeY || size || 1;
  27976. var sizeZ = options.sizeZ || size || 1;
  27977. var data = options.custom || polyhedra[type];
  27978. var nbfaces = data.face.length;
  27979. var faceUV = options.faceUV || new Array(nbfaces);
  27980. var faceColors = options.faceColors;
  27981. var flat = (options.flat === undefined) ? true : options.flat;
  27982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27983. var positions = [];
  27984. var indices = [];
  27985. var normals = [];
  27986. var uvs = [];
  27987. var colors = [];
  27988. var index = 0;
  27989. var faceIdx = 0; // face cursor in the array "indexes"
  27990. var indexes = [];
  27991. var i = 0;
  27992. var f = 0;
  27993. var u, v, ang, x, y, tmp;
  27994. // default face colors and UV if undefined
  27995. if (flat) {
  27996. for (f = 0; f < nbfaces; f++) {
  27997. if (faceColors && faceColors[f] === undefined) {
  27998. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27999. }
  28000. if (faceUV && faceUV[f] === undefined) {
  28001. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28002. }
  28003. }
  28004. }
  28005. if (!flat) {
  28006. for (i = 0; i < data.vertex.length; i++) {
  28007. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28008. uvs.push(0, 0);
  28009. }
  28010. for (f = 0; f < nbfaces; f++) {
  28011. for (i = 0; i < data.face[f].length - 2; i++) {
  28012. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28013. }
  28014. }
  28015. }
  28016. else {
  28017. for (f = 0; f < nbfaces; f++) {
  28018. var fl = data.face[f].length; // number of vertices of the current face
  28019. ang = 2 * Math.PI / fl;
  28020. x = 0.5 * Math.tan(ang / 2);
  28021. y = 0.5;
  28022. // positions, uvs, colors
  28023. for (i = 0; i < fl; i++) {
  28024. // positions
  28025. 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);
  28026. indexes.push(index);
  28027. index++;
  28028. // uvs
  28029. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28030. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28031. uvs.push(u, v);
  28032. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28033. y = x * Math.sin(ang) + y * Math.cos(ang);
  28034. x = tmp;
  28035. // colors
  28036. if (faceColors) {
  28037. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28038. }
  28039. }
  28040. // indices from indexes
  28041. for (i = 0; i < fl - 2; i++) {
  28042. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28043. }
  28044. faceIdx += fl;
  28045. }
  28046. }
  28047. VertexData.ComputeNormals(positions, indices, normals);
  28048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28049. var vertexData = new VertexData();
  28050. vertexData.positions = positions;
  28051. vertexData.indices = indices;
  28052. vertexData.normals = normals;
  28053. vertexData.uvs = uvs;
  28054. if (faceColors && flat) {
  28055. vertexData.colors = colors;
  28056. }
  28057. return vertexData;
  28058. };
  28059. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28060. /**
  28061. * Creates the VertexData of the Torus Knot.
  28062. */
  28063. VertexData.CreateTorusKnot = function (options) {
  28064. var indices = [];
  28065. var positions = [];
  28066. var normals = [];
  28067. var uvs = [];
  28068. var radius = options.radius || 2;
  28069. var tube = options.tube || 0.5;
  28070. var radialSegments = options.radialSegments || 32;
  28071. var tubularSegments = options.tubularSegments || 32;
  28072. var p = options.p || 2;
  28073. var q = options.q || 3;
  28074. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28075. // Helper
  28076. var getPos = function (angle) {
  28077. var cu = Math.cos(angle);
  28078. var su = Math.sin(angle);
  28079. var quOverP = q / p * angle;
  28080. var cs = Math.cos(quOverP);
  28081. var tx = radius * (2 + cs) * 0.5 * cu;
  28082. var ty = radius * (2 + cs) * su * 0.5;
  28083. var tz = radius * Math.sin(quOverP) * 0.5;
  28084. return new BABYLON.Vector3(tx, ty, tz);
  28085. };
  28086. // Vertices
  28087. var i;
  28088. var j;
  28089. for (i = 0; i <= radialSegments; i++) {
  28090. var modI = i % radialSegments;
  28091. var u = modI / radialSegments * 2 * p * Math.PI;
  28092. var p1 = getPos(u);
  28093. var p2 = getPos(u + 0.01);
  28094. var tang = p2.subtract(p1);
  28095. var n = p2.add(p1);
  28096. var bitan = BABYLON.Vector3.Cross(tang, n);
  28097. n = BABYLON.Vector3.Cross(bitan, tang);
  28098. bitan.normalize();
  28099. n.normalize();
  28100. for (j = 0; j < tubularSegments; j++) {
  28101. var modJ = j % tubularSegments;
  28102. var v = modJ / tubularSegments * 2 * Math.PI;
  28103. var cx = -tube * Math.cos(v);
  28104. var cy = tube * Math.sin(v);
  28105. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28106. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28107. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28108. uvs.push(i / radialSegments);
  28109. uvs.push(j / tubularSegments);
  28110. }
  28111. }
  28112. for (i = 0; i < radialSegments; i++) {
  28113. for (j = 0; j < tubularSegments; j++) {
  28114. var jNext = (j + 1) % tubularSegments;
  28115. var a = i * tubularSegments + j;
  28116. var b = (i + 1) * tubularSegments + j;
  28117. var c = (i + 1) * tubularSegments + jNext;
  28118. var d = i * tubularSegments + jNext;
  28119. indices.push(d);
  28120. indices.push(b);
  28121. indices.push(a);
  28122. indices.push(d);
  28123. indices.push(c);
  28124. indices.push(b);
  28125. }
  28126. }
  28127. // Normals
  28128. VertexData.ComputeNormals(positions, indices, normals);
  28129. // Sides
  28130. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28131. // Result
  28132. var vertexData = new VertexData();
  28133. vertexData.indices = indices;
  28134. vertexData.positions = positions;
  28135. vertexData.normals = normals;
  28136. vertexData.uvs = uvs;
  28137. return vertexData;
  28138. };
  28139. // Tools
  28140. /**
  28141. * @param {any} - positions (number[] or Float32Array)
  28142. * @param {any} - indices (number[] or Uint16Array)
  28143. * @param {any} - normals (number[] or Float32Array)
  28144. * options (optional) :
  28145. * facetPositions : optional array of facet positions (vector3)
  28146. * facetNormals : optional array of facet normals (vector3)
  28147. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28148. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28149. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28150. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28151. * bInfo : optional bounding info, required for facetPartitioning computation
  28152. */
  28153. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28154. // temporary scalar variables
  28155. var index = 0; // facet index
  28156. var p1p2x = 0.0; // p1p2 vector x coordinate
  28157. var p1p2y = 0.0; // p1p2 vector y coordinate
  28158. var p1p2z = 0.0; // p1p2 vector z coordinate
  28159. var p3p2x = 0.0; // p3p2 vector x coordinate
  28160. var p3p2y = 0.0; // p3p2 vector y coordinate
  28161. var p3p2z = 0.0; // p3p2 vector z coordinate
  28162. var faceNormalx = 0.0; // facet normal x coordinate
  28163. var faceNormaly = 0.0; // facet normal y coordinate
  28164. var faceNormalz = 0.0; // facet normal z coordinate
  28165. var length = 0.0; // facet normal length before normalization
  28166. var v1x = 0; // vector1 x index in the positions array
  28167. var v1y = 0; // vector1 y index in the positions array
  28168. var v1z = 0; // vector1 z index in the positions array
  28169. var v2x = 0; // vector2 x index in the positions array
  28170. var v2y = 0; // vector2 y index in the positions array
  28171. var v2z = 0; // vector2 z index in the positions array
  28172. var v3x = 0; // vector3 x index in the positions array
  28173. var v3y = 0; // vector3 y index in the positions array
  28174. var v3z = 0; // vector3 z index in the positions array
  28175. var computeFacetNormals = false;
  28176. var computeFacetPositions = false;
  28177. var computeFacetPartitioning = false;
  28178. var faceNormalSign = 1;
  28179. if (options) {
  28180. computeFacetNormals = (options.facetNormals) ? true : false;
  28181. computeFacetPositions = (options.facetPositions) ? true : false;
  28182. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28183. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28184. }
  28185. // facetPartitioning reinit if needed
  28186. if (computeFacetPartitioning) {
  28187. var ox = 0; // X partitioning index for facet position
  28188. var oy = 0; // Y partinioning index for facet position
  28189. var oz = 0; // Z partinioning index for facet position
  28190. var b1x = 0; // X partitioning index for facet v1 vertex
  28191. var b1y = 0; // Y partitioning index for facet v1 vertex
  28192. var b1z = 0; // z partitioning index for facet v1 vertex
  28193. var b2x = 0; // X partitioning index for facet v2 vertex
  28194. var b2y = 0; // Y partitioning index for facet v2 vertex
  28195. var b2z = 0; // Z partitioning index for facet v2 vertex
  28196. var b3x = 0; // X partitioning index for facet v3 vertex
  28197. var b3y = 0; // Y partitioning index for facet v3 vertex
  28198. var b3z = 0; // Z partitioning index for facet v3 vertex
  28199. var block_idx_o = 0; // facet barycenter block index
  28200. var block_idx_v1 = 0; // v1 vertex block index
  28201. var block_idx_v2 = 0; // v2 vertex block index
  28202. var block_idx_v3 = 0; // v3 vertex block index
  28203. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28204. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28205. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28206. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28207. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28208. var subSq = options.subDiv.max * options.subDiv.max;
  28209. options.facetPartitioning.length = 0;
  28210. }
  28211. // reset the normals
  28212. for (index = 0; index < positions.length; index++) {
  28213. normals[index] = 0.0;
  28214. }
  28215. // Loop : 1 indice triplet = 1 facet
  28216. var nbFaces = indices.length / 3;
  28217. for (index = 0; index < nbFaces; index++) {
  28218. // get the indexes of the coordinates of each vertex of the facet
  28219. v1x = indices[index * 3] * 3;
  28220. v1y = v1x + 1;
  28221. v1z = v1x + 2;
  28222. v2x = indices[index * 3 + 1] * 3;
  28223. v2y = v2x + 1;
  28224. v2z = v2x + 2;
  28225. v3x = indices[index * 3 + 2] * 3;
  28226. v3y = v3x + 1;
  28227. v3z = v3x + 2;
  28228. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28229. p1p2y = positions[v1y] - positions[v2y];
  28230. p1p2z = positions[v1z] - positions[v2z];
  28231. p3p2x = positions[v3x] - positions[v2x];
  28232. p3p2y = positions[v3y] - positions[v2y];
  28233. p3p2z = positions[v3z] - positions[v2z];
  28234. // compute the face normal with the cross product
  28235. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28236. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28237. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28238. // normalize this normal and store it in the array facetData
  28239. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28240. length = (length === 0) ? 1.0 : length;
  28241. faceNormalx /= length;
  28242. faceNormaly /= length;
  28243. faceNormalz /= length;
  28244. if (computeFacetNormals) {
  28245. options.facetNormals[index].x = faceNormalx;
  28246. options.facetNormals[index].y = faceNormaly;
  28247. options.facetNormals[index].z = faceNormalz;
  28248. }
  28249. if (computeFacetPositions) {
  28250. // compute and the facet barycenter coordinates in the array facetPositions
  28251. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28252. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28253. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28254. }
  28255. if (computeFacetPartitioning) {
  28256. // store the facet indexes in arrays in the main facetPartitioning array :
  28257. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28258. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28259. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28260. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28261. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28262. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28263. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28264. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28265. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28266. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28267. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28268. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28269. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28270. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28271. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28272. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28273. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28274. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28275. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28276. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28277. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28278. // push each facet index in each block containing the vertex
  28279. options.facetPartitioning[block_idx_v1].push(index);
  28280. if (block_idx_v2 != block_idx_v1) {
  28281. options.facetPartitioning[block_idx_v2].push(index);
  28282. }
  28283. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28284. options.facetPartitioning[block_idx_v3].push(index);
  28285. }
  28286. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28287. options.facetPartitioning[block_idx_o].push(index);
  28288. }
  28289. }
  28290. // compute the normals anyway
  28291. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28292. normals[v1y] += faceNormaly;
  28293. normals[v1z] += faceNormalz;
  28294. normals[v2x] += faceNormalx;
  28295. normals[v2y] += faceNormaly;
  28296. normals[v2z] += faceNormalz;
  28297. normals[v3x] += faceNormalx;
  28298. normals[v3y] += faceNormaly;
  28299. normals[v3z] += faceNormalz;
  28300. }
  28301. // last normalization of each normal
  28302. for (index = 0; index < normals.length / 3; index++) {
  28303. faceNormalx = normals[index * 3];
  28304. faceNormaly = normals[index * 3 + 1];
  28305. faceNormalz = normals[index * 3 + 2];
  28306. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28307. length = (length === 0) ? 1.0 : length;
  28308. faceNormalx /= length;
  28309. faceNormaly /= length;
  28310. faceNormalz /= length;
  28311. normals[index * 3] = faceNormalx;
  28312. normals[index * 3 + 1] = faceNormaly;
  28313. normals[index * 3 + 2] = faceNormalz;
  28314. }
  28315. };
  28316. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28317. var li = indices.length;
  28318. var ln = normals.length;
  28319. var i;
  28320. var n;
  28321. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28322. switch (sideOrientation) {
  28323. case BABYLON.Mesh.FRONTSIDE:
  28324. // nothing changed
  28325. break;
  28326. case BABYLON.Mesh.BACKSIDE:
  28327. var tmp;
  28328. // indices
  28329. for (i = 0; i < li; i += 3) {
  28330. tmp = indices[i];
  28331. indices[i] = indices[i + 2];
  28332. indices[i + 2] = tmp;
  28333. }
  28334. // normals
  28335. for (n = 0; n < ln; n++) {
  28336. normals[n] = -normals[n];
  28337. }
  28338. break;
  28339. case BABYLON.Mesh.DOUBLESIDE:
  28340. // positions
  28341. var lp = positions.length;
  28342. var l = lp / 3;
  28343. for (var p = 0; p < lp; p++) {
  28344. positions[lp + p] = positions[p];
  28345. }
  28346. // indices
  28347. for (i = 0; i < li; i += 3) {
  28348. indices[i + li] = indices[i + 2] + l;
  28349. indices[i + 1 + li] = indices[i + 1] + l;
  28350. indices[i + 2 + li] = indices[i] + l;
  28351. }
  28352. // normals
  28353. for (n = 0; n < ln; n++) {
  28354. normals[ln + n] = -normals[n];
  28355. }
  28356. // uvs
  28357. var lu = uvs.length;
  28358. var u = 0;
  28359. for (u = 0; u < lu; u++) {
  28360. uvs[u + lu] = uvs[u];
  28361. }
  28362. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28363. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28364. u = 0;
  28365. for (i = 0; i < lu / 2; i++) {
  28366. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28367. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28368. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28369. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28370. u += 2;
  28371. }
  28372. break;
  28373. }
  28374. };
  28375. /**
  28376. * Creates a new VertexData from the imported parameters.
  28377. */
  28378. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28379. var vertexData = new VertexData();
  28380. // positions
  28381. var positions = parsedVertexData.positions;
  28382. if (positions) {
  28383. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28384. }
  28385. // normals
  28386. var normals = parsedVertexData.normals;
  28387. if (normals) {
  28388. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28389. }
  28390. // tangents
  28391. var tangents = parsedVertexData.tangents;
  28392. if (tangents) {
  28393. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28394. }
  28395. // uvs
  28396. var uvs = parsedVertexData.uvs;
  28397. if (uvs) {
  28398. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28399. }
  28400. // uv2s
  28401. var uv2s = parsedVertexData.uv2s;
  28402. if (uv2s) {
  28403. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28404. }
  28405. // uv3s
  28406. var uv3s = parsedVertexData.uv3s;
  28407. if (uv3s) {
  28408. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28409. }
  28410. // uv4s
  28411. var uv4s = parsedVertexData.uv4s;
  28412. if (uv4s) {
  28413. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28414. }
  28415. // uv5s
  28416. var uv5s = parsedVertexData.uv5s;
  28417. if (uv5s) {
  28418. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28419. }
  28420. // uv6s
  28421. var uv6s = parsedVertexData.uv6s;
  28422. if (uv6s) {
  28423. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28424. }
  28425. // colors
  28426. var colors = parsedVertexData.colors;
  28427. if (colors) {
  28428. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28429. }
  28430. // matricesIndices
  28431. var matricesIndices = parsedVertexData.matricesIndices;
  28432. if (matricesIndices) {
  28433. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28434. }
  28435. // matricesWeights
  28436. var matricesWeights = parsedVertexData.matricesWeights;
  28437. if (matricesWeights) {
  28438. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28439. }
  28440. // indices
  28441. var indices = parsedVertexData.indices;
  28442. if (indices) {
  28443. vertexData.indices = indices;
  28444. }
  28445. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28446. };
  28447. return VertexData;
  28448. }());
  28449. BABYLON.VertexData = VertexData;
  28450. })(BABYLON || (BABYLON = {}));
  28451. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28452. var BABYLON;
  28453. (function (BABYLON) {
  28454. var Geometry = (function () {
  28455. function Geometry(id, scene, vertexData, updatable, mesh) {
  28456. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28457. this._totalVertices = 0;
  28458. this._isDisposed = false;
  28459. this.id = id;
  28460. this._engine = scene.getEngine();
  28461. this._meshes = [];
  28462. this._scene = scene;
  28463. //Init vertex buffer cache
  28464. this._vertexBuffers = {};
  28465. this._indices = [];
  28466. this._updatable = updatable;
  28467. // vertexData
  28468. if (vertexData) {
  28469. this.setAllVerticesData(vertexData, updatable);
  28470. }
  28471. else {
  28472. this._totalVertices = 0;
  28473. this._indices = [];
  28474. }
  28475. if (this._engine.getCaps().vertexArrayObject) {
  28476. this._vertexArrayObjects = {};
  28477. }
  28478. // applyToMesh
  28479. if (mesh) {
  28480. if (mesh.getClassName() === "LinesMesh") {
  28481. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28482. this.updateExtend();
  28483. }
  28484. this.applyToMesh(mesh);
  28485. mesh.computeWorldMatrix(true);
  28486. }
  28487. }
  28488. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28489. /**
  28490. * 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
  28491. * @returns The Bias Vector
  28492. */
  28493. get: function () {
  28494. return this._boundingBias;
  28495. },
  28496. set: function (value) {
  28497. if (this._boundingBias && this._boundingBias.equals(value)) {
  28498. return;
  28499. }
  28500. this._boundingBias = value.clone();
  28501. this.updateBoundingInfo(true, null);
  28502. },
  28503. enumerable: true,
  28504. configurable: true
  28505. });
  28506. Object.defineProperty(Geometry.prototype, "extend", {
  28507. get: function () {
  28508. return this._extend;
  28509. },
  28510. enumerable: true,
  28511. configurable: true
  28512. });
  28513. Geometry.prototype.getScene = function () {
  28514. return this._scene;
  28515. };
  28516. Geometry.prototype.getEngine = function () {
  28517. return this._engine;
  28518. };
  28519. Geometry.prototype.isReady = function () {
  28520. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28521. };
  28522. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28523. get: function () {
  28524. for (var index = 0; index < this._meshes.length; index++) {
  28525. if (!this._meshes[index].doNotSerialize) {
  28526. return false;
  28527. }
  28528. }
  28529. return true;
  28530. },
  28531. enumerable: true,
  28532. configurable: true
  28533. });
  28534. Geometry.prototype._rebuild = function () {
  28535. if (this._vertexArrayObjects) {
  28536. this._vertexArrayObjects = {};
  28537. }
  28538. // Index buffer
  28539. if (this._meshes.length !== 0 && this._indices) {
  28540. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28541. }
  28542. // Vertex buffers
  28543. for (var key in this._vertexBuffers) {
  28544. var vertexBuffer = this._vertexBuffers[key];
  28545. vertexBuffer._rebuild();
  28546. }
  28547. };
  28548. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28549. vertexData.applyToGeometry(this, updatable);
  28550. this.notifyUpdate();
  28551. };
  28552. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28553. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28554. this.setVerticesBuffer(buffer);
  28555. };
  28556. Geometry.prototype.removeVerticesData = function (kind) {
  28557. if (this._vertexBuffers[kind]) {
  28558. this._vertexBuffers[kind].dispose();
  28559. delete this._vertexBuffers[kind];
  28560. }
  28561. };
  28562. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28563. var kind = buffer.getKind();
  28564. if (this._vertexBuffers[kind]) {
  28565. this._vertexBuffers[kind].dispose();
  28566. }
  28567. this._vertexBuffers[kind] = buffer;
  28568. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28569. var data = buffer.getData();
  28570. var stride = buffer.getStrideSize();
  28571. this._totalVertices = data.length / stride;
  28572. this.updateExtend(data, stride);
  28573. this._resetPointsArrayCache();
  28574. var meshes = this._meshes;
  28575. var numOfMeshes = meshes.length;
  28576. for (var index = 0; index < numOfMeshes; index++) {
  28577. var mesh = meshes[index];
  28578. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28579. mesh._createGlobalSubMesh(false);
  28580. mesh.computeWorldMatrix(true);
  28581. }
  28582. }
  28583. this.notifyUpdate(kind);
  28584. if (this._vertexArrayObjects) {
  28585. this._disposeVertexArrayObjects();
  28586. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28587. }
  28588. };
  28589. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28590. var vertexBuffer = this.getVertexBuffer(kind);
  28591. if (!vertexBuffer) {
  28592. return;
  28593. }
  28594. vertexBuffer.updateDirectly(data, offset);
  28595. this.notifyUpdate(kind);
  28596. };
  28597. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28598. var vertexBuffer = this.getVertexBuffer(kind);
  28599. if (!vertexBuffer) {
  28600. return;
  28601. }
  28602. vertexBuffer.update(data);
  28603. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28604. var stride = vertexBuffer.getStrideSize();
  28605. this._totalVertices = data.length / stride;
  28606. this.updateBoundingInfo(updateExtends, data);
  28607. }
  28608. this.notifyUpdate(kind);
  28609. };
  28610. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28611. if (updateExtends) {
  28612. this.updateExtend(data);
  28613. }
  28614. var meshes = this._meshes;
  28615. var numOfMeshes = meshes.length;
  28616. this._resetPointsArrayCache();
  28617. for (var index = 0; index < numOfMeshes; index++) {
  28618. var mesh = meshes[index];
  28619. if (updateExtends) {
  28620. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28621. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28622. var subMesh = mesh.subMeshes[subIndex];
  28623. subMesh.refreshBoundingInfo();
  28624. }
  28625. }
  28626. }
  28627. };
  28628. Geometry.prototype._bind = function (effect, indexToBind) {
  28629. if (indexToBind === void 0) { indexToBind = undefined; }
  28630. if (indexToBind === undefined) {
  28631. indexToBind = this._indexBuffer;
  28632. }
  28633. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28634. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28635. return;
  28636. }
  28637. // Using VAO
  28638. if (!this._vertexArrayObjects[effect.key]) {
  28639. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28640. }
  28641. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28642. };
  28643. Geometry.prototype.getTotalVertices = function () {
  28644. if (!this.isReady()) {
  28645. return 0;
  28646. }
  28647. return this._totalVertices;
  28648. };
  28649. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28650. var vertexBuffer = this.getVertexBuffer(kind);
  28651. if (!vertexBuffer) {
  28652. return null;
  28653. }
  28654. var orig = vertexBuffer.getData();
  28655. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28656. return orig;
  28657. }
  28658. else {
  28659. var len = orig.length;
  28660. var copy = [];
  28661. for (var i = 0; i < len; i++) {
  28662. copy.push(orig[i]);
  28663. }
  28664. return copy;
  28665. }
  28666. };
  28667. Geometry.prototype.getVertexBuffer = function (kind) {
  28668. if (!this.isReady()) {
  28669. return null;
  28670. }
  28671. return this._vertexBuffers[kind];
  28672. };
  28673. Geometry.prototype.getVertexBuffers = function () {
  28674. if (!this.isReady()) {
  28675. return null;
  28676. }
  28677. return this._vertexBuffers;
  28678. };
  28679. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28680. if (!this._vertexBuffers) {
  28681. if (this._delayInfo) {
  28682. return this._delayInfo.indexOf(kind) !== -1;
  28683. }
  28684. return false;
  28685. }
  28686. return this._vertexBuffers[kind] !== undefined;
  28687. };
  28688. Geometry.prototype.getVerticesDataKinds = function () {
  28689. var result = [];
  28690. var kind;
  28691. if (!this._vertexBuffers && this._delayInfo) {
  28692. for (kind in this._delayInfo) {
  28693. result.push(kind);
  28694. }
  28695. }
  28696. else {
  28697. for (kind in this._vertexBuffers) {
  28698. result.push(kind);
  28699. }
  28700. }
  28701. return result;
  28702. };
  28703. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28704. if (this._indexBuffer) {
  28705. this._engine._releaseBuffer(this._indexBuffer);
  28706. }
  28707. this._disposeVertexArrayObjects();
  28708. this._indices = indices;
  28709. if (this._meshes.length !== 0 && this._indices) {
  28710. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28711. }
  28712. if (totalVertices !== undefined) {
  28713. this._totalVertices = totalVertices;
  28714. }
  28715. var meshes = this._meshes;
  28716. var numOfMeshes = meshes.length;
  28717. for (var index = 0; index < numOfMeshes; index++) {
  28718. meshes[index]._createGlobalSubMesh(true);
  28719. }
  28720. this.notifyUpdate();
  28721. };
  28722. Geometry.prototype.getTotalIndices = function () {
  28723. if (!this.isReady()) {
  28724. return 0;
  28725. }
  28726. return this._indices.length;
  28727. };
  28728. Geometry.prototype.getIndices = function (copyWhenShared) {
  28729. if (!this.isReady()) {
  28730. return null;
  28731. }
  28732. var orig = this._indices;
  28733. if (!copyWhenShared || this._meshes.length === 1) {
  28734. return orig;
  28735. }
  28736. else {
  28737. var len = orig.length;
  28738. var copy = [];
  28739. for (var i = 0; i < len; i++) {
  28740. copy.push(orig[i]);
  28741. }
  28742. return copy;
  28743. }
  28744. };
  28745. Geometry.prototype.getIndexBuffer = function () {
  28746. if (!this.isReady()) {
  28747. return null;
  28748. }
  28749. return this._indexBuffer;
  28750. };
  28751. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28752. if (!effect || !this._vertexArrayObjects) {
  28753. return;
  28754. }
  28755. if (this._vertexArrayObjects[effect.key]) {
  28756. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28757. delete this._vertexArrayObjects[effect.key];
  28758. }
  28759. };
  28760. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28761. var meshes = this._meshes;
  28762. var index = meshes.indexOf(mesh);
  28763. if (index === -1) {
  28764. return;
  28765. }
  28766. meshes.splice(index, 1);
  28767. mesh._geometry = null;
  28768. if (meshes.length === 0 && shouldDispose) {
  28769. this.dispose();
  28770. }
  28771. };
  28772. Geometry.prototype.applyToMesh = function (mesh) {
  28773. if (mesh._geometry === this) {
  28774. return;
  28775. }
  28776. var previousGeometry = mesh._geometry;
  28777. if (previousGeometry) {
  28778. previousGeometry.releaseForMesh(mesh);
  28779. }
  28780. var meshes = this._meshes;
  28781. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28782. mesh._geometry = this;
  28783. this._scene.pushGeometry(this);
  28784. meshes.push(mesh);
  28785. if (this.isReady()) {
  28786. this._applyToMesh(mesh);
  28787. }
  28788. else {
  28789. mesh._boundingInfo = this._boundingInfo;
  28790. }
  28791. };
  28792. Geometry.prototype.updateExtend = function (data, stride) {
  28793. if (data === void 0) { data = null; }
  28794. if (!data) {
  28795. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28796. }
  28797. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28798. };
  28799. Geometry.prototype._applyToMesh = function (mesh) {
  28800. var numOfMeshes = this._meshes.length;
  28801. // vertexBuffers
  28802. for (var kind in this._vertexBuffers) {
  28803. if (numOfMeshes === 1) {
  28804. this._vertexBuffers[kind].create();
  28805. }
  28806. var buffer = this._vertexBuffers[kind].getBuffer();
  28807. if (buffer)
  28808. buffer.references = numOfMeshes;
  28809. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28810. if (!this._extend) {
  28811. this.updateExtend(this._vertexBuffers[kind].getData());
  28812. }
  28813. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28814. mesh._createGlobalSubMesh(false);
  28815. //bounding info was just created again, world matrix should be applied again.
  28816. mesh._updateBoundingInfo();
  28817. }
  28818. }
  28819. // indexBuffer
  28820. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28821. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28822. }
  28823. if (this._indexBuffer) {
  28824. this._indexBuffer.references = numOfMeshes;
  28825. }
  28826. };
  28827. Geometry.prototype.notifyUpdate = function (kind) {
  28828. if (this.onGeometryUpdated) {
  28829. this.onGeometryUpdated(this, kind);
  28830. }
  28831. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28832. var mesh = _a[_i];
  28833. mesh._markSubMeshesAsAttributesDirty();
  28834. }
  28835. };
  28836. Geometry.prototype.load = function (scene, onLoaded) {
  28837. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28838. return;
  28839. }
  28840. if (this.isReady()) {
  28841. if (onLoaded) {
  28842. onLoaded();
  28843. }
  28844. return;
  28845. }
  28846. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28847. this._queueLoad(scene, onLoaded);
  28848. };
  28849. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28850. var _this = this;
  28851. scene._addPendingData(this);
  28852. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28853. _this._delayLoadingFunction(JSON.parse(data), _this);
  28854. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28855. _this._delayInfo = [];
  28856. scene._removePendingData(_this);
  28857. var meshes = _this._meshes;
  28858. var numOfMeshes = meshes.length;
  28859. for (var index = 0; index < numOfMeshes; index++) {
  28860. _this._applyToMesh(meshes[index]);
  28861. }
  28862. if (onLoaded) {
  28863. onLoaded();
  28864. }
  28865. }, function () { }, scene.database);
  28866. };
  28867. /**
  28868. * Invert the geometry to move from a right handed system to a left handed one.
  28869. */
  28870. Geometry.prototype.toLeftHanded = function () {
  28871. // Flip faces
  28872. var tIndices = this.getIndices(false);
  28873. if (tIndices != null && tIndices.length > 0) {
  28874. for (var i = 0; i < tIndices.length; i += 3) {
  28875. var tTemp = tIndices[i + 0];
  28876. tIndices[i + 0] = tIndices[i + 2];
  28877. tIndices[i + 2] = tTemp;
  28878. }
  28879. this.setIndices(tIndices);
  28880. }
  28881. // Negate position.z
  28882. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28883. if (tPositions != null && tPositions.length > 0) {
  28884. for (var i = 0; i < tPositions.length; i += 3) {
  28885. tPositions[i + 2] = -tPositions[i + 2];
  28886. }
  28887. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28888. }
  28889. // Negate normal.z
  28890. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28891. if (tNormals != null && tNormals.length > 0) {
  28892. for (var i = 0; i < tNormals.length; i += 3) {
  28893. tNormals[i + 2] = -tNormals[i + 2];
  28894. }
  28895. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28896. }
  28897. };
  28898. // Cache
  28899. Geometry.prototype._resetPointsArrayCache = function () {
  28900. this._positions = null;
  28901. };
  28902. Geometry.prototype._generatePointsArray = function () {
  28903. if (this._positions)
  28904. return true;
  28905. this._positions = [];
  28906. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28907. if (!data) {
  28908. return false;
  28909. }
  28910. for (var index = 0; index < data.length; index += 3) {
  28911. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28912. }
  28913. return true;
  28914. };
  28915. Geometry.prototype.isDisposed = function () {
  28916. return this._isDisposed;
  28917. };
  28918. Geometry.prototype._disposeVertexArrayObjects = function () {
  28919. if (this._vertexArrayObjects) {
  28920. for (var kind in this._vertexArrayObjects) {
  28921. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28922. }
  28923. this._vertexArrayObjects = {};
  28924. }
  28925. };
  28926. Geometry.prototype.dispose = function () {
  28927. var meshes = this._meshes;
  28928. var numOfMeshes = meshes.length;
  28929. var index;
  28930. for (index = 0; index < numOfMeshes; index++) {
  28931. this.releaseForMesh(meshes[index]);
  28932. }
  28933. this._meshes = [];
  28934. this._disposeVertexArrayObjects();
  28935. for (var kind in this._vertexBuffers) {
  28936. this._vertexBuffers[kind].dispose();
  28937. }
  28938. this._vertexBuffers = {};
  28939. this._totalVertices = 0;
  28940. if (this._indexBuffer) {
  28941. this._engine._releaseBuffer(this._indexBuffer);
  28942. }
  28943. this._indexBuffer = null;
  28944. this._indices = [];
  28945. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28946. this.delayLoadingFile = null;
  28947. this._delayLoadingFunction = null;
  28948. this._delayInfo = [];
  28949. this._boundingInfo = null;
  28950. this._scene.removeGeometry(this);
  28951. this._isDisposed = true;
  28952. };
  28953. Geometry.prototype.copy = function (id) {
  28954. var vertexData = new BABYLON.VertexData();
  28955. vertexData.indices = [];
  28956. var indices = this.getIndices();
  28957. for (var index = 0; index < indices.length; index++) {
  28958. vertexData.indices.push(indices[index]);
  28959. }
  28960. var updatable = false;
  28961. var stopChecking = false;
  28962. var kind;
  28963. for (kind in this._vertexBuffers) {
  28964. // using slice() to make a copy of the array and not just reference it
  28965. var data = this.getVerticesData(kind);
  28966. if (data instanceof Float32Array) {
  28967. vertexData.set(new Float32Array(data), kind);
  28968. }
  28969. else {
  28970. vertexData.set(data.slice(0), kind);
  28971. }
  28972. if (!stopChecking) {
  28973. updatable = this.getVertexBuffer(kind).isUpdatable();
  28974. stopChecking = !updatable;
  28975. }
  28976. }
  28977. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28978. geometry.delayLoadState = this.delayLoadState;
  28979. geometry.delayLoadingFile = this.delayLoadingFile;
  28980. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28981. for (kind in this._delayInfo) {
  28982. geometry._delayInfo = geometry._delayInfo || [];
  28983. geometry._delayInfo.push(kind);
  28984. }
  28985. // Bounding info
  28986. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28987. return geometry;
  28988. };
  28989. Geometry.prototype.serialize = function () {
  28990. var serializationObject = {};
  28991. serializationObject.id = this.id;
  28992. serializationObject.updatable = this._updatable;
  28993. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28994. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28995. }
  28996. return serializationObject;
  28997. };
  28998. Geometry.prototype.toNumberArray = function (origin) {
  28999. if (Array.isArray(origin)) {
  29000. return origin;
  29001. }
  29002. else {
  29003. return Array.prototype.slice.call(origin);
  29004. }
  29005. };
  29006. Geometry.prototype.serializeVerticeData = function () {
  29007. var serializationObject = this.serialize();
  29008. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29009. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29010. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29011. serializationObject.positions._updatable = true;
  29012. }
  29013. }
  29014. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29015. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29016. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29017. serializationObject.normals._updatable = true;
  29018. }
  29019. }
  29020. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29021. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29022. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29023. serializationObject.uvs._updatable = true;
  29024. }
  29025. }
  29026. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29027. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29028. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29029. serializationObject.uv2s._updatable = true;
  29030. }
  29031. }
  29032. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29033. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29034. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29035. serializationObject.uv3s._updatable = true;
  29036. }
  29037. }
  29038. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29039. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29040. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29041. serializationObject.uv4s._updatable = true;
  29042. }
  29043. }
  29044. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29045. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29046. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29047. serializationObject.uv5s._updatable = true;
  29048. }
  29049. }
  29050. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29051. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29052. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29053. serializationObject.uv6s._updatable = true;
  29054. }
  29055. }
  29056. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29057. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29058. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29059. serializationObject.colors._updatable = true;
  29060. }
  29061. }
  29062. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29063. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29064. serializationObject.matricesIndices._isExpanded = true;
  29065. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29066. serializationObject.matricesIndices._updatable = true;
  29067. }
  29068. }
  29069. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29070. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29071. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29072. serializationObject.matricesWeights._updatable = true;
  29073. }
  29074. }
  29075. serializationObject.indices = this.toNumberArray(this.getIndices());
  29076. return serializationObject;
  29077. };
  29078. // Statics
  29079. Geometry.ExtractFromMesh = function (mesh, id) {
  29080. var geometry = mesh._geometry;
  29081. if (!geometry) {
  29082. return null;
  29083. }
  29084. return geometry.copy(id);
  29085. };
  29086. /**
  29087. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29088. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29089. * Be aware Math.random() could cause collisions, but:
  29090. * "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"
  29091. */
  29092. Geometry.RandomId = function () {
  29093. return BABYLON.Tools.RandomId();
  29094. };
  29095. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29096. var scene = mesh.getScene();
  29097. // Geometry
  29098. var geometryId = parsedGeometry.geometryId;
  29099. if (geometryId) {
  29100. var geometry = scene.getGeometryByID(geometryId);
  29101. if (geometry) {
  29102. geometry.applyToMesh(mesh);
  29103. }
  29104. }
  29105. else if (parsedGeometry instanceof ArrayBuffer) {
  29106. var binaryInfo = mesh._binaryInfo;
  29107. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29108. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29109. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29110. }
  29111. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29112. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29113. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29114. }
  29115. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29116. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29117. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29118. }
  29119. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29120. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29121. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29122. }
  29123. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29124. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29125. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29126. }
  29127. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29128. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29129. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29130. }
  29131. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29132. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29133. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29134. }
  29135. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29136. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29137. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29138. }
  29139. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29140. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29141. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29142. }
  29143. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29144. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29145. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29146. }
  29147. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29148. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29149. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29150. }
  29151. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29152. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29153. mesh.setIndices(indicesData);
  29154. }
  29155. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29156. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29157. mesh.subMeshes = [];
  29158. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29159. var materialIndex = subMeshesData[(i * 5) + 0];
  29160. var verticesStart = subMeshesData[(i * 5) + 1];
  29161. var verticesCount = subMeshesData[(i * 5) + 2];
  29162. var indexStart = subMeshesData[(i * 5) + 3];
  29163. var indexCount = subMeshesData[(i * 5) + 4];
  29164. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29165. }
  29166. }
  29167. }
  29168. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29169. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29170. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29171. if (parsedGeometry.uvs) {
  29172. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29173. }
  29174. if (parsedGeometry.uvs2) {
  29175. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29176. }
  29177. if (parsedGeometry.uvs3) {
  29178. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29179. }
  29180. if (parsedGeometry.uvs4) {
  29181. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29182. }
  29183. if (parsedGeometry.uvs5) {
  29184. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29185. }
  29186. if (parsedGeometry.uvs6) {
  29187. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29188. }
  29189. if (parsedGeometry.colors) {
  29190. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29191. }
  29192. if (parsedGeometry.matricesIndices) {
  29193. if (!parsedGeometry.matricesIndices._isExpanded) {
  29194. var floatIndices = [];
  29195. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29196. var matricesIndex = parsedGeometry.matricesIndices[i];
  29197. floatIndices.push(matricesIndex & 0x000000FF);
  29198. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29199. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29200. floatIndices.push(matricesIndex >> 24);
  29201. }
  29202. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29203. }
  29204. else {
  29205. delete parsedGeometry.matricesIndices._isExpanded;
  29206. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29207. }
  29208. }
  29209. if (parsedGeometry.matricesIndicesExtra) {
  29210. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29211. var floatIndices = [];
  29212. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29213. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29214. floatIndices.push(matricesIndex & 0x000000FF);
  29215. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29216. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29217. floatIndices.push(matricesIndex >> 24);
  29218. }
  29219. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29220. }
  29221. else {
  29222. delete parsedGeometry.matricesIndices._isExpanded;
  29223. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29224. }
  29225. }
  29226. if (parsedGeometry.matricesWeights) {
  29227. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29228. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29229. }
  29230. if (parsedGeometry.matricesWeightsExtra) {
  29231. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29232. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29233. }
  29234. mesh.setIndices(parsedGeometry.indices);
  29235. }
  29236. // SubMeshes
  29237. if (parsedGeometry.subMeshes) {
  29238. mesh.subMeshes = [];
  29239. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29240. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29241. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29242. }
  29243. }
  29244. // Flat shading
  29245. if (mesh._shouldGenerateFlatShading) {
  29246. mesh.convertToFlatShadedMesh();
  29247. delete mesh._shouldGenerateFlatShading;
  29248. }
  29249. // Update
  29250. mesh.computeWorldMatrix(true);
  29251. // Octree
  29252. if (scene['_selectionOctree']) {
  29253. scene['_selectionOctree'].addMesh(mesh);
  29254. }
  29255. };
  29256. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29257. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29258. return;
  29259. }
  29260. var size = matricesWeights.length;
  29261. for (var i = 0; i < size; i += influencers) {
  29262. var weight = 0;
  29263. var biggerIndex = i;
  29264. var biggerWeight = 0;
  29265. for (var j = 0; j < influencers - 1; j++) {
  29266. weight += matricesWeights[i + j];
  29267. if (matricesWeights[i + j] > biggerWeight) {
  29268. biggerWeight = matricesWeights[i + j];
  29269. biggerIndex = i + j;
  29270. }
  29271. }
  29272. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29273. }
  29274. };
  29275. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29276. if (scene.getGeometryByID(parsedVertexData.id)) {
  29277. return null; // null since geometry could be something else than a box...
  29278. }
  29279. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29280. if (BABYLON.Tags) {
  29281. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29282. }
  29283. if (parsedVertexData.delayLoadingFile) {
  29284. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29285. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29286. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29287. geometry._delayInfo = [];
  29288. if (parsedVertexData.hasUVs) {
  29289. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29290. }
  29291. if (parsedVertexData.hasUVs2) {
  29292. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29293. }
  29294. if (parsedVertexData.hasUVs3) {
  29295. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29296. }
  29297. if (parsedVertexData.hasUVs4) {
  29298. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29299. }
  29300. if (parsedVertexData.hasUVs5) {
  29301. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29302. }
  29303. if (parsedVertexData.hasUVs6) {
  29304. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29305. }
  29306. if (parsedVertexData.hasColors) {
  29307. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29308. }
  29309. if (parsedVertexData.hasMatricesIndices) {
  29310. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29311. }
  29312. if (parsedVertexData.hasMatricesWeights) {
  29313. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29314. }
  29315. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29316. }
  29317. else {
  29318. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29319. }
  29320. scene.pushGeometry(geometry, true);
  29321. return geometry;
  29322. };
  29323. return Geometry;
  29324. }());
  29325. BABYLON.Geometry = Geometry;
  29326. /////// Primitives //////////////////////////////////////////////
  29327. (function (Geometry) {
  29328. var Primitives;
  29329. (function (Primitives) {
  29330. /// Abstract class
  29331. var _Primitive = (function (_super) {
  29332. __extends(_Primitive, _super);
  29333. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29334. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29335. _this._canBeRegenerated = _canBeRegenerated;
  29336. _this._beingRegenerated = true;
  29337. _this.regenerate();
  29338. _this._beingRegenerated = false;
  29339. return _this;
  29340. }
  29341. _Primitive.prototype.canBeRegenerated = function () {
  29342. return this._canBeRegenerated;
  29343. };
  29344. _Primitive.prototype.regenerate = function () {
  29345. if (!this._canBeRegenerated) {
  29346. return;
  29347. }
  29348. this._beingRegenerated = true;
  29349. this.setAllVerticesData(this._regenerateVertexData(), false);
  29350. this._beingRegenerated = false;
  29351. };
  29352. _Primitive.prototype.asNewGeometry = function (id) {
  29353. return _super.prototype.copy.call(this, id);
  29354. };
  29355. // overrides
  29356. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29357. if (!this._beingRegenerated) {
  29358. return;
  29359. }
  29360. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29361. };
  29362. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29363. if (!this._beingRegenerated) {
  29364. return;
  29365. }
  29366. _super.prototype.setVerticesData.call(this, kind, data, false);
  29367. };
  29368. // to override
  29369. // protected
  29370. _Primitive.prototype._regenerateVertexData = function () {
  29371. throw new Error("Abstract method");
  29372. };
  29373. _Primitive.prototype.copy = function (id) {
  29374. throw new Error("Must be overriden in sub-classes.");
  29375. };
  29376. _Primitive.prototype.serialize = function () {
  29377. var serializationObject = _super.prototype.serialize.call(this);
  29378. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29379. return serializationObject;
  29380. };
  29381. return _Primitive;
  29382. }(Geometry));
  29383. Primitives._Primitive = _Primitive;
  29384. var Ribbon = (function (_super) {
  29385. __extends(Ribbon, _super);
  29386. // Members
  29387. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29388. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29389. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29390. _this.pathArray = pathArray;
  29391. _this.closeArray = closeArray;
  29392. _this.closePath = closePath;
  29393. _this.offset = offset;
  29394. _this.side = side;
  29395. return _this;
  29396. }
  29397. Ribbon.prototype._regenerateVertexData = function () {
  29398. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29399. };
  29400. Ribbon.prototype.copy = function (id) {
  29401. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29402. };
  29403. return Ribbon;
  29404. }(_Primitive));
  29405. Primitives.Ribbon = Ribbon;
  29406. var Box = (function (_super) {
  29407. __extends(Box, _super);
  29408. // Members
  29409. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29410. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29411. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29412. _this.size = size;
  29413. _this.side = side;
  29414. return _this;
  29415. }
  29416. Box.prototype._regenerateVertexData = function () {
  29417. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29418. };
  29419. Box.prototype.copy = function (id) {
  29420. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29421. };
  29422. Box.prototype.serialize = function () {
  29423. var serializationObject = _super.prototype.serialize.call(this);
  29424. serializationObject.size = this.size;
  29425. return serializationObject;
  29426. };
  29427. Box.Parse = function (parsedBox, scene) {
  29428. if (scene.getGeometryByID(parsedBox.id)) {
  29429. return null; // null since geometry could be something else than a box...
  29430. }
  29431. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29432. if (BABYLON.Tags) {
  29433. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29434. }
  29435. scene.pushGeometry(box, true);
  29436. return box;
  29437. };
  29438. return Box;
  29439. }(_Primitive));
  29440. Primitives.Box = Box;
  29441. var Sphere = (function (_super) {
  29442. __extends(Sphere, _super);
  29443. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29444. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29445. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29446. _this.segments = segments;
  29447. _this.diameter = diameter;
  29448. _this.side = side;
  29449. return _this;
  29450. }
  29451. Sphere.prototype._regenerateVertexData = function () {
  29452. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29453. };
  29454. Sphere.prototype.copy = function (id) {
  29455. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29456. };
  29457. Sphere.prototype.serialize = function () {
  29458. var serializationObject = _super.prototype.serialize.call(this);
  29459. serializationObject.segments = this.segments;
  29460. serializationObject.diameter = this.diameter;
  29461. return serializationObject;
  29462. };
  29463. Sphere.Parse = function (parsedSphere, scene) {
  29464. if (scene.getGeometryByID(parsedSphere.id)) {
  29465. return null; // null since geometry could be something else than a sphere...
  29466. }
  29467. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29468. if (BABYLON.Tags) {
  29469. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29470. }
  29471. scene.pushGeometry(sphere, true);
  29472. return sphere;
  29473. };
  29474. return Sphere;
  29475. }(_Primitive));
  29476. Primitives.Sphere = Sphere;
  29477. var Disc = (function (_super) {
  29478. __extends(Disc, _super);
  29479. // Members
  29480. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29481. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29482. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29483. _this.radius = radius;
  29484. _this.tessellation = tessellation;
  29485. _this.side = side;
  29486. return _this;
  29487. }
  29488. Disc.prototype._regenerateVertexData = function () {
  29489. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29490. };
  29491. Disc.prototype.copy = function (id) {
  29492. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29493. };
  29494. return Disc;
  29495. }(_Primitive));
  29496. Primitives.Disc = Disc;
  29497. var Cylinder = (function (_super) {
  29498. __extends(Cylinder, _super);
  29499. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29500. if (subdivisions === void 0) { subdivisions = 1; }
  29501. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29502. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29503. _this.height = height;
  29504. _this.diameterTop = diameterTop;
  29505. _this.diameterBottom = diameterBottom;
  29506. _this.tessellation = tessellation;
  29507. _this.subdivisions = subdivisions;
  29508. _this.side = side;
  29509. return _this;
  29510. }
  29511. Cylinder.prototype._regenerateVertexData = function () {
  29512. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29513. };
  29514. Cylinder.prototype.copy = function (id) {
  29515. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29516. };
  29517. Cylinder.prototype.serialize = function () {
  29518. var serializationObject = _super.prototype.serialize.call(this);
  29519. serializationObject.height = this.height;
  29520. serializationObject.diameterTop = this.diameterTop;
  29521. serializationObject.diameterBottom = this.diameterBottom;
  29522. serializationObject.tessellation = this.tessellation;
  29523. return serializationObject;
  29524. };
  29525. Cylinder.Parse = function (parsedCylinder, scene) {
  29526. if (scene.getGeometryByID(parsedCylinder.id)) {
  29527. return null; // null since geometry could be something else than a cylinder...
  29528. }
  29529. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29530. if (BABYLON.Tags) {
  29531. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29532. }
  29533. scene.pushGeometry(cylinder, true);
  29534. return cylinder;
  29535. };
  29536. return Cylinder;
  29537. }(_Primitive));
  29538. Primitives.Cylinder = Cylinder;
  29539. var Torus = (function (_super) {
  29540. __extends(Torus, _super);
  29541. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29542. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29543. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29544. _this.diameter = diameter;
  29545. _this.thickness = thickness;
  29546. _this.tessellation = tessellation;
  29547. _this.side = side;
  29548. return _this;
  29549. }
  29550. Torus.prototype._regenerateVertexData = function () {
  29551. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29552. };
  29553. Torus.prototype.copy = function (id) {
  29554. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29555. };
  29556. Torus.prototype.serialize = function () {
  29557. var serializationObject = _super.prototype.serialize.call(this);
  29558. serializationObject.diameter = this.diameter;
  29559. serializationObject.thickness = this.thickness;
  29560. serializationObject.tessellation = this.tessellation;
  29561. return serializationObject;
  29562. };
  29563. Torus.Parse = function (parsedTorus, scene) {
  29564. if (scene.getGeometryByID(parsedTorus.id)) {
  29565. return null; // null since geometry could be something else than a torus...
  29566. }
  29567. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29568. if (BABYLON.Tags) {
  29569. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29570. }
  29571. scene.pushGeometry(torus, true);
  29572. return torus;
  29573. };
  29574. return Torus;
  29575. }(_Primitive));
  29576. Primitives.Torus = Torus;
  29577. var Ground = (function (_super) {
  29578. __extends(Ground, _super);
  29579. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29580. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29581. _this.width = width;
  29582. _this.height = height;
  29583. _this.subdivisions = subdivisions;
  29584. return _this;
  29585. }
  29586. Ground.prototype._regenerateVertexData = function () {
  29587. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29588. };
  29589. Ground.prototype.copy = function (id) {
  29590. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29591. };
  29592. Ground.prototype.serialize = function () {
  29593. var serializationObject = _super.prototype.serialize.call(this);
  29594. serializationObject.width = this.width;
  29595. serializationObject.height = this.height;
  29596. serializationObject.subdivisions = this.subdivisions;
  29597. return serializationObject;
  29598. };
  29599. Ground.Parse = function (parsedGround, scene) {
  29600. if (scene.getGeometryByID(parsedGround.id)) {
  29601. return null; // null since geometry could be something else than a ground...
  29602. }
  29603. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29604. if (BABYLON.Tags) {
  29605. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29606. }
  29607. scene.pushGeometry(ground, true);
  29608. return ground;
  29609. };
  29610. return Ground;
  29611. }(_Primitive));
  29612. Primitives.Ground = Ground;
  29613. var TiledGround = (function (_super) {
  29614. __extends(TiledGround, _super);
  29615. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29616. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29617. _this.xmin = xmin;
  29618. _this.zmin = zmin;
  29619. _this.xmax = xmax;
  29620. _this.zmax = zmax;
  29621. _this.subdivisions = subdivisions;
  29622. _this.precision = precision;
  29623. return _this;
  29624. }
  29625. TiledGround.prototype._regenerateVertexData = function () {
  29626. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29627. };
  29628. TiledGround.prototype.copy = function (id) {
  29629. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29630. };
  29631. return TiledGround;
  29632. }(_Primitive));
  29633. Primitives.TiledGround = TiledGround;
  29634. var Plane = (function (_super) {
  29635. __extends(Plane, _super);
  29636. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29637. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29638. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29639. _this.size = size;
  29640. _this.side = side;
  29641. return _this;
  29642. }
  29643. Plane.prototype._regenerateVertexData = function () {
  29644. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29645. };
  29646. Plane.prototype.copy = function (id) {
  29647. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29648. };
  29649. Plane.prototype.serialize = function () {
  29650. var serializationObject = _super.prototype.serialize.call(this);
  29651. serializationObject.size = this.size;
  29652. return serializationObject;
  29653. };
  29654. Plane.Parse = function (parsedPlane, scene) {
  29655. if (scene.getGeometryByID(parsedPlane.id)) {
  29656. return null; // null since geometry could be something else than a ground...
  29657. }
  29658. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29659. if (BABYLON.Tags) {
  29660. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29661. }
  29662. scene.pushGeometry(plane, true);
  29663. return plane;
  29664. };
  29665. return Plane;
  29666. }(_Primitive));
  29667. Primitives.Plane = Plane;
  29668. var TorusKnot = (function (_super) {
  29669. __extends(TorusKnot, _super);
  29670. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29671. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29672. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29673. _this.radius = radius;
  29674. _this.tube = tube;
  29675. _this.radialSegments = radialSegments;
  29676. _this.tubularSegments = tubularSegments;
  29677. _this.p = p;
  29678. _this.q = q;
  29679. _this.side = side;
  29680. return _this;
  29681. }
  29682. TorusKnot.prototype._regenerateVertexData = function () {
  29683. 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 });
  29684. };
  29685. TorusKnot.prototype.copy = function (id) {
  29686. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29687. };
  29688. TorusKnot.prototype.serialize = function () {
  29689. var serializationObject = _super.prototype.serialize.call(this);
  29690. serializationObject.radius = this.radius;
  29691. serializationObject.tube = this.tube;
  29692. serializationObject.radialSegments = this.radialSegments;
  29693. serializationObject.tubularSegments = this.tubularSegments;
  29694. serializationObject.p = this.p;
  29695. serializationObject.q = this.q;
  29696. return serializationObject;
  29697. };
  29698. ;
  29699. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29700. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29701. return null; // null since geometry could be something else than a ground...
  29702. }
  29703. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29704. if (BABYLON.Tags) {
  29705. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29706. }
  29707. scene.pushGeometry(torusKnot, true);
  29708. return torusKnot;
  29709. };
  29710. return TorusKnot;
  29711. }(_Primitive));
  29712. Primitives.TorusKnot = TorusKnot;
  29713. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29714. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29715. })(BABYLON || (BABYLON = {}));
  29716. //# sourceMappingURL=babylon.geometry.js.map
  29717. var BABYLON;
  29718. (function (BABYLON) {
  29719. var PostProcessManager = (function () {
  29720. function PostProcessManager(scene) {
  29721. this._vertexBuffers = {};
  29722. this._scene = scene;
  29723. }
  29724. PostProcessManager.prototype._prepareBuffers = function () {
  29725. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29726. return;
  29727. }
  29728. // VBO
  29729. var vertices = [];
  29730. vertices.push(1, 1);
  29731. vertices.push(-1, 1);
  29732. vertices.push(-1, -1);
  29733. vertices.push(1, -1);
  29734. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29735. this._buildIndexBuffer();
  29736. };
  29737. PostProcessManager.prototype._buildIndexBuffer = function () {
  29738. // Indices
  29739. var indices = [];
  29740. indices.push(0);
  29741. indices.push(1);
  29742. indices.push(2);
  29743. indices.push(0);
  29744. indices.push(2);
  29745. indices.push(3);
  29746. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29747. };
  29748. PostProcessManager.prototype._rebuild = function () {
  29749. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29750. return;
  29751. }
  29752. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29753. this._buildIndexBuffer();
  29754. };
  29755. // Methods
  29756. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29757. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29758. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29759. return false;
  29760. }
  29761. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29762. return true;
  29763. };
  29764. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29765. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29766. var engine = this._scene.getEngine();
  29767. for (var index = 0; index < postProcesses.length; index++) {
  29768. if (index < postProcesses.length - 1) {
  29769. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29770. }
  29771. else {
  29772. if (targetTexture) {
  29773. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29774. }
  29775. else {
  29776. engine.restoreDefaultFramebuffer();
  29777. }
  29778. }
  29779. var pp = postProcesses[index];
  29780. var effect = pp.apply();
  29781. if (effect) {
  29782. pp.onBeforeRenderObservable.notifyObservers(effect);
  29783. // VBOs
  29784. this._prepareBuffers();
  29785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29786. // Draw order
  29787. engine.draw(true, 0, 6);
  29788. pp.onAfterRenderObservable.notifyObservers(effect);
  29789. }
  29790. }
  29791. // Restore depth buffer
  29792. engine.setDepthBuffer(true);
  29793. engine.setDepthWrite(true);
  29794. };
  29795. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29796. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29797. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29798. return;
  29799. }
  29800. var engine = this._scene.getEngine();
  29801. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29802. if (index < len - 1) {
  29803. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29804. }
  29805. else {
  29806. if (targetTexture) {
  29807. engine.bindFramebuffer(targetTexture, faceIndex);
  29808. }
  29809. else {
  29810. engine.restoreDefaultFramebuffer();
  29811. }
  29812. }
  29813. if (doNotPresent) {
  29814. break;
  29815. }
  29816. var pp = postProcesses[index];
  29817. var effect = pp.apply();
  29818. if (effect) {
  29819. pp.onBeforeRenderObservable.notifyObservers(effect);
  29820. // VBOs
  29821. this._prepareBuffers();
  29822. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29823. // Draw order
  29824. engine.draw(true, 0, 6);
  29825. pp.onAfterRenderObservable.notifyObservers(effect);
  29826. }
  29827. }
  29828. // Restore states
  29829. engine.setDepthBuffer(true);
  29830. engine.setDepthWrite(true);
  29831. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29832. };
  29833. PostProcessManager.prototype.dispose = function () {
  29834. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29835. if (buffer) {
  29836. buffer.dispose();
  29837. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29838. }
  29839. if (this._indexBuffer) {
  29840. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29841. this._indexBuffer = null;
  29842. }
  29843. };
  29844. return PostProcessManager;
  29845. }());
  29846. BABYLON.PostProcessManager = PostProcessManager;
  29847. })(BABYLON || (BABYLON = {}));
  29848. //# sourceMappingURL=babylon.postProcessManager.js.map
  29849. var BABYLON;
  29850. (function (BABYLON) {
  29851. /**
  29852. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29853. */
  29854. var PerformanceMonitor = (function () {
  29855. /**
  29856. * constructor
  29857. * @param frameSampleSize The number of samples required to saturate the sliding window
  29858. */
  29859. function PerformanceMonitor(frameSampleSize) {
  29860. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29861. this._enabled = true;
  29862. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29863. }
  29864. /**
  29865. * Samples current frame
  29866. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29867. */
  29868. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29869. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29870. if (!this._enabled)
  29871. return;
  29872. if (this._lastFrameTimeMs != null) {
  29873. var dt = timeMs - this._lastFrameTimeMs;
  29874. this._rollingFrameTime.add(dt);
  29875. }
  29876. this._lastFrameTimeMs = timeMs;
  29877. };
  29878. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29879. /**
  29880. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29881. * @return Average frame time in milliseconds
  29882. */
  29883. get: function () {
  29884. return this._rollingFrameTime.average;
  29885. },
  29886. enumerable: true,
  29887. configurable: true
  29888. });
  29889. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29890. /**
  29891. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29892. * @return Frame time variance in milliseconds squared
  29893. */
  29894. get: function () {
  29895. return this._rollingFrameTime.variance;
  29896. },
  29897. enumerable: true,
  29898. configurable: true
  29899. });
  29900. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29901. /**
  29902. * Returns the frame time of the most recent frame
  29903. * @return Frame time in milliseconds
  29904. */
  29905. get: function () {
  29906. return this._rollingFrameTime.history(0);
  29907. },
  29908. enumerable: true,
  29909. configurable: true
  29910. });
  29911. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29912. /**
  29913. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29914. * @return Framerate in frames per second
  29915. */
  29916. get: function () {
  29917. return 1000.0 / this._rollingFrameTime.average;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29923. /**
  29924. * Returns the average framerate in frames per second using the most recent frame time
  29925. * @return Framerate in frames per second
  29926. */
  29927. get: function () {
  29928. return 1000.0 / this._rollingFrameTime.history(0);
  29929. },
  29930. enumerable: true,
  29931. configurable: true
  29932. });
  29933. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29934. /**
  29935. * Returns true if enough samples have been taken to completely fill the sliding window
  29936. * @return true if saturated
  29937. */
  29938. get: function () {
  29939. return this._rollingFrameTime.isSaturated();
  29940. },
  29941. enumerable: true,
  29942. configurable: true
  29943. });
  29944. /**
  29945. * Enables contributions to the sliding window sample set
  29946. */
  29947. PerformanceMonitor.prototype.enable = function () {
  29948. this._enabled = true;
  29949. };
  29950. /**
  29951. * Disables contributions to the sliding window sample set
  29952. * Samples will not be interpolated over the disabled period
  29953. */
  29954. PerformanceMonitor.prototype.disable = function () {
  29955. this._enabled = false;
  29956. //clear last sample to avoid interpolating over the disabled period when next enabled
  29957. this._lastFrameTimeMs = null;
  29958. this._lastChangeTimeMs = null;
  29959. };
  29960. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29961. /**
  29962. * Returns true if sampling is enabled
  29963. * @return true if enabled
  29964. */
  29965. get: function () {
  29966. return this._enabled;
  29967. },
  29968. enumerable: true,
  29969. configurable: true
  29970. });
  29971. /**
  29972. * Resets performance monitor
  29973. */
  29974. PerformanceMonitor.prototype.reset = function () {
  29975. //clear last sample to avoid interpolating over the disabled period when next enabled
  29976. this._lastFrameTimeMs = null;
  29977. this._lastChangeTimeMs = null;
  29978. //wipe record
  29979. this._rollingFrameTime.reset();
  29980. };
  29981. return PerformanceMonitor;
  29982. }());
  29983. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29984. /**
  29985. * RollingAverage
  29986. *
  29987. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29988. */
  29989. var RollingAverage = (function () {
  29990. /**
  29991. * constructor
  29992. * @param length The number of samples required to saturate the sliding window
  29993. */
  29994. function RollingAverage(length) {
  29995. this._samples = new Array(length);
  29996. this.reset();
  29997. }
  29998. /**
  29999. * Adds a sample to the sample set
  30000. * @param v The sample value
  30001. */
  30002. RollingAverage.prototype.add = function (v) {
  30003. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30004. var delta;
  30005. //we need to check if we've already wrapped round
  30006. if (this.isSaturated()) {
  30007. //remove bottom of stack from mean
  30008. var bottomValue = this._samples[this._pos];
  30009. delta = bottomValue - this.average;
  30010. this.average -= delta / (this._sampleCount - 1);
  30011. this._m2 -= delta * (bottomValue - this.average);
  30012. }
  30013. else {
  30014. this._sampleCount++;
  30015. }
  30016. //add new value to mean
  30017. delta = v - this.average;
  30018. this.average += delta / (this._sampleCount);
  30019. this._m2 += delta * (v - this.average);
  30020. //set the new variance
  30021. this.variance = this._m2 / (this._sampleCount - 1);
  30022. this._samples[this._pos] = v;
  30023. this._pos++;
  30024. this._pos %= this._samples.length; //positive wrap around
  30025. };
  30026. /**
  30027. * Returns previously added values or null if outside of history or outside the sliding window domain
  30028. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30029. * @return Value previously recorded with add() or null if outside of range
  30030. */
  30031. RollingAverage.prototype.history = function (i) {
  30032. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30033. return null;
  30034. }
  30035. var i0 = this._wrapPosition(this._pos - 1.0);
  30036. return this._samples[this._wrapPosition(i0 - i)];
  30037. };
  30038. /**
  30039. * Returns true if enough samples have been taken to completely fill the sliding window
  30040. * @return true if sample-set saturated
  30041. */
  30042. RollingAverage.prototype.isSaturated = function () {
  30043. return this._sampleCount >= this._samples.length;
  30044. };
  30045. /**
  30046. * Resets the rolling average (equivalent to 0 samples taken so far)
  30047. */
  30048. RollingAverage.prototype.reset = function () {
  30049. this.average = 0;
  30050. this.variance = 0;
  30051. this._sampleCount = 0;
  30052. this._pos = 0;
  30053. this._m2 = 0;
  30054. };
  30055. /**
  30056. * Wraps a value around the sample range boundaries
  30057. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30058. * @return Wrapped position in sample range
  30059. */
  30060. RollingAverage.prototype._wrapPosition = function (i) {
  30061. var max = this._samples.length;
  30062. return ((i % max) + max) % max;
  30063. };
  30064. return RollingAverage;
  30065. }());
  30066. BABYLON.RollingAverage = RollingAverage;
  30067. })(BABYLON || (BABYLON = {}));
  30068. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30069. var BABYLON;
  30070. (function (BABYLON) {
  30071. var AnimationRange = (function () {
  30072. function AnimationRange(name, from, to) {
  30073. this.name = name;
  30074. this.from = from;
  30075. this.to = to;
  30076. }
  30077. AnimationRange.prototype.clone = function () {
  30078. return new AnimationRange(this.name, this.from, this.to);
  30079. };
  30080. return AnimationRange;
  30081. }());
  30082. BABYLON.AnimationRange = AnimationRange;
  30083. /**
  30084. * Composed of a frame, and an action function
  30085. */
  30086. var AnimationEvent = (function () {
  30087. function AnimationEvent(frame, action, onlyOnce) {
  30088. this.frame = frame;
  30089. this.action = action;
  30090. this.onlyOnce = onlyOnce;
  30091. this.isDone = false;
  30092. }
  30093. return AnimationEvent;
  30094. }());
  30095. BABYLON.AnimationEvent = AnimationEvent;
  30096. var PathCursor = (function () {
  30097. function PathCursor(path) {
  30098. this.path = path;
  30099. this._onchange = new Array();
  30100. this.value = 0;
  30101. this.animations = new Array();
  30102. }
  30103. PathCursor.prototype.getPoint = function () {
  30104. var point = this.path.getPointAtLengthPosition(this.value);
  30105. return new BABYLON.Vector3(point.x, 0, point.y);
  30106. };
  30107. PathCursor.prototype.moveAhead = function (step) {
  30108. if (step === void 0) { step = 0.002; }
  30109. this.move(step);
  30110. return this;
  30111. };
  30112. PathCursor.prototype.moveBack = function (step) {
  30113. if (step === void 0) { step = 0.002; }
  30114. this.move(-step);
  30115. return this;
  30116. };
  30117. PathCursor.prototype.move = function (step) {
  30118. if (Math.abs(step) > 1) {
  30119. throw "step size should be less than 1.";
  30120. }
  30121. this.value += step;
  30122. this.ensureLimits();
  30123. this.raiseOnChange();
  30124. return this;
  30125. };
  30126. PathCursor.prototype.ensureLimits = function () {
  30127. while (this.value > 1) {
  30128. this.value -= 1;
  30129. }
  30130. while (this.value < 0) {
  30131. this.value += 1;
  30132. }
  30133. return this;
  30134. };
  30135. // used by animation engine
  30136. PathCursor.prototype.markAsDirty = function (propertyName) {
  30137. this.ensureLimits();
  30138. this.raiseOnChange();
  30139. return this;
  30140. };
  30141. PathCursor.prototype.raiseOnChange = function () {
  30142. var _this = this;
  30143. this._onchange.forEach(function (f) { return f(_this); });
  30144. return this;
  30145. };
  30146. PathCursor.prototype.onchange = function (f) {
  30147. this._onchange.push(f);
  30148. return this;
  30149. };
  30150. return PathCursor;
  30151. }());
  30152. BABYLON.PathCursor = PathCursor;
  30153. var Animation = (function () {
  30154. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30155. this.name = name;
  30156. this.targetProperty = targetProperty;
  30157. this.framePerSecond = framePerSecond;
  30158. this.dataType = dataType;
  30159. this.loopMode = loopMode;
  30160. this.enableBlending = enableBlending;
  30161. this._offsetsCache = {};
  30162. this._highLimitsCache = {};
  30163. this._stopped = false;
  30164. this._blendingFactor = 0;
  30165. // The set of event that will be linked to this animation
  30166. this._events = new Array();
  30167. this.allowMatricesInterpolation = false;
  30168. this.blendingSpeed = 0.01;
  30169. this._ranges = {};
  30170. this.targetPropertyPath = targetProperty.split(".");
  30171. this.dataType = dataType;
  30172. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30173. }
  30174. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30175. var dataType = undefined;
  30176. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30177. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30178. }
  30179. else if (from instanceof BABYLON.Quaternion) {
  30180. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30181. }
  30182. else if (from instanceof BABYLON.Vector3) {
  30183. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30184. }
  30185. else if (from instanceof BABYLON.Vector2) {
  30186. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30187. }
  30188. else if (from instanceof BABYLON.Color3) {
  30189. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30190. }
  30191. else if (from instanceof BABYLON.Size) {
  30192. dataType = Animation.ANIMATIONTYPE_SIZE;
  30193. }
  30194. if (dataType == undefined) {
  30195. return null;
  30196. }
  30197. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30198. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30199. animation.setKeys(keys);
  30200. if (easingFunction !== undefined) {
  30201. animation.setEasingFunction(easingFunction);
  30202. }
  30203. return animation;
  30204. };
  30205. /**
  30206. * Sets up an animation.
  30207. * @param property the property to animate
  30208. * @param animationType the animation type to apply
  30209. * @param easingFunction the easing function used in the animation
  30210. * @returns The created animation
  30211. */
  30212. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  30213. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30214. animation.setEasingFunction(easingFunction);
  30215. return animation;
  30216. };
  30217. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30218. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30219. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30220. };
  30221. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30222. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30223. node.animations.push(animation);
  30224. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30225. };
  30226. /**
  30227. * Transition property of the Camera to the target Value.
  30228. * @param property The property to transition
  30229. * @param targetValue The target Value of the property
  30230. * @param host The object where the property to animate belongs
  30231. * @param scene Scene used to run the animation
  30232. * @param frameRate Framerate (in frame/s) to use
  30233. * @param transition The transition type we want to use
  30234. * @param duration The duration of the animation, in milliseconds
  30235. * @param onAnimationEnd Call back trigger at the end of the animation.
  30236. */
  30237. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  30238. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  30239. if (duration <= 0) {
  30240. host[property] = targetValue;
  30241. if (onAnimationEnd) {
  30242. onAnimationEnd();
  30243. }
  30244. return;
  30245. }
  30246. var endFrame = frameRate * (duration / 1000);
  30247. transition.setKeys([{
  30248. frame: 0,
  30249. value: host[property].clone ? host[property].clone() : host[property]
  30250. },
  30251. {
  30252. frame: endFrame,
  30253. value: targetValue
  30254. }]);
  30255. if (!host.animations) {
  30256. host.animations = [];
  30257. }
  30258. host.animations.push(transition);
  30259. var animation = scene.beginAnimation(host, 0, endFrame, false);
  30260. animation.onAnimationEnd = onAnimationEnd;
  30261. return animation;
  30262. };
  30263. // Methods
  30264. /**
  30265. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30266. */
  30267. Animation.prototype.toString = function (fullDetails) {
  30268. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30269. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30270. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30271. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30272. if (fullDetails) {
  30273. ret += ", Ranges: {";
  30274. var first = true;
  30275. for (var name in this._ranges) {
  30276. if (first) {
  30277. ret += ", ";
  30278. first = false;
  30279. }
  30280. ret += name;
  30281. }
  30282. ret += "}";
  30283. }
  30284. return ret;
  30285. };
  30286. /**
  30287. * Add an event to this animation.
  30288. */
  30289. Animation.prototype.addEvent = function (event) {
  30290. this._events.push(event);
  30291. };
  30292. /**
  30293. * Remove all events found at the given frame
  30294. * @param frame
  30295. */
  30296. Animation.prototype.removeEvents = function (frame) {
  30297. for (var index = 0; index < this._events.length; index++) {
  30298. if (this._events[index].frame === frame) {
  30299. this._events.splice(index, 1);
  30300. index--;
  30301. }
  30302. }
  30303. };
  30304. Animation.prototype.createRange = function (name, from, to) {
  30305. // check name not already in use; could happen for bones after serialized
  30306. if (!this._ranges[name]) {
  30307. this._ranges[name] = new AnimationRange(name, from, to);
  30308. }
  30309. };
  30310. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30311. if (deleteFrames === void 0) { deleteFrames = true; }
  30312. if (this._ranges[name]) {
  30313. if (deleteFrames) {
  30314. var from = this._ranges[name].from;
  30315. var to = this._ranges[name].to;
  30316. // this loop MUST go high to low for multiple splices to work
  30317. for (var key = this._keys.length - 1; key >= 0; key--) {
  30318. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30319. this._keys.splice(key, 1);
  30320. }
  30321. }
  30322. }
  30323. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30324. }
  30325. };
  30326. Animation.prototype.getRange = function (name) {
  30327. return this._ranges[name];
  30328. };
  30329. Animation.prototype.reset = function () {
  30330. this._offsetsCache = {};
  30331. this._highLimitsCache = {};
  30332. this.currentFrame = 0;
  30333. this._blendingFactor = 0;
  30334. this._originalBlendValue = null;
  30335. };
  30336. Animation.prototype.isStopped = function () {
  30337. return this._stopped;
  30338. };
  30339. Animation.prototype.getKeys = function () {
  30340. return this._keys;
  30341. };
  30342. Animation.prototype.getHighestFrame = function () {
  30343. var ret = 0;
  30344. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30345. if (ret < this._keys[key].frame) {
  30346. ret = this._keys[key].frame;
  30347. }
  30348. }
  30349. return ret;
  30350. };
  30351. Animation.prototype.getEasingFunction = function () {
  30352. return this._easingFunction;
  30353. };
  30354. Animation.prototype.setEasingFunction = function (easingFunction) {
  30355. this._easingFunction = easingFunction;
  30356. };
  30357. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30358. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30359. };
  30360. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30361. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30362. };
  30363. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30364. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30365. };
  30366. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30367. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30368. };
  30369. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30370. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30371. };
  30372. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30373. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30374. };
  30375. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30376. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30377. };
  30378. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30379. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30380. };
  30381. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30382. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30383. };
  30384. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30385. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30386. };
  30387. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30388. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30389. };
  30390. Animation.prototype.clone = function () {
  30391. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30392. clone.enableBlending = this.enableBlending;
  30393. clone.blendingSpeed = this.blendingSpeed;
  30394. if (this._keys) {
  30395. clone.setKeys(this._keys);
  30396. }
  30397. if (this._ranges) {
  30398. clone._ranges = {};
  30399. for (var name in this._ranges) {
  30400. clone._ranges[name] = this._ranges[name].clone();
  30401. }
  30402. }
  30403. return clone;
  30404. };
  30405. Animation.prototype.setKeys = function (values) {
  30406. this._keys = values.slice(0);
  30407. this._offsetsCache = {};
  30408. this._highLimitsCache = {};
  30409. };
  30410. Animation.prototype._getKeyValue = function (value) {
  30411. if (typeof value === "function") {
  30412. return value();
  30413. }
  30414. return value;
  30415. };
  30416. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30417. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30418. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30419. }
  30420. this.currentFrame = currentFrame;
  30421. // Try to get a hash to find the right key
  30422. 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));
  30423. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30424. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30425. startKeyIndex--;
  30426. }
  30427. }
  30428. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30429. var endKey = this._keys[key + 1];
  30430. if (endKey.frame >= currentFrame) {
  30431. var startKey = this._keys[key];
  30432. var startValue = this._getKeyValue(startKey.value);
  30433. var endValue = this._getKeyValue(endKey.value);
  30434. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30435. var frameDelta = endKey.frame - startKey.frame;
  30436. // gradient : percent of currentFrame between the frame inf and the frame sup
  30437. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30438. // check for easingFunction and correction of gradient
  30439. if (this._easingFunction != null) {
  30440. gradient = this._easingFunction.ease(gradient);
  30441. }
  30442. switch (this.dataType) {
  30443. // Float
  30444. case Animation.ANIMATIONTYPE_FLOAT:
  30445. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30446. switch (loopMode) {
  30447. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30448. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30449. return floatValue;
  30450. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30451. return offsetValue * repeatCount + floatValue;
  30452. }
  30453. break;
  30454. // Quaternion
  30455. case Animation.ANIMATIONTYPE_QUATERNION:
  30456. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30457. switch (loopMode) {
  30458. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30459. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30460. return quatValue;
  30461. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30462. return quatValue.add(offsetValue.scale(repeatCount));
  30463. }
  30464. return quatValue;
  30465. // Vector3
  30466. case Animation.ANIMATIONTYPE_VECTOR3:
  30467. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30468. switch (loopMode) {
  30469. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30470. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30471. return vec3Value;
  30472. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30473. return vec3Value.add(offsetValue.scale(repeatCount));
  30474. }
  30475. // Vector2
  30476. case Animation.ANIMATIONTYPE_VECTOR2:
  30477. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30478. switch (loopMode) {
  30479. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30480. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30481. return vec2Value;
  30482. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30483. return vec2Value.add(offsetValue.scale(repeatCount));
  30484. }
  30485. // Size
  30486. case Animation.ANIMATIONTYPE_SIZE:
  30487. switch (loopMode) {
  30488. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30489. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30490. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30491. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30492. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30493. }
  30494. // Color3
  30495. case Animation.ANIMATIONTYPE_COLOR3:
  30496. switch (loopMode) {
  30497. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30498. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30499. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30500. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30501. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30502. }
  30503. // Matrix
  30504. case Animation.ANIMATIONTYPE_MATRIX:
  30505. switch (loopMode) {
  30506. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30507. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30508. if (this.allowMatricesInterpolation) {
  30509. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30510. }
  30511. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30512. return startValue;
  30513. }
  30514. default:
  30515. break;
  30516. }
  30517. break;
  30518. }
  30519. }
  30520. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30521. };
  30522. Animation.prototype.setValue = function (currentValue, blend) {
  30523. if (blend === void 0) { blend = false; }
  30524. // Set value
  30525. var path;
  30526. var destination;
  30527. if (this.targetPropertyPath.length > 1) {
  30528. var property = this._target[this.targetPropertyPath[0]];
  30529. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30530. property = property[this.targetPropertyPath[index]];
  30531. }
  30532. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30533. destination = property;
  30534. }
  30535. else {
  30536. path = this.targetPropertyPath[0];
  30537. destination = this._target;
  30538. }
  30539. // Blending
  30540. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30541. if (!this._originalBlendValue) {
  30542. if (destination[path].clone) {
  30543. this._originalBlendValue = destination[path].clone();
  30544. }
  30545. else {
  30546. this._originalBlendValue = destination[path];
  30547. }
  30548. }
  30549. if (this._originalBlendValue.prototype) {
  30550. if (this._originalBlendValue.prototype.Lerp) {
  30551. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30552. }
  30553. else {
  30554. destination[path] = currentValue;
  30555. }
  30556. }
  30557. else if (this._originalBlendValue.m) {
  30558. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30559. }
  30560. else {
  30561. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30562. }
  30563. this._blendingFactor += this.blendingSpeed;
  30564. }
  30565. else {
  30566. destination[path] = currentValue;
  30567. }
  30568. if (this._target.markAsDirty) {
  30569. this._target.markAsDirty(this.targetProperty);
  30570. }
  30571. };
  30572. Animation.prototype.goToFrame = function (frame) {
  30573. if (frame < this._keys[0].frame) {
  30574. frame = this._keys[0].frame;
  30575. }
  30576. else if (frame > this._keys[this._keys.length - 1].frame) {
  30577. frame = this._keys[this._keys.length - 1].frame;
  30578. }
  30579. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30580. this.setValue(currentValue);
  30581. };
  30582. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30583. if (blend === void 0) { blend = false; }
  30584. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30585. this._stopped = true;
  30586. return false;
  30587. }
  30588. var returnValue = true;
  30589. // Adding a start key at frame 0 if missing
  30590. if (this._keys[0].frame !== 0) {
  30591. var newKey = { frame: 0, value: this._keys[0].value };
  30592. this._keys.splice(0, 0, newKey);
  30593. }
  30594. // Check limits
  30595. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30596. from = this._keys[0].frame;
  30597. }
  30598. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30599. to = this._keys[this._keys.length - 1].frame;
  30600. }
  30601. //to and from cannot be the same key
  30602. if (from === to) {
  30603. from++;
  30604. }
  30605. // Compute ratio
  30606. var range = to - from;
  30607. var offsetValue;
  30608. // ratio represents the frame delta between from and to
  30609. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30610. var highLimitValue = 0;
  30611. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30612. returnValue = false;
  30613. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30614. }
  30615. else {
  30616. // Get max value if required
  30617. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30618. var keyOffset = to.toString() + from.toString();
  30619. if (!this._offsetsCache[keyOffset]) {
  30620. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30621. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30622. switch (this.dataType) {
  30623. // Float
  30624. case Animation.ANIMATIONTYPE_FLOAT:
  30625. this._offsetsCache[keyOffset] = toValue - fromValue;
  30626. break;
  30627. // Quaternion
  30628. case Animation.ANIMATIONTYPE_QUATERNION:
  30629. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30630. break;
  30631. // Vector3
  30632. case Animation.ANIMATIONTYPE_VECTOR3:
  30633. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30634. // Vector2
  30635. case Animation.ANIMATIONTYPE_VECTOR2:
  30636. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30637. // Size
  30638. case Animation.ANIMATIONTYPE_SIZE:
  30639. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30640. // Color3
  30641. case Animation.ANIMATIONTYPE_COLOR3:
  30642. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30643. default:
  30644. break;
  30645. }
  30646. this._highLimitsCache[keyOffset] = toValue;
  30647. }
  30648. highLimitValue = this._highLimitsCache[keyOffset];
  30649. offsetValue = this._offsetsCache[keyOffset];
  30650. }
  30651. }
  30652. if (offsetValue === undefined) {
  30653. switch (this.dataType) {
  30654. // Float
  30655. case Animation.ANIMATIONTYPE_FLOAT:
  30656. offsetValue = 0;
  30657. break;
  30658. // Quaternion
  30659. case Animation.ANIMATIONTYPE_QUATERNION:
  30660. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30661. break;
  30662. // Vector3
  30663. case Animation.ANIMATIONTYPE_VECTOR3:
  30664. offsetValue = BABYLON.Vector3.Zero();
  30665. break;
  30666. // Vector2
  30667. case Animation.ANIMATIONTYPE_VECTOR2:
  30668. offsetValue = BABYLON.Vector2.Zero();
  30669. break;
  30670. // Size
  30671. case Animation.ANIMATIONTYPE_SIZE:
  30672. offsetValue = BABYLON.Size.Zero();
  30673. break;
  30674. // Color3
  30675. case Animation.ANIMATIONTYPE_COLOR3:
  30676. offsetValue = BABYLON.Color3.Black();
  30677. }
  30678. }
  30679. // Compute value
  30680. var repeatCount = (ratio / range) >> 0;
  30681. var currentFrame = returnValue ? from + ratio % range : to;
  30682. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30683. // Set value
  30684. this.setValue(currentValue);
  30685. // Check events
  30686. for (var index = 0; index < this._events.length; index++) {
  30687. // Make sure current frame has passed event frame and that event frame is within the current range
  30688. // Also, handle both forward and reverse animations
  30689. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30690. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30691. var event = this._events[index];
  30692. if (!event.isDone) {
  30693. // If event should be done only once, remove it.
  30694. if (event.onlyOnce) {
  30695. this._events.splice(index, 1);
  30696. index--;
  30697. }
  30698. event.isDone = true;
  30699. event.action();
  30700. } // Don't do anything if the event has already be done.
  30701. }
  30702. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30703. // reset event, the animation is looping
  30704. this._events[index].isDone = false;
  30705. }
  30706. }
  30707. if (!returnValue) {
  30708. this._stopped = true;
  30709. }
  30710. return returnValue;
  30711. };
  30712. Animation.prototype.serialize = function () {
  30713. var serializationObject = {};
  30714. serializationObject.name = this.name;
  30715. serializationObject.property = this.targetProperty;
  30716. serializationObject.framePerSecond = this.framePerSecond;
  30717. serializationObject.dataType = this.dataType;
  30718. serializationObject.loopBehavior = this.loopMode;
  30719. serializationObject.enableBlending = this.enableBlending;
  30720. serializationObject.blendingSpeed = this.blendingSpeed;
  30721. var dataType = this.dataType;
  30722. serializationObject.keys = [];
  30723. var keys = this.getKeys();
  30724. for (var index = 0; index < keys.length; index++) {
  30725. var animationKey = keys[index];
  30726. var key = {};
  30727. key.frame = animationKey.frame;
  30728. switch (dataType) {
  30729. case Animation.ANIMATIONTYPE_FLOAT:
  30730. key.values = [animationKey.value];
  30731. break;
  30732. case Animation.ANIMATIONTYPE_QUATERNION:
  30733. case Animation.ANIMATIONTYPE_MATRIX:
  30734. case Animation.ANIMATIONTYPE_VECTOR3:
  30735. case Animation.ANIMATIONTYPE_COLOR3:
  30736. key.values = animationKey.value.asArray();
  30737. break;
  30738. }
  30739. serializationObject.keys.push(key);
  30740. }
  30741. serializationObject.ranges = [];
  30742. for (var name in this._ranges) {
  30743. var range = {};
  30744. range.name = name;
  30745. range.from = this._ranges[name].from;
  30746. range.to = this._ranges[name].to;
  30747. serializationObject.ranges.push(range);
  30748. }
  30749. return serializationObject;
  30750. };
  30751. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30752. get: function () {
  30753. return Animation._ANIMATIONTYPE_FLOAT;
  30754. },
  30755. enumerable: true,
  30756. configurable: true
  30757. });
  30758. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30759. get: function () {
  30760. return Animation._ANIMATIONTYPE_VECTOR3;
  30761. },
  30762. enumerable: true,
  30763. configurable: true
  30764. });
  30765. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30766. get: function () {
  30767. return Animation._ANIMATIONTYPE_VECTOR2;
  30768. },
  30769. enumerable: true,
  30770. configurable: true
  30771. });
  30772. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30773. get: function () {
  30774. return Animation._ANIMATIONTYPE_SIZE;
  30775. },
  30776. enumerable: true,
  30777. configurable: true
  30778. });
  30779. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30780. get: function () {
  30781. return Animation._ANIMATIONTYPE_QUATERNION;
  30782. },
  30783. enumerable: true,
  30784. configurable: true
  30785. });
  30786. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30787. get: function () {
  30788. return Animation._ANIMATIONTYPE_MATRIX;
  30789. },
  30790. enumerable: true,
  30791. configurable: true
  30792. });
  30793. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30794. get: function () {
  30795. return Animation._ANIMATIONTYPE_COLOR3;
  30796. },
  30797. enumerable: true,
  30798. configurable: true
  30799. });
  30800. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30801. get: function () {
  30802. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30808. get: function () {
  30809. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30810. },
  30811. enumerable: true,
  30812. configurable: true
  30813. });
  30814. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30815. get: function () {
  30816. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30817. },
  30818. enumerable: true,
  30819. configurable: true
  30820. });
  30821. Animation.Parse = function (parsedAnimation) {
  30822. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30823. var dataType = parsedAnimation.dataType;
  30824. var keys = [];
  30825. var data;
  30826. var index;
  30827. if (parsedAnimation.enableBlending) {
  30828. animation.enableBlending = parsedAnimation.enableBlending;
  30829. }
  30830. if (parsedAnimation.blendingSpeed) {
  30831. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30832. }
  30833. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30834. var key = parsedAnimation.keys[index];
  30835. switch (dataType) {
  30836. case Animation.ANIMATIONTYPE_FLOAT:
  30837. data = key.values[0];
  30838. break;
  30839. case Animation.ANIMATIONTYPE_QUATERNION:
  30840. data = BABYLON.Quaternion.FromArray(key.values);
  30841. break;
  30842. case Animation.ANIMATIONTYPE_MATRIX:
  30843. data = BABYLON.Matrix.FromArray(key.values);
  30844. break;
  30845. case Animation.ANIMATIONTYPE_COLOR3:
  30846. data = BABYLON.Color3.FromArray(key.values);
  30847. break;
  30848. case Animation.ANIMATIONTYPE_VECTOR3:
  30849. default:
  30850. data = BABYLON.Vector3.FromArray(key.values);
  30851. break;
  30852. }
  30853. keys.push({
  30854. frame: key.frame,
  30855. value: data
  30856. });
  30857. }
  30858. animation.setKeys(keys);
  30859. if (parsedAnimation.ranges) {
  30860. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30861. data = parsedAnimation.ranges[index];
  30862. animation.createRange(data.name, data.from, data.to);
  30863. }
  30864. }
  30865. return animation;
  30866. };
  30867. Animation.AppendSerializedAnimations = function (source, destination) {
  30868. if (source.animations) {
  30869. destination.animations = [];
  30870. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30871. var animation = source.animations[animationIndex];
  30872. destination.animations.push(animation.serialize());
  30873. }
  30874. }
  30875. };
  30876. // Statics
  30877. Animation._ANIMATIONTYPE_FLOAT = 0;
  30878. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30879. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30880. Animation._ANIMATIONTYPE_MATRIX = 3;
  30881. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30882. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30883. Animation._ANIMATIONTYPE_SIZE = 6;
  30884. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30885. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30886. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30887. return Animation;
  30888. }());
  30889. BABYLON.Animation = Animation;
  30890. })(BABYLON || (BABYLON = {}));
  30891. //# sourceMappingURL=babylon.animation.js.map
  30892. var BABYLON;
  30893. (function (BABYLON) {
  30894. var Animatable = (function () {
  30895. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30896. if (fromFrame === void 0) { fromFrame = 0; }
  30897. if (toFrame === void 0) { toFrame = 100; }
  30898. if (loopAnimation === void 0) { loopAnimation = false; }
  30899. if (speedRatio === void 0) { speedRatio = 1.0; }
  30900. this.target = target;
  30901. this.fromFrame = fromFrame;
  30902. this.toFrame = toFrame;
  30903. this.loopAnimation = loopAnimation;
  30904. this.speedRatio = speedRatio;
  30905. this.onAnimationEnd = onAnimationEnd;
  30906. this._localDelayOffset = null;
  30907. this._pausedDelay = null;
  30908. this._animations = new Array();
  30909. this._paused = false;
  30910. this.animationStarted = false;
  30911. if (animations) {
  30912. this.appendAnimations(target, animations);
  30913. }
  30914. this._scene = scene;
  30915. scene._activeAnimatables.push(this);
  30916. }
  30917. // Methods
  30918. Animatable.prototype.getAnimations = function () {
  30919. return this._animations;
  30920. };
  30921. Animatable.prototype.appendAnimations = function (target, animations) {
  30922. for (var index = 0; index < animations.length; index++) {
  30923. var animation = animations[index];
  30924. animation._target = target;
  30925. this._animations.push(animation);
  30926. }
  30927. };
  30928. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30929. var animations = this._animations;
  30930. for (var index = 0; index < animations.length; index++) {
  30931. if (animations[index].targetProperty === property) {
  30932. return animations[index];
  30933. }
  30934. }
  30935. return null;
  30936. };
  30937. Animatable.prototype.reset = function () {
  30938. var animations = this._animations;
  30939. for (var index = 0; index < animations.length; index++) {
  30940. animations[index].reset();
  30941. }
  30942. this._localDelayOffset = null;
  30943. this._pausedDelay = null;
  30944. };
  30945. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30946. var animations = this._animations;
  30947. for (var index = 0; index < animations.length; index++) {
  30948. animations[index].enableBlending = true;
  30949. animations[index].blendingSpeed = blendingSpeed;
  30950. }
  30951. };
  30952. Animatable.prototype.disableBlending = function () {
  30953. var animations = this._animations;
  30954. for (var index = 0; index < animations.length; index++) {
  30955. animations[index].enableBlending = false;
  30956. }
  30957. };
  30958. Animatable.prototype.goToFrame = function (frame) {
  30959. var animations = this._animations;
  30960. if (animations[0]) {
  30961. var fps = animations[0].framePerSecond;
  30962. var currentFrame = animations[0].currentFrame;
  30963. var adjustTime = frame - currentFrame;
  30964. var delay = adjustTime * 1000 / fps;
  30965. this._localDelayOffset -= delay;
  30966. }
  30967. for (var index = 0; index < animations.length; index++) {
  30968. animations[index].goToFrame(frame);
  30969. }
  30970. };
  30971. Animatable.prototype.pause = function () {
  30972. if (this._paused) {
  30973. return;
  30974. }
  30975. this._paused = true;
  30976. };
  30977. Animatable.prototype.restart = function () {
  30978. this._paused = false;
  30979. };
  30980. Animatable.prototype.stop = function (animationName) {
  30981. if (animationName) {
  30982. var idx = this._scene._activeAnimatables.indexOf(this);
  30983. if (idx > -1) {
  30984. var animations = this._animations;
  30985. for (var index = animations.length - 1; index >= 0; index--) {
  30986. if (typeof animationName === "string" && animations[index].name != animationName) {
  30987. continue;
  30988. }
  30989. animations[index].reset();
  30990. animations.splice(index, 1);
  30991. }
  30992. if (animations.length == 0) {
  30993. this._scene._activeAnimatables.splice(idx, 1);
  30994. if (this.onAnimationEnd) {
  30995. this.onAnimationEnd();
  30996. }
  30997. }
  30998. }
  30999. }
  31000. else {
  31001. var index = this._scene._activeAnimatables.indexOf(this);
  31002. if (index > -1) {
  31003. this._scene._activeAnimatables.splice(index, 1);
  31004. var animations = this._animations;
  31005. for (var index = 0; index < animations.length; index++) {
  31006. animations[index].reset();
  31007. }
  31008. if (this.onAnimationEnd) {
  31009. this.onAnimationEnd();
  31010. }
  31011. }
  31012. }
  31013. };
  31014. Animatable.prototype._animate = function (delay) {
  31015. if (this._paused) {
  31016. this.animationStarted = false;
  31017. if (this._pausedDelay === null) {
  31018. this._pausedDelay = delay;
  31019. }
  31020. return true;
  31021. }
  31022. if (this._localDelayOffset === null) {
  31023. this._localDelayOffset = delay;
  31024. }
  31025. else if (this._pausedDelay !== null) {
  31026. this._localDelayOffset += delay - this._pausedDelay;
  31027. this._pausedDelay = null;
  31028. }
  31029. // Animating
  31030. var running = false;
  31031. var animations = this._animations;
  31032. var index;
  31033. for (index = 0; index < animations.length; index++) {
  31034. var animation = animations[index];
  31035. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  31036. running = running || isRunning;
  31037. }
  31038. this.animationStarted = running;
  31039. if (!running) {
  31040. // Remove from active animatables
  31041. index = this._scene._activeAnimatables.indexOf(this);
  31042. this._scene._activeAnimatables.splice(index, 1);
  31043. }
  31044. if (!running && this.onAnimationEnd) {
  31045. this.onAnimationEnd();
  31046. this.onAnimationEnd = null;
  31047. }
  31048. return running;
  31049. };
  31050. return Animatable;
  31051. }());
  31052. BABYLON.Animatable = Animatable;
  31053. })(BABYLON || (BABYLON = {}));
  31054. //# sourceMappingURL=babylon.animatable.js.map
  31055. var BABYLON;
  31056. (function (BABYLON) {
  31057. var EasingFunction = (function () {
  31058. function EasingFunction() {
  31059. // Properties
  31060. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  31061. }
  31062. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  31063. get: function () {
  31064. return EasingFunction._EASINGMODE_EASEIN;
  31065. },
  31066. enumerable: true,
  31067. configurable: true
  31068. });
  31069. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  31070. get: function () {
  31071. return EasingFunction._EASINGMODE_EASEOUT;
  31072. },
  31073. enumerable: true,
  31074. configurable: true
  31075. });
  31076. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  31077. get: function () {
  31078. return EasingFunction._EASINGMODE_EASEINOUT;
  31079. },
  31080. enumerable: true,
  31081. configurable: true
  31082. });
  31083. EasingFunction.prototype.setEasingMode = function (easingMode) {
  31084. var n = Math.min(Math.max(easingMode, 0), 2);
  31085. this._easingMode = n;
  31086. };
  31087. EasingFunction.prototype.getEasingMode = function () {
  31088. return this._easingMode;
  31089. };
  31090. EasingFunction.prototype.easeInCore = function (gradient) {
  31091. throw new Error('You must implement this method');
  31092. };
  31093. EasingFunction.prototype.ease = function (gradient) {
  31094. switch (this._easingMode) {
  31095. case EasingFunction.EASINGMODE_EASEIN:
  31096. return this.easeInCore(gradient);
  31097. case EasingFunction.EASINGMODE_EASEOUT:
  31098. return (1 - this.easeInCore(1 - gradient));
  31099. }
  31100. if (gradient >= 0.5) {
  31101. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  31102. }
  31103. return (this.easeInCore(gradient * 2) * 0.5);
  31104. };
  31105. //Statics
  31106. EasingFunction._EASINGMODE_EASEIN = 0;
  31107. EasingFunction._EASINGMODE_EASEOUT = 1;
  31108. EasingFunction._EASINGMODE_EASEINOUT = 2;
  31109. return EasingFunction;
  31110. }());
  31111. BABYLON.EasingFunction = EasingFunction;
  31112. var CircleEase = (function (_super) {
  31113. __extends(CircleEase, _super);
  31114. function CircleEase() {
  31115. return _super !== null && _super.apply(this, arguments) || this;
  31116. }
  31117. CircleEase.prototype.easeInCore = function (gradient) {
  31118. gradient = Math.max(0, Math.min(1, gradient));
  31119. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  31120. };
  31121. return CircleEase;
  31122. }(EasingFunction));
  31123. BABYLON.CircleEase = CircleEase;
  31124. var BackEase = (function (_super) {
  31125. __extends(BackEase, _super);
  31126. function BackEase(amplitude) {
  31127. if (amplitude === void 0) { amplitude = 1; }
  31128. var _this = _super.call(this) || this;
  31129. _this.amplitude = amplitude;
  31130. return _this;
  31131. }
  31132. BackEase.prototype.easeInCore = function (gradient) {
  31133. var num = Math.max(0, this.amplitude);
  31134. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  31135. };
  31136. return BackEase;
  31137. }(EasingFunction));
  31138. BABYLON.BackEase = BackEase;
  31139. var BounceEase = (function (_super) {
  31140. __extends(BounceEase, _super);
  31141. function BounceEase(bounces, bounciness) {
  31142. if (bounces === void 0) { bounces = 3; }
  31143. if (bounciness === void 0) { bounciness = 2; }
  31144. var _this = _super.call(this) || this;
  31145. _this.bounces = bounces;
  31146. _this.bounciness = bounciness;
  31147. return _this;
  31148. }
  31149. BounceEase.prototype.easeInCore = function (gradient) {
  31150. var y = Math.max(0.0, this.bounces);
  31151. var bounciness = this.bounciness;
  31152. if (bounciness <= 1.0) {
  31153. bounciness = 1.001;
  31154. }
  31155. var num9 = Math.pow(bounciness, y);
  31156. var num5 = 1.0 - bounciness;
  31157. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31158. var num15 = gradient * num4;
  31159. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31160. var num3 = Math.floor(num65);
  31161. var num13 = num3 + 1.0;
  31162. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31163. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31164. var num7 = (num8 + num12) * 0.5;
  31165. var num6 = gradient - num7;
  31166. var num2 = num7 - num8;
  31167. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31168. };
  31169. return BounceEase;
  31170. }(EasingFunction));
  31171. BABYLON.BounceEase = BounceEase;
  31172. var CubicEase = (function (_super) {
  31173. __extends(CubicEase, _super);
  31174. function CubicEase() {
  31175. return _super !== null && _super.apply(this, arguments) || this;
  31176. }
  31177. CubicEase.prototype.easeInCore = function (gradient) {
  31178. return (gradient * gradient * gradient);
  31179. };
  31180. return CubicEase;
  31181. }(EasingFunction));
  31182. BABYLON.CubicEase = CubicEase;
  31183. var ElasticEase = (function (_super) {
  31184. __extends(ElasticEase, _super);
  31185. function ElasticEase(oscillations, springiness) {
  31186. if (oscillations === void 0) { oscillations = 3; }
  31187. if (springiness === void 0) { springiness = 3; }
  31188. var _this = _super.call(this) || this;
  31189. _this.oscillations = oscillations;
  31190. _this.springiness = springiness;
  31191. return _this;
  31192. }
  31193. ElasticEase.prototype.easeInCore = function (gradient) {
  31194. var num2;
  31195. var num3 = Math.max(0.0, this.oscillations);
  31196. var num = Math.max(0.0, this.springiness);
  31197. if (num == 0) {
  31198. num2 = gradient;
  31199. }
  31200. else {
  31201. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31202. }
  31203. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31204. };
  31205. return ElasticEase;
  31206. }(EasingFunction));
  31207. BABYLON.ElasticEase = ElasticEase;
  31208. var ExponentialEase = (function (_super) {
  31209. __extends(ExponentialEase, _super);
  31210. function ExponentialEase(exponent) {
  31211. if (exponent === void 0) { exponent = 2; }
  31212. var _this = _super.call(this) || this;
  31213. _this.exponent = exponent;
  31214. return _this;
  31215. }
  31216. ExponentialEase.prototype.easeInCore = function (gradient) {
  31217. if (this.exponent <= 0) {
  31218. return gradient;
  31219. }
  31220. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31221. };
  31222. return ExponentialEase;
  31223. }(EasingFunction));
  31224. BABYLON.ExponentialEase = ExponentialEase;
  31225. var PowerEase = (function (_super) {
  31226. __extends(PowerEase, _super);
  31227. function PowerEase(power) {
  31228. if (power === void 0) { power = 2; }
  31229. var _this = _super.call(this) || this;
  31230. _this.power = power;
  31231. return _this;
  31232. }
  31233. PowerEase.prototype.easeInCore = function (gradient) {
  31234. var y = Math.max(0.0, this.power);
  31235. return Math.pow(gradient, y);
  31236. };
  31237. return PowerEase;
  31238. }(EasingFunction));
  31239. BABYLON.PowerEase = PowerEase;
  31240. var QuadraticEase = (function (_super) {
  31241. __extends(QuadraticEase, _super);
  31242. function QuadraticEase() {
  31243. return _super !== null && _super.apply(this, arguments) || this;
  31244. }
  31245. QuadraticEase.prototype.easeInCore = function (gradient) {
  31246. return (gradient * gradient);
  31247. };
  31248. return QuadraticEase;
  31249. }(EasingFunction));
  31250. BABYLON.QuadraticEase = QuadraticEase;
  31251. var QuarticEase = (function (_super) {
  31252. __extends(QuarticEase, _super);
  31253. function QuarticEase() {
  31254. return _super !== null && _super.apply(this, arguments) || this;
  31255. }
  31256. QuarticEase.prototype.easeInCore = function (gradient) {
  31257. return (gradient * gradient * gradient * gradient);
  31258. };
  31259. return QuarticEase;
  31260. }(EasingFunction));
  31261. BABYLON.QuarticEase = QuarticEase;
  31262. var QuinticEase = (function (_super) {
  31263. __extends(QuinticEase, _super);
  31264. function QuinticEase() {
  31265. return _super !== null && _super.apply(this, arguments) || this;
  31266. }
  31267. QuinticEase.prototype.easeInCore = function (gradient) {
  31268. return (gradient * gradient * gradient * gradient * gradient);
  31269. };
  31270. return QuinticEase;
  31271. }(EasingFunction));
  31272. BABYLON.QuinticEase = QuinticEase;
  31273. var SineEase = (function (_super) {
  31274. __extends(SineEase, _super);
  31275. function SineEase() {
  31276. return _super !== null && _super.apply(this, arguments) || this;
  31277. }
  31278. SineEase.prototype.easeInCore = function (gradient) {
  31279. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31280. };
  31281. return SineEase;
  31282. }(EasingFunction));
  31283. BABYLON.SineEase = SineEase;
  31284. var BezierCurveEase = (function (_super) {
  31285. __extends(BezierCurveEase, _super);
  31286. function BezierCurveEase(x1, y1, x2, y2) {
  31287. if (x1 === void 0) { x1 = 0; }
  31288. if (y1 === void 0) { y1 = 0; }
  31289. if (x2 === void 0) { x2 = 1; }
  31290. if (y2 === void 0) { y2 = 1; }
  31291. var _this = _super.call(this) || this;
  31292. _this.x1 = x1;
  31293. _this.y1 = y1;
  31294. _this.x2 = x2;
  31295. _this.y2 = y2;
  31296. return _this;
  31297. }
  31298. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31299. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31300. };
  31301. return BezierCurveEase;
  31302. }(EasingFunction));
  31303. BABYLON.BezierCurveEase = BezierCurveEase;
  31304. })(BABYLON || (BABYLON = {}));
  31305. //# sourceMappingURL=babylon.easing.js.map
  31306. var BABYLON;
  31307. (function (BABYLON) {
  31308. BABYLON.CameraInputTypes = {};
  31309. var CameraInputsManager = (function () {
  31310. function CameraInputsManager(camera) {
  31311. this.attached = {};
  31312. this.camera = camera;
  31313. this.checkInputs = function () { };
  31314. }
  31315. CameraInputsManager.prototype.add = function (input) {
  31316. var type = input.getSimpleName();
  31317. if (this.attached[type]) {
  31318. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31319. return;
  31320. }
  31321. this.attached[type] = input;
  31322. input.camera = this.camera;
  31323. //for checkInputs, we are dynamically creating a function
  31324. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31325. if (input.checkInputs) {
  31326. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31327. }
  31328. if (this.attachedElement) {
  31329. input.attachControl(this.attachedElement);
  31330. }
  31331. };
  31332. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31333. for (var cam in this.attached) {
  31334. var input = this.attached[cam];
  31335. if (input === inputToRemove) {
  31336. input.detachControl(this.attachedElement);
  31337. input.camera = null;
  31338. delete this.attached[cam];
  31339. this.rebuildInputCheck();
  31340. }
  31341. }
  31342. };
  31343. CameraInputsManager.prototype.removeByType = function (inputType) {
  31344. for (var cam in this.attached) {
  31345. var input = this.attached[cam];
  31346. if (input.getClassName() === inputType) {
  31347. input.detachControl(this.attachedElement);
  31348. input.camera = null;
  31349. delete this.attached[cam];
  31350. this.rebuildInputCheck();
  31351. }
  31352. }
  31353. };
  31354. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31355. var current = this.checkInputs;
  31356. return function () {
  31357. current();
  31358. fn();
  31359. };
  31360. };
  31361. CameraInputsManager.prototype.attachInput = function (input) {
  31362. input.attachControl(this.attachedElement, this.noPreventDefault);
  31363. };
  31364. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31365. if (this.attachedElement) {
  31366. return;
  31367. }
  31368. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31369. this.attachedElement = element;
  31370. this.noPreventDefault = noPreventDefault;
  31371. for (var cam in this.attached) {
  31372. var input = this.attached[cam];
  31373. this.attached[cam].attachControl(element, noPreventDefault);
  31374. }
  31375. };
  31376. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  31377. if (disconnect === void 0) { disconnect = false; }
  31378. if (this.attachedElement !== element) {
  31379. return;
  31380. }
  31381. for (var cam in this.attached) {
  31382. var input = this.attached[cam];
  31383. this.attached[cam].detachControl(element);
  31384. if (disconnect) {
  31385. this.attached[cam].camera = null;
  31386. }
  31387. }
  31388. this.attachedElement = null;
  31389. };
  31390. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31391. this.checkInputs = function () { };
  31392. for (var cam in this.attached) {
  31393. var input = this.attached[cam];
  31394. if (input.checkInputs) {
  31395. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31396. }
  31397. }
  31398. };
  31399. CameraInputsManager.prototype.clear = function () {
  31400. if (this.attachedElement) {
  31401. this.detachElement(this.attachedElement, true);
  31402. }
  31403. this.attached = {};
  31404. this.attachedElement = null;
  31405. this.checkInputs = function () { };
  31406. };
  31407. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31408. var inputs = {};
  31409. for (var cam in this.attached) {
  31410. var input = this.attached[cam];
  31411. var res = BABYLON.SerializationHelper.Serialize(input);
  31412. inputs[input.getClassName()] = res;
  31413. }
  31414. serializedCamera.inputsmgr = inputs;
  31415. };
  31416. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31417. var parsedInputs = parsedCamera.inputsmgr;
  31418. if (parsedInputs) {
  31419. this.clear();
  31420. for (var n in parsedInputs) {
  31421. var construct = BABYLON.CameraInputTypes[n];
  31422. if (construct) {
  31423. var parsedinput = parsedInputs[n];
  31424. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31425. this.add(input);
  31426. }
  31427. }
  31428. }
  31429. else {
  31430. //2016-03-08 this part is for managing backward compatibility
  31431. for (var n in this.attached) {
  31432. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  31433. if (construct) {
  31434. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31435. this.remove(this.attached[n]);
  31436. this.add(input);
  31437. }
  31438. }
  31439. }
  31440. };
  31441. return CameraInputsManager;
  31442. }());
  31443. BABYLON.CameraInputsManager = CameraInputsManager;
  31444. })(BABYLON || (BABYLON = {}));
  31445. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31446. /// <reference path="babylon.camera.ts" />
  31447. var BABYLON;
  31448. (function (BABYLON) {
  31449. var TargetCamera = (function (_super) {
  31450. __extends(TargetCamera, _super);
  31451. function TargetCamera(name, position, scene) {
  31452. var _this = _super.call(this, name, position, scene) || this;
  31453. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31454. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31455. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31456. _this.speed = 2.0;
  31457. _this.noRotationConstraint = false;
  31458. _this.lockedTarget = null;
  31459. _this._currentTarget = BABYLON.Vector3.Zero();
  31460. _this._viewMatrix = BABYLON.Matrix.Zero();
  31461. _this._camMatrix = BABYLON.Matrix.Zero();
  31462. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31463. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31464. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31465. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31466. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31467. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31468. _this._tempMatrix = BABYLON.Matrix.Zero();
  31469. return _this;
  31470. }
  31471. TargetCamera.prototype.getFrontPosition = function (distance) {
  31472. var direction = this.getTarget().subtract(this.position);
  31473. direction.normalize();
  31474. direction.scaleInPlace(distance);
  31475. return this.globalPosition.add(direction);
  31476. };
  31477. TargetCamera.prototype._getLockedTargetPosition = function () {
  31478. if (!this.lockedTarget) {
  31479. return null;
  31480. }
  31481. if (this.lockedTarget.absolutePosition) {
  31482. this.lockedTarget.computeWorldMatrix();
  31483. }
  31484. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31485. };
  31486. TargetCamera.prototype.storeState = function () {
  31487. this._storedPosition = this.position.clone();
  31488. this._storedRotation = this.rotation.clone();
  31489. if (this.rotationQuaternion) {
  31490. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  31491. }
  31492. return _super.prototype.storeState.call(this);
  31493. };
  31494. /**
  31495. * Restored camera state. You must call storeState() first
  31496. */
  31497. TargetCamera.prototype.restoreState = function () {
  31498. if (!_super.prototype.restoreState.call(this)) {
  31499. return false;
  31500. }
  31501. this.position = this._storedPosition.clone();
  31502. this.rotation = this._storedRotation.clone();
  31503. if (this.rotationQuaternion) {
  31504. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  31505. }
  31506. this.cameraDirection.copyFromFloats(0, 0, 0);
  31507. this.cameraRotation.copyFromFloats(0, 0);
  31508. return true;
  31509. };
  31510. // Cache
  31511. TargetCamera.prototype._initCache = function () {
  31512. _super.prototype._initCache.call(this);
  31513. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31514. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31515. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31516. };
  31517. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31518. if (!ignoreParentClass) {
  31519. _super.prototype._updateCache.call(this);
  31520. }
  31521. var lockedTargetPosition = this._getLockedTargetPosition();
  31522. if (!lockedTargetPosition) {
  31523. this._cache.lockedTarget = null;
  31524. }
  31525. else {
  31526. if (!this._cache.lockedTarget) {
  31527. this._cache.lockedTarget = lockedTargetPosition.clone();
  31528. }
  31529. else {
  31530. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31531. }
  31532. }
  31533. this._cache.rotation.copyFrom(this.rotation);
  31534. if (this.rotationQuaternion)
  31535. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31536. };
  31537. // Synchronized
  31538. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31539. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31540. return false;
  31541. }
  31542. var lockedTargetPosition = this._getLockedTargetPosition();
  31543. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31544. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31545. };
  31546. // Methods
  31547. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31548. var engine = this.getEngine();
  31549. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31550. };
  31551. // Target
  31552. TargetCamera.prototype.setTarget = function (target) {
  31553. this.upVector.normalize();
  31554. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31555. this._camMatrix.invert();
  31556. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31557. var vDir = target.subtract(this.position);
  31558. if (vDir.x >= 0.0) {
  31559. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31560. }
  31561. else {
  31562. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31563. }
  31564. this.rotation.z = 0;
  31565. if (isNaN(this.rotation.x)) {
  31566. this.rotation.x = 0;
  31567. }
  31568. if (isNaN(this.rotation.y)) {
  31569. this.rotation.y = 0;
  31570. }
  31571. if (isNaN(this.rotation.z)) {
  31572. this.rotation.z = 0;
  31573. }
  31574. if (this.rotationQuaternion) {
  31575. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31576. }
  31577. };
  31578. /**
  31579. * Return the current target position of the camera. This value is expressed in local space.
  31580. */
  31581. TargetCamera.prototype.getTarget = function () {
  31582. return this._currentTarget;
  31583. };
  31584. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31585. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31586. };
  31587. TargetCamera.prototype._updatePosition = function () {
  31588. if (this.parent) {
  31589. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31590. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31591. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31592. return;
  31593. }
  31594. this.position.addInPlace(this.cameraDirection);
  31595. };
  31596. TargetCamera.prototype._checkInputs = function () {
  31597. var needToMove = this._decideIfNeedsToMove();
  31598. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31599. // Move
  31600. if (needToMove) {
  31601. this._updatePosition();
  31602. }
  31603. // Rotate
  31604. if (needToRotate) {
  31605. this.rotation.x += this.cameraRotation.x;
  31606. this.rotation.y += this.cameraRotation.y;
  31607. //rotate, if quaternion is set and rotation was used
  31608. if (this.rotationQuaternion) {
  31609. var len = this.rotation.lengthSquared();
  31610. if (len) {
  31611. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31612. }
  31613. }
  31614. if (!this.noRotationConstraint) {
  31615. var limit = (Math.PI / 2) * 0.95;
  31616. if (this.rotation.x > limit)
  31617. this.rotation.x = limit;
  31618. if (this.rotation.x < -limit)
  31619. this.rotation.x = -limit;
  31620. }
  31621. }
  31622. // Inertia
  31623. if (needToMove) {
  31624. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31625. this.cameraDirection.x = 0;
  31626. }
  31627. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31628. this.cameraDirection.y = 0;
  31629. }
  31630. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31631. this.cameraDirection.z = 0;
  31632. }
  31633. this.cameraDirection.scaleInPlace(this.inertia);
  31634. }
  31635. if (needToRotate) {
  31636. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31637. this.cameraRotation.x = 0;
  31638. }
  31639. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31640. this.cameraRotation.y = 0;
  31641. }
  31642. this.cameraRotation.scaleInPlace(this.inertia);
  31643. }
  31644. _super.prototype._checkInputs.call(this);
  31645. };
  31646. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31647. if (this.rotationQuaternion) {
  31648. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31649. //update the up vector!
  31650. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31651. }
  31652. else {
  31653. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31654. }
  31655. };
  31656. TargetCamera.prototype._getViewMatrix = function () {
  31657. if (!this.lockedTarget) {
  31658. // Compute
  31659. this._updateCameraRotationMatrix();
  31660. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31661. // Computing target and final matrix
  31662. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31663. }
  31664. else {
  31665. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31666. }
  31667. if (this.getScene().useRightHandedSystem) {
  31668. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31669. }
  31670. else {
  31671. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31672. }
  31673. return this._viewMatrix;
  31674. };
  31675. /**
  31676. * @override
  31677. * Override Camera.createRigCamera
  31678. */
  31679. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31680. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31681. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31682. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31683. if (!this.rotationQuaternion) {
  31684. this.rotationQuaternion = new BABYLON.Quaternion();
  31685. }
  31686. rigCamera._cameraRigParams = {};
  31687. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31688. }
  31689. return rigCamera;
  31690. }
  31691. return null;
  31692. };
  31693. /**
  31694. * @override
  31695. * Override Camera._updateRigCameras
  31696. */
  31697. TargetCamera.prototype._updateRigCameras = function () {
  31698. var camLeft = this._rigCameras[0];
  31699. var camRight = this._rigCameras[1];
  31700. switch (this.cameraRigMode) {
  31701. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31702. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31703. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31704. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31705. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31706. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31707. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31708. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31709. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31710. camLeft.setTarget(this.getTarget());
  31711. camRight.setTarget(this.getTarget());
  31712. break;
  31713. case BABYLON.Camera.RIG_MODE_VR:
  31714. if (camLeft.rotationQuaternion) {
  31715. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31716. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31717. }
  31718. else {
  31719. camLeft.rotation.copyFrom(this.rotation);
  31720. camRight.rotation.copyFrom(this.rotation);
  31721. }
  31722. camLeft.position.copyFrom(this.position);
  31723. camRight.position.copyFrom(this.position);
  31724. break;
  31725. }
  31726. _super.prototype._updateRigCameras.call(this);
  31727. };
  31728. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31729. if (!this._rigCamTransformMatrix) {
  31730. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31731. }
  31732. var target = this.getTarget();
  31733. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31734. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31735. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31736. };
  31737. TargetCamera.prototype.getClassName = function () {
  31738. return "TargetCamera";
  31739. };
  31740. __decorate([
  31741. BABYLON.serializeAsVector3()
  31742. ], TargetCamera.prototype, "rotation", void 0);
  31743. __decorate([
  31744. BABYLON.serialize()
  31745. ], TargetCamera.prototype, "speed", void 0);
  31746. __decorate([
  31747. BABYLON.serializeAsMeshReference("lockedTargetId")
  31748. ], TargetCamera.prototype, "lockedTarget", void 0);
  31749. return TargetCamera;
  31750. }(BABYLON.Camera));
  31751. BABYLON.TargetCamera = TargetCamera;
  31752. })(BABYLON || (BABYLON = {}));
  31753. //# sourceMappingURL=babylon.targetCamera.js.map
  31754. var BABYLON;
  31755. (function (BABYLON) {
  31756. var ArcRotateCameraKeyboardMoveInput = (function () {
  31757. function ArcRotateCameraKeyboardMoveInput() {
  31758. this._keys = [];
  31759. this.keysUp = [38];
  31760. this.keysDown = [40];
  31761. this.keysLeft = [37];
  31762. this.keysRight = [39];
  31763. this.keysReset = [111];
  31764. this.panningSensibility = 50.0;
  31765. }
  31766. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31767. var _this = this;
  31768. element.tabIndex = 1;
  31769. this._onKeyDown = function (evt) {
  31770. _this._ctrlPressed = evt.ctrlKey;
  31771. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31772. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31773. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31774. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31775. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31776. var index = _this._keys.indexOf(evt.keyCode);
  31777. if (index === -1) {
  31778. _this._keys.push(evt.keyCode);
  31779. }
  31780. if (evt.preventDefault) {
  31781. if (!noPreventDefault) {
  31782. evt.preventDefault();
  31783. }
  31784. }
  31785. }
  31786. };
  31787. this._onKeyUp = function (evt) {
  31788. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31789. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31790. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31791. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31792. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31793. var index = _this._keys.indexOf(evt.keyCode);
  31794. if (index >= 0) {
  31795. _this._keys.splice(index, 1);
  31796. }
  31797. if (evt.preventDefault) {
  31798. if (!noPreventDefault) {
  31799. evt.preventDefault();
  31800. }
  31801. }
  31802. }
  31803. };
  31804. this._onLostFocus = function () {
  31805. _this._keys = [];
  31806. };
  31807. this._onFocus = function () {
  31808. element.addEventListener("keydown", _this._onKeyDown, false);
  31809. element.addEventListener("keyup", _this._onKeyUp, false);
  31810. };
  31811. this._onBlur = function () {
  31812. element.removeEventListener("keydown", _this._onKeyDown);
  31813. element.removeEventListener("keyup", _this._onKeyUp);
  31814. };
  31815. element.addEventListener("focus", this._onFocus);
  31816. element.addEventListener("blur", this._onBlur);
  31817. BABYLON.Tools.RegisterTopRootEvents([
  31818. { name: "blur", handler: this._onLostFocus }
  31819. ]);
  31820. };
  31821. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31822. if (element && this._onBlur) {
  31823. this._onBlur();
  31824. element.removeEventListener("focus", this._onFocus);
  31825. element.removeEventListener("blur", this._onBlur);
  31826. }
  31827. BABYLON.Tools.UnregisterTopRootEvents([
  31828. { name: "blur", handler: this._onLostFocus }
  31829. ]);
  31830. this._keys = [];
  31831. this._onKeyDown = null;
  31832. this._onKeyUp = null;
  31833. this._onLostFocus = null;
  31834. this._onBlur = null;
  31835. this._onFocus = null;
  31836. };
  31837. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31838. if (this._onKeyDown) {
  31839. var camera = this.camera;
  31840. for (var index = 0; index < this._keys.length; index++) {
  31841. var keyCode = this._keys[index];
  31842. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31843. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31844. camera.inertialPanningX -= 1 / this.panningSensibility;
  31845. }
  31846. else {
  31847. camera.inertialAlphaOffset -= 0.01;
  31848. }
  31849. }
  31850. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31851. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31852. camera.inertialPanningY += 1 / this.panningSensibility;
  31853. }
  31854. else {
  31855. camera.inertialBetaOffset -= 0.01;
  31856. }
  31857. }
  31858. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31859. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31860. camera.inertialPanningX += 1 / this.panningSensibility;
  31861. }
  31862. else {
  31863. camera.inertialAlphaOffset += 0.01;
  31864. }
  31865. }
  31866. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31867. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31868. camera.inertialPanningY -= 1 / this.panningSensibility;
  31869. }
  31870. else {
  31871. camera.inertialBetaOffset += 0.01;
  31872. }
  31873. }
  31874. else if (this.keysReset.indexOf(keyCode) !== -1) {
  31875. camera.restoreState();
  31876. }
  31877. }
  31878. }
  31879. };
  31880. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31881. return "ArcRotateCameraKeyboardMoveInput";
  31882. };
  31883. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31884. return "keyboard";
  31885. };
  31886. __decorate([
  31887. BABYLON.serialize()
  31888. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31889. __decorate([
  31890. BABYLON.serialize()
  31891. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31892. __decorate([
  31893. BABYLON.serialize()
  31894. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31895. __decorate([
  31896. BABYLON.serialize()
  31897. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31898. __decorate([
  31899. BABYLON.serialize()
  31900. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  31901. __decorate([
  31902. BABYLON.serialize()
  31903. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  31904. return ArcRotateCameraKeyboardMoveInput;
  31905. }());
  31906. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31907. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31908. })(BABYLON || (BABYLON = {}));
  31909. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31910. var BABYLON;
  31911. (function (BABYLON) {
  31912. var ArcRotateCameraMouseWheelInput = (function () {
  31913. function ArcRotateCameraMouseWheelInput() {
  31914. this.wheelPrecision = 3.0;
  31915. }
  31916. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31917. var _this = this;
  31918. this._wheel = function (p, s) {
  31919. //sanity check - this should be a PointerWheel event.
  31920. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31921. return;
  31922. var event = p.event;
  31923. var delta = 0;
  31924. if (event.wheelDelta) {
  31925. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31926. }
  31927. else if (event.detail) {
  31928. delta = -event.detail / _this.wheelPrecision;
  31929. }
  31930. if (delta)
  31931. _this.camera.inertialRadiusOffset += delta;
  31932. if (event.preventDefault) {
  31933. if (!noPreventDefault) {
  31934. event.preventDefault();
  31935. }
  31936. }
  31937. };
  31938. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31939. };
  31940. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31941. if (this._observer && element) {
  31942. this.camera.getScene().onPointerObservable.remove(this._observer);
  31943. this._observer = null;
  31944. this._wheel = null;
  31945. }
  31946. };
  31947. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  31948. return "ArcRotateCameraMouseWheelInput";
  31949. };
  31950. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31951. return "mousewheel";
  31952. };
  31953. __decorate([
  31954. BABYLON.serialize()
  31955. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31956. return ArcRotateCameraMouseWheelInput;
  31957. }());
  31958. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31959. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31960. })(BABYLON || (BABYLON = {}));
  31961. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31962. var BABYLON;
  31963. (function (BABYLON) {
  31964. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31965. var ArcRotateCameraPointersInput = (function () {
  31966. function ArcRotateCameraPointersInput() {
  31967. this.buttons = [0, 1, 2];
  31968. this.angularSensibilityX = 1000.0;
  31969. this.angularSensibilityY = 1000.0;
  31970. this.pinchPrecision = 6.0;
  31971. this.panningSensibility = 50.0;
  31972. this._isPanClick = false;
  31973. this.pinchInwards = true;
  31974. }
  31975. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31976. var _this = this;
  31977. var engine = this.camera.getEngine();
  31978. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31979. var pointA, pointB;
  31980. var previousPinchDistance = 0;
  31981. this._pointerInput = function (p, s) {
  31982. var evt = p.event;
  31983. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31984. return;
  31985. }
  31986. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31987. try {
  31988. evt.srcElement.setPointerCapture(evt.pointerId);
  31989. }
  31990. catch (e) {
  31991. //Nothing to do with the error. Execution will continue.
  31992. }
  31993. // Manage panning with pan button click
  31994. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31995. // manage pointers
  31996. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31997. if (pointA === undefined) {
  31998. pointA = cacheSoloPointer;
  31999. }
  32000. else if (pointB === undefined) {
  32001. pointB = cacheSoloPointer;
  32002. }
  32003. if (!noPreventDefault) {
  32004. evt.preventDefault();
  32005. element.focus();
  32006. }
  32007. }
  32008. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  32009. _this.camera.restoreState();
  32010. }
  32011. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32012. try {
  32013. evt.srcElement.releasePointerCapture(evt.pointerId);
  32014. }
  32015. catch (e) {
  32016. //Nothing to do with the error.
  32017. }
  32018. cacheSoloPointer = null;
  32019. previousPinchDistance = 0;
  32020. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32021. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32022. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32023. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32024. pointA = pointB = undefined;
  32025. if (!noPreventDefault) {
  32026. evt.preventDefault();
  32027. }
  32028. }
  32029. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32030. if (!noPreventDefault) {
  32031. evt.preventDefault();
  32032. }
  32033. // One button down
  32034. if (pointA && pointB === undefined) {
  32035. if (_this.panningSensibility !== 0 &&
  32036. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32037. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32038. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32039. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32040. }
  32041. else {
  32042. var offsetX = evt.clientX - cacheSoloPointer.x;
  32043. var offsetY = evt.clientY - cacheSoloPointer.y;
  32044. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32045. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32046. }
  32047. cacheSoloPointer.x = evt.clientX;
  32048. cacheSoloPointer.y = evt.clientY;
  32049. }
  32050. else if (pointA && pointB) {
  32051. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32052. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32053. ed.x = evt.clientX;
  32054. ed.y = evt.clientY;
  32055. var direction = _this.pinchInwards ? 1 : -1;
  32056. var distX = pointA.x - pointB.x;
  32057. var distY = pointA.y - pointB.y;
  32058. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32059. if (previousPinchDistance === 0) {
  32060. previousPinchDistance = pinchSquaredDistance;
  32061. return;
  32062. }
  32063. if (pinchSquaredDistance !== previousPinchDistance) {
  32064. _this.camera
  32065. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32066. (_this.pinchPrecision *
  32067. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32068. direction);
  32069. previousPinchDistance = pinchSquaredDistance;
  32070. }
  32071. }
  32072. }
  32073. };
  32074. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  32075. this._onContextMenu = function (evt) {
  32076. evt.preventDefault();
  32077. };
  32078. if (!this.camera._useCtrlForPanning) {
  32079. element.addEventListener("contextmenu", this._onContextMenu, false);
  32080. }
  32081. this._onLostFocus = function () {
  32082. //this._keys = [];
  32083. pointA = pointB = undefined;
  32084. previousPinchDistance = 0;
  32085. cacheSoloPointer = null;
  32086. };
  32087. this._onMouseMove = function (evt) {
  32088. if (!engine.isPointerLock) {
  32089. return;
  32090. }
  32091. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32092. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32093. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32094. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32095. if (!noPreventDefault) {
  32096. evt.preventDefault();
  32097. }
  32098. };
  32099. this._onGestureStart = function (e) {
  32100. if (window.MSGesture === undefined) {
  32101. return;
  32102. }
  32103. if (!_this._MSGestureHandler) {
  32104. _this._MSGestureHandler = new MSGesture();
  32105. _this._MSGestureHandler.target = element;
  32106. }
  32107. _this._MSGestureHandler.addPointer(e.pointerId);
  32108. };
  32109. this._onGesture = function (e) {
  32110. _this.camera.radius *= e.scale;
  32111. if (e.preventDefault) {
  32112. if (!noPreventDefault) {
  32113. e.stopPropagation();
  32114. e.preventDefault();
  32115. }
  32116. }
  32117. };
  32118. element.addEventListener("mousemove", this._onMouseMove, false);
  32119. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32120. element.addEventListener("MSGestureChange", this._onGesture, false);
  32121. BABYLON.Tools.RegisterTopRootEvents([
  32122. { name: "blur", handler: this._onLostFocus }
  32123. ]);
  32124. };
  32125. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32126. BABYLON.Tools.UnregisterTopRootEvents([
  32127. { name: "blur", handler: this._onLostFocus }
  32128. ]);
  32129. if (element && this._observer) {
  32130. this.camera.getScene().onPointerObservable.remove(this._observer);
  32131. this._observer = null;
  32132. element.removeEventListener("contextmenu", this._onContextMenu);
  32133. element.removeEventListener("mousemove", this._onMouseMove);
  32134. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32135. element.removeEventListener("MSGestureChange", this._onGesture);
  32136. this._isPanClick = false;
  32137. this.pinchInwards = true;
  32138. this._onMouseMove = null;
  32139. this._onGestureStart = null;
  32140. this._onGesture = null;
  32141. this._MSGestureHandler = null;
  32142. this._onLostFocus = null;
  32143. this._onContextMenu = null;
  32144. }
  32145. };
  32146. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  32147. return "ArcRotateCameraPointersInput";
  32148. };
  32149. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32150. return "pointers";
  32151. };
  32152. __decorate([
  32153. BABYLON.serialize()
  32154. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32155. __decorate([
  32156. BABYLON.serialize()
  32157. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32158. __decorate([
  32159. BABYLON.serialize()
  32160. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32161. __decorate([
  32162. BABYLON.serialize()
  32163. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32164. __decorate([
  32165. BABYLON.serialize()
  32166. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32167. return ArcRotateCameraPointersInput;
  32168. }());
  32169. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32170. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32171. })(BABYLON || (BABYLON = {}));
  32172. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32173. /// <reference path="babylon.targetCamera.ts" />
  32174. /// <reference path="..\Tools\babylon.tools.ts" />
  32175. var BABYLON;
  32176. (function (BABYLON) {
  32177. var ArcRotateCamera = (function (_super) {
  32178. __extends(ArcRotateCamera, _super);
  32179. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32180. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32181. _this.inertialAlphaOffset = 0;
  32182. _this.inertialBetaOffset = 0;
  32183. _this.inertialRadiusOffset = 0;
  32184. _this.lowerAlphaLimit = null;
  32185. _this.upperAlphaLimit = null;
  32186. _this.lowerBetaLimit = 0.01;
  32187. _this.upperBetaLimit = Math.PI;
  32188. _this.lowerRadiusLimit = null;
  32189. _this.upperRadiusLimit = null;
  32190. _this.inertialPanningX = 0;
  32191. _this.inertialPanningY = 0;
  32192. _this.panningInertia = 0.9;
  32193. //-- end properties for backward compatibility for inputs
  32194. _this.zoomOnFactor = 1;
  32195. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32196. _this.allowUpsideDown = true;
  32197. _this._viewMatrix = new BABYLON.Matrix();
  32198. // Panning
  32199. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32200. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  32201. _this.checkCollisions = false;
  32202. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32203. _this._previousPosition = BABYLON.Vector3.Zero();
  32204. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32205. _this._newPosition = BABYLON.Vector3.Zero();
  32206. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32207. if (collidedMesh === void 0) { collidedMesh = null; }
  32208. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32209. newPosition.multiplyInPlace(_this._collider.radius);
  32210. }
  32211. if (!collidedMesh) {
  32212. _this._previousPosition.copyFrom(_this.position);
  32213. }
  32214. else {
  32215. _this.setPosition(newPosition);
  32216. if (_this.onCollide) {
  32217. _this.onCollide(collidedMesh);
  32218. }
  32219. }
  32220. // Recompute because of constraints
  32221. var cosa = Math.cos(_this.alpha);
  32222. var sina = Math.sin(_this.alpha);
  32223. var cosb = Math.cos(_this.beta);
  32224. var sinb = Math.sin(_this.beta);
  32225. if (sinb === 0) {
  32226. sinb = 0.0001;
  32227. }
  32228. var target = _this._getTargetPosition();
  32229. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32230. _this.position.copyFrom(_this._newPosition);
  32231. var up = _this.upVector;
  32232. if (_this.allowUpsideDown && _this.beta < 0) {
  32233. up = up.clone();
  32234. up = up.negate();
  32235. }
  32236. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32237. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32238. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32239. _this._collisionTriggered = false;
  32240. };
  32241. _this._target = BABYLON.Vector3.Zero();
  32242. if (target) {
  32243. _this.setTarget(target);
  32244. }
  32245. _this.alpha = alpha;
  32246. _this.beta = beta;
  32247. _this.radius = radius;
  32248. _this.getViewMatrix();
  32249. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32250. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32251. return _this;
  32252. }
  32253. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32254. get: function () {
  32255. return this._target;
  32256. },
  32257. set: function (value) {
  32258. this.setTarget(value);
  32259. },
  32260. enumerable: true,
  32261. configurable: true
  32262. });
  32263. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32264. //-- begin properties for backward compatibility for inputs
  32265. get: function () {
  32266. var pointers = this.inputs.attached["pointers"];
  32267. if (pointers)
  32268. return pointers.angularSensibilityX;
  32269. },
  32270. set: function (value) {
  32271. var pointers = this.inputs.attached["pointers"];
  32272. if (pointers) {
  32273. pointers.angularSensibilityX = value;
  32274. }
  32275. },
  32276. enumerable: true,
  32277. configurable: true
  32278. });
  32279. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32280. get: function () {
  32281. var pointers = this.inputs.attached["pointers"];
  32282. if (pointers)
  32283. return pointers.angularSensibilityY;
  32284. },
  32285. set: function (value) {
  32286. var pointers = this.inputs.attached["pointers"];
  32287. if (pointers) {
  32288. pointers.angularSensibilityY = value;
  32289. }
  32290. },
  32291. enumerable: true,
  32292. configurable: true
  32293. });
  32294. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32295. get: function () {
  32296. var pointers = this.inputs.attached["pointers"];
  32297. if (pointers)
  32298. return pointers.pinchPrecision;
  32299. },
  32300. set: function (value) {
  32301. var pointers = this.inputs.attached["pointers"];
  32302. if (pointers) {
  32303. pointers.pinchPrecision = value;
  32304. }
  32305. },
  32306. enumerable: true,
  32307. configurable: true
  32308. });
  32309. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32310. get: function () {
  32311. var pointers = this.inputs.attached["pointers"];
  32312. if (pointers)
  32313. return pointers.panningSensibility;
  32314. },
  32315. set: function (value) {
  32316. var pointers = this.inputs.attached["pointers"];
  32317. if (pointers) {
  32318. pointers.panningSensibility = value;
  32319. }
  32320. },
  32321. enumerable: true,
  32322. configurable: true
  32323. });
  32324. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32325. get: function () {
  32326. var keyboard = this.inputs.attached["keyboard"];
  32327. if (keyboard)
  32328. return keyboard.keysUp;
  32329. },
  32330. set: function (value) {
  32331. var keyboard = this.inputs.attached["keyboard"];
  32332. if (keyboard)
  32333. keyboard.keysUp = value;
  32334. },
  32335. enumerable: true,
  32336. configurable: true
  32337. });
  32338. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32339. get: function () {
  32340. var keyboard = this.inputs.attached["keyboard"];
  32341. if (keyboard)
  32342. return keyboard.keysDown;
  32343. },
  32344. set: function (value) {
  32345. var keyboard = this.inputs.attached["keyboard"];
  32346. if (keyboard)
  32347. keyboard.keysDown = value;
  32348. },
  32349. enumerable: true,
  32350. configurable: true
  32351. });
  32352. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32353. get: function () {
  32354. var keyboard = this.inputs.attached["keyboard"];
  32355. if (keyboard)
  32356. return keyboard.keysLeft;
  32357. },
  32358. set: function (value) {
  32359. var keyboard = this.inputs.attached["keyboard"];
  32360. if (keyboard)
  32361. keyboard.keysLeft = value;
  32362. },
  32363. enumerable: true,
  32364. configurable: true
  32365. });
  32366. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32367. get: function () {
  32368. var keyboard = this.inputs.attached["keyboard"];
  32369. if (keyboard)
  32370. return keyboard.keysRight;
  32371. },
  32372. set: function (value) {
  32373. var keyboard = this.inputs.attached["keyboard"];
  32374. if (keyboard)
  32375. keyboard.keysRight = value;
  32376. },
  32377. enumerable: true,
  32378. configurable: true
  32379. });
  32380. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32381. get: function () {
  32382. var mousewheel = this.inputs.attached["mousewheel"];
  32383. if (mousewheel)
  32384. return mousewheel.wheelPrecision;
  32385. },
  32386. set: function (value) {
  32387. var mousewheel = this.inputs.attached["mousewheel"];
  32388. if (mousewheel)
  32389. mousewheel.wheelPrecision = value;
  32390. },
  32391. enumerable: true,
  32392. configurable: true
  32393. });
  32394. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  32395. get: function () {
  32396. return this._bouncingBehavior;
  32397. },
  32398. enumerable: true,
  32399. configurable: true
  32400. });
  32401. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  32402. get: function () {
  32403. return this._bouncingBehavior != null;
  32404. },
  32405. set: function (value) {
  32406. if (value === this.useBouncingBehavior) {
  32407. return;
  32408. }
  32409. if (value) {
  32410. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  32411. this.addBehavior(this._bouncingBehavior);
  32412. }
  32413. else {
  32414. this.removeBehavior(this._bouncingBehavior);
  32415. this._bouncingBehavior = null;
  32416. }
  32417. },
  32418. enumerable: true,
  32419. configurable: true
  32420. });
  32421. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  32422. get: function () {
  32423. return this._framingBehavior;
  32424. },
  32425. enumerable: true,
  32426. configurable: true
  32427. });
  32428. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  32429. get: function () {
  32430. return this._framingBehavior != null;
  32431. },
  32432. set: function (value) {
  32433. if (value === this.useFramingBehavior) {
  32434. return;
  32435. }
  32436. if (value) {
  32437. this._framingBehavior = new BABYLON.FramingBehavior();
  32438. this.addBehavior(this._framingBehavior);
  32439. }
  32440. else {
  32441. this.removeBehavior(this._framingBehavior);
  32442. this._framingBehavior = null;
  32443. }
  32444. },
  32445. enumerable: true,
  32446. configurable: true
  32447. });
  32448. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  32449. get: function () {
  32450. return this._autoRotationBehavior;
  32451. },
  32452. enumerable: true,
  32453. configurable: true
  32454. });
  32455. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  32456. get: function () {
  32457. return this._autoRotationBehavior != null;
  32458. },
  32459. set: function (value) {
  32460. if (value === this.useAutoRotationBehavior) {
  32461. return;
  32462. }
  32463. if (value) {
  32464. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  32465. this.addBehavior(this._autoRotationBehavior);
  32466. }
  32467. else {
  32468. this.removeBehavior(this._autoRotationBehavior);
  32469. this._autoRotationBehavior = null;
  32470. }
  32471. },
  32472. enumerable: true,
  32473. configurable: true
  32474. });
  32475. // Cache
  32476. ArcRotateCamera.prototype._initCache = function () {
  32477. _super.prototype._initCache.call(this);
  32478. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32479. this._cache.alpha = undefined;
  32480. this._cache.beta = undefined;
  32481. this._cache.radius = undefined;
  32482. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32483. };
  32484. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32485. if (!ignoreParentClass) {
  32486. _super.prototype._updateCache.call(this);
  32487. }
  32488. this._cache._target.copyFrom(this._getTargetPosition());
  32489. this._cache.alpha = this.alpha;
  32490. this._cache.beta = this.beta;
  32491. this._cache.radius = this.radius;
  32492. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32493. };
  32494. ArcRotateCamera.prototype._getTargetPosition = function () {
  32495. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32496. var pos = this._targetHost.getAbsolutePosition();
  32497. if (this._targetBoundingCenter) {
  32498. pos.addToRef(this._targetBoundingCenter, this._target);
  32499. }
  32500. else {
  32501. this._target.copyFrom(pos);
  32502. }
  32503. }
  32504. var lockedTargetPosition = this._getLockedTargetPosition();
  32505. if (lockedTargetPosition) {
  32506. return lockedTargetPosition;
  32507. }
  32508. return this._target;
  32509. };
  32510. ArcRotateCamera.prototype.storeState = function () {
  32511. this._storedAlpha = this.alpha;
  32512. this._storedBeta = this.beta;
  32513. this._storedRadius = this.radius;
  32514. this._storedTarget = this._getTargetPosition().clone();
  32515. return _super.prototype.storeState.call(this);
  32516. };
  32517. /**
  32518. * Restored camera state. You must call storeState() first
  32519. */
  32520. ArcRotateCamera.prototype.restoreState = function () {
  32521. if (!_super.prototype.restoreState.call(this)) {
  32522. return false;
  32523. }
  32524. this.alpha = this._storedAlpha;
  32525. this.beta = this._storedBeta;
  32526. this.radius = this._storedRadius;
  32527. this.setTarget(this._storedTarget);
  32528. this.inertialAlphaOffset = 0;
  32529. this.inertialBetaOffset = 0;
  32530. this.inertialRadiusOffset = 0;
  32531. this.inertialPanningX = 0;
  32532. this.inertialPanningY = 0;
  32533. return true;
  32534. };
  32535. // Synchronized
  32536. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32537. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32538. return false;
  32539. return this._cache._target.equals(this._getTargetPosition())
  32540. && this._cache.alpha === this.alpha
  32541. && this._cache.beta === this.beta
  32542. && this._cache.radius === this.radius
  32543. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32544. };
  32545. // Methods
  32546. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32547. var _this = this;
  32548. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32549. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32550. this._useCtrlForPanning = useCtrlForPanning;
  32551. this._panningMouseButton = panningMouseButton;
  32552. this.inputs.attachElement(element, noPreventDefault);
  32553. this._reset = function () {
  32554. _this.inertialAlphaOffset = 0;
  32555. _this.inertialBetaOffset = 0;
  32556. _this.inertialRadiusOffset = 0;
  32557. _this.inertialPanningX = 0;
  32558. _this.inertialPanningY = 0;
  32559. };
  32560. };
  32561. ArcRotateCamera.prototype.detachControl = function (element) {
  32562. this.inputs.detachElement(element);
  32563. if (this._reset) {
  32564. this._reset();
  32565. }
  32566. };
  32567. ArcRotateCamera.prototype._checkInputs = function () {
  32568. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32569. if (this._collisionTriggered) {
  32570. return;
  32571. }
  32572. this.inputs.checkInputs();
  32573. // Inertia
  32574. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32575. if (this.getScene().useRightHandedSystem) {
  32576. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32577. }
  32578. else {
  32579. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32580. }
  32581. this.beta += this.inertialBetaOffset;
  32582. this.radius -= this.inertialRadiusOffset;
  32583. this.inertialAlphaOffset *= this.inertia;
  32584. this.inertialBetaOffset *= this.inertia;
  32585. this.inertialRadiusOffset *= this.inertia;
  32586. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  32587. this.inertialAlphaOffset = 0;
  32588. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  32589. this.inertialBetaOffset = 0;
  32590. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32591. this.inertialRadiusOffset = 0;
  32592. }
  32593. // Panning inertia
  32594. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32595. if (!this._localDirection) {
  32596. this._localDirection = BABYLON.Vector3.Zero();
  32597. this._transformedDirection = BABYLON.Vector3.Zero();
  32598. }
  32599. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32600. this._localDirection.multiplyInPlace(this.panningAxis);
  32601. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32602. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32603. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32604. if (!this.panningAxis.y) {
  32605. this._transformedDirection.y = 0;
  32606. }
  32607. if (!this._targetHost) {
  32608. this._target.addInPlace(this._transformedDirection);
  32609. }
  32610. this.inertialPanningX *= this.panningInertia;
  32611. this.inertialPanningY *= this.panningInertia;
  32612. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32613. this.inertialPanningX = 0;
  32614. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32615. this.inertialPanningY = 0;
  32616. }
  32617. // Limits
  32618. this._checkLimits();
  32619. _super.prototype._checkInputs.call(this);
  32620. };
  32621. ArcRotateCamera.prototype._checkLimits = function () {
  32622. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32623. if (this.allowUpsideDown && this.beta > Math.PI) {
  32624. this.beta = this.beta - (2 * Math.PI);
  32625. }
  32626. }
  32627. else {
  32628. if (this.beta < this.lowerBetaLimit) {
  32629. this.beta = this.lowerBetaLimit;
  32630. }
  32631. }
  32632. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32633. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32634. this.beta = this.beta + (2 * Math.PI);
  32635. }
  32636. }
  32637. else {
  32638. if (this.beta > this.upperBetaLimit) {
  32639. this.beta = this.upperBetaLimit;
  32640. }
  32641. }
  32642. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32643. this.alpha = this.lowerAlphaLimit;
  32644. }
  32645. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32646. this.alpha = this.upperAlphaLimit;
  32647. }
  32648. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32649. this.radius = this.lowerRadiusLimit;
  32650. }
  32651. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32652. this.radius = this.upperRadiusLimit;
  32653. }
  32654. };
  32655. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32656. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32657. this.radius = radiusv3.length();
  32658. if (this.radius === 0) {
  32659. this.radius = 0.0001; // Just to avoid division by zero
  32660. }
  32661. // Alpha
  32662. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32663. if (radiusv3.z < 0) {
  32664. this.alpha = 2 * Math.PI - this.alpha;
  32665. }
  32666. // Beta
  32667. this.beta = Math.acos(radiusv3.y / this.radius);
  32668. this._checkLimits();
  32669. };
  32670. ArcRotateCamera.prototype.setPosition = function (position) {
  32671. if (this.position.equals(position)) {
  32672. return;
  32673. }
  32674. this.position.copyFrom(position);
  32675. this.rebuildAnglesAndRadius();
  32676. };
  32677. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32678. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32679. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32680. if (target.getBoundingInfo) {
  32681. if (toBoundingCenter) {
  32682. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32683. }
  32684. else {
  32685. this._targetBoundingCenter = null;
  32686. }
  32687. this._targetHost = target;
  32688. this._target = this._getTargetPosition();
  32689. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32690. }
  32691. else {
  32692. var newTarget = target;
  32693. var currentTarget = this._getTargetPosition();
  32694. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32695. return;
  32696. }
  32697. this._targetHost = null;
  32698. this._target = newTarget;
  32699. this._targetBoundingCenter = null;
  32700. this.onMeshTargetChangedObservable.notifyObservers(null);
  32701. }
  32702. this.rebuildAnglesAndRadius();
  32703. };
  32704. ArcRotateCamera.prototype._getViewMatrix = function () {
  32705. // Compute
  32706. var cosa = Math.cos(this.alpha);
  32707. var sina = Math.sin(this.alpha);
  32708. var cosb = Math.cos(this.beta);
  32709. var sinb = Math.sin(this.beta);
  32710. if (sinb === 0) {
  32711. sinb = 0.0001;
  32712. }
  32713. var target = this._getTargetPosition();
  32714. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32715. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32716. if (!this._collider) {
  32717. this._collider = new BABYLON.Collider();
  32718. }
  32719. this._collider.radius = this.collisionRadius;
  32720. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32721. this._collisionTriggered = true;
  32722. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32723. }
  32724. else {
  32725. this.position.copyFrom(this._newPosition);
  32726. var up = this.upVector;
  32727. if (this.allowUpsideDown && sinb < 0) {
  32728. up = up.clone();
  32729. up = up.negate();
  32730. }
  32731. if (this.getScene().useRightHandedSystem) {
  32732. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32733. }
  32734. else {
  32735. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32736. }
  32737. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32738. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32739. }
  32740. this._currentTarget = target;
  32741. return this._viewMatrix;
  32742. };
  32743. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32744. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32745. meshes = meshes || this.getScene().meshes;
  32746. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32747. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32748. this.radius = distance * this.zoomOnFactor;
  32749. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32750. };
  32751. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32752. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32753. var meshesOrMinMaxVector;
  32754. var distance;
  32755. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32756. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32757. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32758. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32759. }
  32760. else {
  32761. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32762. distance = meshesOrMinMaxVectorAndDistance.distance;
  32763. }
  32764. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32765. if (!doNotUpdateMaxZ) {
  32766. this.maxZ = distance * 2;
  32767. }
  32768. };
  32769. /**
  32770. * @override
  32771. * Override Camera.createRigCamera
  32772. */
  32773. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32774. var alphaShift;
  32775. switch (this.cameraRigMode) {
  32776. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32778. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32779. case BABYLON.Camera.RIG_MODE_VR:
  32780. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32781. break;
  32782. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32783. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32784. break;
  32785. }
  32786. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32787. rigCam._cameraRigParams = {};
  32788. return rigCam;
  32789. };
  32790. /**
  32791. * @override
  32792. * Override Camera._updateRigCameras
  32793. */
  32794. ArcRotateCamera.prototype._updateRigCameras = function () {
  32795. var camLeft = this._rigCameras[0];
  32796. var camRight = this._rigCameras[1];
  32797. camLeft.beta = camRight.beta = this.beta;
  32798. camLeft.radius = camRight.radius = this.radius;
  32799. switch (this.cameraRigMode) {
  32800. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32801. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32802. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32803. case BABYLON.Camera.RIG_MODE_VR:
  32804. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32805. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32806. break;
  32807. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32808. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32809. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32810. break;
  32811. }
  32812. _super.prototype._updateRigCameras.call(this);
  32813. };
  32814. ArcRotateCamera.prototype.dispose = function () {
  32815. this.inputs.clear();
  32816. _super.prototype.dispose.call(this);
  32817. };
  32818. ArcRotateCamera.prototype.getClassName = function () {
  32819. return "ArcRotateCamera";
  32820. };
  32821. __decorate([
  32822. BABYLON.serialize()
  32823. ], ArcRotateCamera.prototype, "alpha", void 0);
  32824. __decorate([
  32825. BABYLON.serialize()
  32826. ], ArcRotateCamera.prototype, "beta", void 0);
  32827. __decorate([
  32828. BABYLON.serialize()
  32829. ], ArcRotateCamera.prototype, "radius", void 0);
  32830. __decorate([
  32831. BABYLON.serializeAsVector3("target")
  32832. ], ArcRotateCamera.prototype, "_target", void 0);
  32833. __decorate([
  32834. BABYLON.serialize()
  32835. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32836. __decorate([
  32837. BABYLON.serialize()
  32838. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32839. __decorate([
  32840. BABYLON.serialize()
  32841. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32842. __decorate([
  32843. BABYLON.serialize()
  32844. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32845. __decorate([
  32846. BABYLON.serialize()
  32847. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32848. __decorate([
  32849. BABYLON.serialize()
  32850. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32851. __decorate([
  32852. BABYLON.serialize()
  32853. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32854. __decorate([
  32855. BABYLON.serialize()
  32856. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32857. __decorate([
  32858. BABYLON.serialize()
  32859. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32860. __decorate([
  32861. BABYLON.serialize()
  32862. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32863. __decorate([
  32864. BABYLON.serialize()
  32865. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32866. __decorate([
  32867. BABYLON.serialize()
  32868. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32869. __decorate([
  32870. BABYLON.serialize()
  32871. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32872. __decorate([
  32873. BABYLON.serialize()
  32874. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32875. return ArcRotateCamera;
  32876. }(BABYLON.TargetCamera));
  32877. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32878. })(BABYLON || (BABYLON = {}));
  32879. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32880. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32881. var BABYLON;
  32882. (function (BABYLON) {
  32883. var ArcRotateCameraInputsManager = (function (_super) {
  32884. __extends(ArcRotateCameraInputsManager, _super);
  32885. function ArcRotateCameraInputsManager(camera) {
  32886. return _super.call(this, camera) || this;
  32887. }
  32888. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32889. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32890. return this;
  32891. };
  32892. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32893. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32894. return this;
  32895. };
  32896. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32897. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32898. return this;
  32899. };
  32900. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32901. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32902. return this;
  32903. };
  32904. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32905. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32906. return this;
  32907. };
  32908. return ArcRotateCameraInputsManager;
  32909. }(BABYLON.CameraInputsManager));
  32910. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32911. })(BABYLON || (BABYLON = {}));
  32912. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32913. var BABYLON;
  32914. (function (BABYLON) {
  32915. var CubeTexture = (function (_super) {
  32916. __extends(CubeTexture, _super);
  32917. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  32918. if (onLoad === void 0) { onLoad = null; }
  32919. if (onError === void 0) { onError = null; }
  32920. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32921. if (prefiltered === void 0) { prefiltered = false; }
  32922. if (forcedExtension === void 0) { forcedExtension = null; }
  32923. var _this = _super.call(this, scene) || this;
  32924. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32925. _this.name = rootUrl;
  32926. _this.url = rootUrl;
  32927. _this._noMipmap = noMipmap;
  32928. _this.hasAlpha = false;
  32929. _this._format = format;
  32930. _this._prefiltered = prefiltered;
  32931. _this.isCube = true;
  32932. _this._textureMatrix = BABYLON.Matrix.Identity();
  32933. if (prefiltered) {
  32934. _this.gammaSpace = false;
  32935. }
  32936. if (!rootUrl && !files) {
  32937. return _this;
  32938. }
  32939. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32940. if (!files) {
  32941. if (!extensions) {
  32942. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32943. }
  32944. files = [];
  32945. for (var index = 0; index < extensions.length; index++) {
  32946. files.push(rootUrl + extensions[index]);
  32947. }
  32948. _this._extensions = extensions;
  32949. }
  32950. _this._files = files;
  32951. if (!_this._texture) {
  32952. if (!scene.useDelayedTextureLoading) {
  32953. if (prefiltered) {
  32954. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  32955. }
  32956. else {
  32957. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  32958. }
  32959. }
  32960. else {
  32961. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32962. }
  32963. }
  32964. else if (onLoad) {
  32965. if (_this._texture.isReady) {
  32966. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32967. }
  32968. else {
  32969. _this._texture.onLoadedObservable.add(onLoad);
  32970. }
  32971. }
  32972. return _this;
  32973. }
  32974. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32975. return new CubeTexture("", scene, null, noMipmap, files);
  32976. };
  32977. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  32978. if (forcedExtension === void 0) { forcedExtension = null; }
  32979. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  32980. };
  32981. // Methods
  32982. CubeTexture.prototype.delayLoad = function () {
  32983. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32984. return;
  32985. }
  32986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32987. this._texture = this._getFromCache(this.url, this._noMipmap);
  32988. if (!this._texture) {
  32989. if (this._prefiltered) {
  32990. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  32991. }
  32992. else {
  32993. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32994. }
  32995. }
  32996. };
  32997. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32998. return this._textureMatrix;
  32999. };
  33000. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  33001. this._textureMatrix = value;
  33002. };
  33003. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33004. var texture = BABYLON.SerializationHelper.Parse(function () {
  33005. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  33006. }, parsedTexture, scene);
  33007. // Animations
  33008. if (parsedTexture.animations) {
  33009. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  33010. var parsedAnimation = parsedTexture.animations[animationIndex];
  33011. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33012. }
  33013. }
  33014. return texture;
  33015. };
  33016. CubeTexture.prototype.clone = function () {
  33017. var _this = this;
  33018. return BABYLON.SerializationHelper.Clone(function () {
  33019. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  33020. }, this);
  33021. };
  33022. return CubeTexture;
  33023. }(BABYLON.BaseTexture));
  33024. BABYLON.CubeTexture = CubeTexture;
  33025. })(BABYLON || (BABYLON = {}));
  33026. //# sourceMappingURL=babylon.cubeTexture.js.map
  33027. var BABYLON;
  33028. (function (BABYLON) {
  33029. var RenderTargetTexture = (function (_super) {
  33030. __extends(RenderTargetTexture, _super);
  33031. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  33032. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  33033. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33034. if (isCube === void 0) { isCube = false; }
  33035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33036. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33037. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  33038. if (isMulti === void 0) { isMulti = false; }
  33039. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  33040. _this.isCube = isCube;
  33041. /**
  33042. * Use this list to define the list of mesh you want to render.
  33043. */
  33044. _this.renderList = new Array();
  33045. _this.renderParticles = true;
  33046. _this.renderSprites = false;
  33047. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  33048. _this.ignoreCameraViewport = false;
  33049. // Events
  33050. /**
  33051. * An event triggered when the texture is unbind.
  33052. * @type {BABYLON.Observable}
  33053. */
  33054. _this.onBeforeBindObservable = new BABYLON.Observable();
  33055. /**
  33056. * An event triggered when the texture is unbind.
  33057. * @type {BABYLON.Observable}
  33058. */
  33059. _this.onAfterUnbindObservable = new BABYLON.Observable();
  33060. /**
  33061. * An event triggered before rendering the texture
  33062. * @type {BABYLON.Observable}
  33063. */
  33064. _this.onBeforeRenderObservable = new BABYLON.Observable();
  33065. /**
  33066. * An event triggered after rendering the texture
  33067. * @type {BABYLON.Observable}
  33068. */
  33069. _this.onAfterRenderObservable = new BABYLON.Observable();
  33070. /**
  33071. * An event triggered after the texture clear
  33072. * @type {BABYLON.Observable}
  33073. */
  33074. _this.onClearObservable = new BABYLON.Observable();
  33075. _this._currentRefreshId = -1;
  33076. _this._refreshRate = 1;
  33077. _this._samples = 1;
  33078. scene = _this.getScene();
  33079. _this.name = name;
  33080. _this.isRenderTarget = true;
  33081. _this._size = size;
  33082. _this._generateMipMaps = generateMipMaps;
  33083. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  33084. // Rendering groups
  33085. _this._renderingManager = new BABYLON.RenderingManager(scene);
  33086. if (isMulti) {
  33087. return _this;
  33088. }
  33089. _this._renderTargetOptions = {
  33090. generateMipMaps: generateMipMaps,
  33091. type: type,
  33092. samplingMode: samplingMode,
  33093. generateDepthBuffer: generateDepthBuffer,
  33094. generateStencilBuffer: generateStencilBuffer
  33095. };
  33096. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  33097. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33098. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33099. }
  33100. if (isCube) {
  33101. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  33102. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  33103. _this._textureMatrix = BABYLON.Matrix.Identity();
  33104. }
  33105. else {
  33106. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  33107. }
  33108. return _this;
  33109. }
  33110. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  33111. get: function () {
  33112. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  33113. },
  33114. enumerable: true,
  33115. configurable: true
  33116. });
  33117. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  33118. get: function () {
  33119. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  33120. },
  33121. enumerable: true,
  33122. configurable: true
  33123. });
  33124. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  33125. get: function () {
  33126. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  33127. },
  33128. enumerable: true,
  33129. configurable: true
  33130. });
  33131. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  33132. set: function (callback) {
  33133. if (this._onAfterUnbindObserver) {
  33134. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  33135. }
  33136. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  33137. },
  33138. enumerable: true,
  33139. configurable: true
  33140. });
  33141. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  33142. set: function (callback) {
  33143. if (this._onBeforeRenderObserver) {
  33144. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33145. }
  33146. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33147. },
  33148. enumerable: true,
  33149. configurable: true
  33150. });
  33151. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  33152. set: function (callback) {
  33153. if (this._onAfterRenderObserver) {
  33154. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33155. }
  33156. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33157. },
  33158. enumerable: true,
  33159. configurable: true
  33160. });
  33161. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  33162. set: function (callback) {
  33163. if (this._onClearObserver) {
  33164. this.onClearObservable.remove(this._onClearObserver);
  33165. }
  33166. this._onClearObserver = this.onClearObservable.add(callback);
  33167. },
  33168. enumerable: true,
  33169. configurable: true
  33170. });
  33171. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  33172. get: function () {
  33173. return this._renderTargetOptions;
  33174. },
  33175. enumerable: true,
  33176. configurable: true
  33177. });
  33178. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  33179. get: function () {
  33180. return this._samples;
  33181. },
  33182. set: function (value) {
  33183. if (this._samples === value) {
  33184. return;
  33185. }
  33186. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  33187. },
  33188. enumerable: true,
  33189. configurable: true
  33190. });
  33191. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  33192. this._currentRefreshId = -1;
  33193. };
  33194. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  33195. get: function () {
  33196. return this._refreshRate;
  33197. },
  33198. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  33199. set: function (value) {
  33200. this._refreshRate = value;
  33201. this.resetRefreshCounter();
  33202. },
  33203. enumerable: true,
  33204. configurable: true
  33205. });
  33206. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  33207. if (!this._postProcessManager) {
  33208. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  33209. this._postProcesses = new Array();
  33210. }
  33211. this._postProcesses.push(postProcess);
  33212. this._postProcesses[0].autoClear = false;
  33213. };
  33214. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  33215. if (!this._postProcesses) {
  33216. return;
  33217. }
  33218. if (dispose) {
  33219. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  33220. var postProcess = _a[_i];
  33221. postProcess.dispose();
  33222. postProcess = null;
  33223. }
  33224. }
  33225. this._postProcesses = [];
  33226. };
  33227. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  33228. if (!this._postProcesses) {
  33229. return;
  33230. }
  33231. var index = this._postProcesses.indexOf(postProcess);
  33232. if (index === -1) {
  33233. return;
  33234. }
  33235. this._postProcesses.splice(index, 1);
  33236. if (this._postProcesses.length > 0) {
  33237. this._postProcesses[0].autoClear = false;
  33238. }
  33239. };
  33240. RenderTargetTexture.prototype._shouldRender = function () {
  33241. if (this._currentRefreshId === -1) {
  33242. this._currentRefreshId = 1;
  33243. return true;
  33244. }
  33245. if (this.refreshRate === this._currentRefreshId) {
  33246. this._currentRefreshId = 1;
  33247. return true;
  33248. }
  33249. this._currentRefreshId++;
  33250. return false;
  33251. };
  33252. RenderTargetTexture.prototype.getRenderSize = function () {
  33253. return this._size;
  33254. };
  33255. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  33256. get: function () {
  33257. return true;
  33258. },
  33259. enumerable: true,
  33260. configurable: true
  33261. });
  33262. RenderTargetTexture.prototype.scale = function (ratio) {
  33263. var newSize = this._size * ratio;
  33264. this.resize(newSize);
  33265. };
  33266. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  33267. if (this.isCube) {
  33268. return this._textureMatrix;
  33269. }
  33270. return _super.prototype.getReflectionTextureMatrix.call(this);
  33271. };
  33272. RenderTargetTexture.prototype.resize = function (size) {
  33273. this.releaseInternalTexture();
  33274. if (this.isCube) {
  33275. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  33276. }
  33277. else {
  33278. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  33279. }
  33280. };
  33281. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  33282. var scene = this.getScene();
  33283. var engine = scene.getEngine();
  33284. if (this.useCameraPostProcesses !== undefined) {
  33285. useCameraPostProcess = this.useCameraPostProcesses;
  33286. }
  33287. if (this._waitingRenderList) {
  33288. this.renderList = [];
  33289. for (var index = 0; index < this._waitingRenderList.length; index++) {
  33290. var id = this._waitingRenderList[index];
  33291. this.renderList.push(scene.getMeshByID(id));
  33292. }
  33293. delete this._waitingRenderList;
  33294. }
  33295. // Is predicate defined?
  33296. if (this.renderListPredicate) {
  33297. this.renderList.splice(0); // Clear previous renderList
  33298. var sceneMeshes = this.getScene().meshes;
  33299. for (var index = 0; index < sceneMeshes.length; index++) {
  33300. var mesh = sceneMeshes[index];
  33301. if (this.renderListPredicate(mesh)) {
  33302. this.renderList.push(mesh);
  33303. }
  33304. }
  33305. }
  33306. if (this.renderList && this.renderList.length === 0) {
  33307. return;
  33308. }
  33309. this.onBeforeBindObservable.notifyObservers(this);
  33310. // Set custom projection.
  33311. // Needs to be before binding to prevent changing the aspect ratio.
  33312. var camera;
  33313. if (this.activeCamera) {
  33314. camera = this.activeCamera;
  33315. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  33316. if (this.activeCamera !== scene.activeCamera) {
  33317. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  33318. }
  33319. }
  33320. else {
  33321. camera = scene.activeCamera;
  33322. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  33323. }
  33324. // Prepare renderingManager
  33325. this._renderingManager.reset();
  33326. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  33327. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  33328. var sceneRenderId = scene.getRenderId();
  33329. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  33330. var mesh = currentRenderList[meshIndex];
  33331. if (mesh) {
  33332. if (!mesh.isReady()) {
  33333. // Reset _currentRefreshId
  33334. this.resetRefreshCounter();
  33335. continue;
  33336. }
  33337. mesh._preActivateForIntermediateRendering(sceneRenderId);
  33338. var isMasked = void 0;
  33339. if (!this.renderList) {
  33340. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  33341. }
  33342. else {
  33343. isMasked = false;
  33344. }
  33345. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  33346. mesh._activate(sceneRenderId);
  33347. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33348. var subMesh = mesh.subMeshes[subIndex];
  33349. scene._activeIndices.addCount(subMesh.indexCount, false);
  33350. this._renderingManager.dispatch(subMesh);
  33351. }
  33352. }
  33353. }
  33354. }
  33355. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  33356. var particleSystem = scene.particleSystems[particleIndex];
  33357. var emitter = particleSystem.emitter;
  33358. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  33359. continue;
  33360. }
  33361. if (currentRenderList.indexOf(emitter) >= 0) {
  33362. this._renderingManager.dispatchParticles(particleSystem);
  33363. }
  33364. }
  33365. if (this.isCube) {
  33366. for (var face = 0; face < 6; face++) {
  33367. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33368. scene.incrementRenderId();
  33369. scene.resetCachedMaterial();
  33370. }
  33371. }
  33372. else {
  33373. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33374. }
  33375. this.onAfterUnbindObservable.notifyObservers(this);
  33376. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  33377. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  33378. }
  33379. engine.setViewport(scene.activeCamera.viewport);
  33380. scene.resetCachedMaterial();
  33381. };
  33382. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  33383. var _this = this;
  33384. var scene = this.getScene();
  33385. var engine = scene.getEngine();
  33386. // Bind
  33387. if (this._postProcessManager) {
  33388. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  33389. }
  33390. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  33391. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  33392. }
  33393. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  33394. // Clear
  33395. if (this.onClearObservable.hasObservers()) {
  33396. this.onClearObservable.notifyObservers(engine);
  33397. }
  33398. else {
  33399. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  33400. }
  33401. if (!this._doNotChangeAspectRatio) {
  33402. scene.updateTransformMatrix(true);
  33403. }
  33404. // Render
  33405. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  33406. if (this._postProcessManager) {
  33407. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  33408. }
  33409. else if (useCameraPostProcess) {
  33410. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  33411. }
  33412. if (!this._doNotChangeAspectRatio) {
  33413. scene.updateTransformMatrix(true);
  33414. }
  33415. // Dump ?
  33416. if (dumpForDebug) {
  33417. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  33418. }
  33419. // Unbind
  33420. if (!this.isCube || faceIndex === 5) {
  33421. if (this.isCube) {
  33422. if (faceIndex === 5) {
  33423. engine.generateMipMapsForCubemap(this._texture);
  33424. }
  33425. }
  33426. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  33427. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  33428. });
  33429. }
  33430. else {
  33431. this.onAfterRenderObservable.notifyObservers(faceIndex);
  33432. }
  33433. };
  33434. /**
  33435. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  33436. * This allowed control for front to back rendering or reversly depending of the special needs.
  33437. *
  33438. * @param renderingGroupId The rendering group id corresponding to its index
  33439. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  33440. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  33441. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  33442. */
  33443. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  33444. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  33445. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  33446. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  33447. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  33448. };
  33449. /**
  33450. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  33451. *
  33452. * @param renderingGroupId The rendering group id corresponding to its index
  33453. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  33454. */
  33455. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  33456. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  33457. };
  33458. RenderTargetTexture.prototype.clone = function () {
  33459. var textureSize = this.getSize();
  33460. 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);
  33461. // Base texture
  33462. newTexture.hasAlpha = this.hasAlpha;
  33463. newTexture.level = this.level;
  33464. // RenderTarget Texture
  33465. newTexture.coordinatesMode = this.coordinatesMode;
  33466. newTexture.renderList = this.renderList.slice(0);
  33467. return newTexture;
  33468. };
  33469. RenderTargetTexture.prototype.serialize = function () {
  33470. if (!this.name) {
  33471. return null;
  33472. }
  33473. var serializationObject = _super.prototype.serialize.call(this);
  33474. serializationObject.renderTargetSize = this.getRenderSize();
  33475. serializationObject.renderList = [];
  33476. for (var index = 0; index < this.renderList.length; index++) {
  33477. serializationObject.renderList.push(this.renderList[index].id);
  33478. }
  33479. return serializationObject;
  33480. };
  33481. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  33482. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  33483. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  33484. };
  33485. RenderTargetTexture.prototype.dispose = function () {
  33486. if (this._postProcessManager) {
  33487. this._postProcessManager.dispose();
  33488. this._postProcessManager = null;
  33489. }
  33490. this.clearPostProcesses(true);
  33491. this.renderList = null;
  33492. // Remove from custom render targets
  33493. var scene = this.getScene();
  33494. var index = scene.customRenderTargets.indexOf(this);
  33495. if (index >= 0) {
  33496. scene.customRenderTargets.splice(index, 1);
  33497. }
  33498. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  33499. var camera = _a[_i];
  33500. index = camera.customRenderTargets.indexOf(this);
  33501. if (index >= 0) {
  33502. camera.customRenderTargets.splice(index, 1);
  33503. }
  33504. }
  33505. _super.prototype.dispose.call(this);
  33506. };
  33507. RenderTargetTexture.prototype._rebuild = function () {
  33508. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  33509. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  33510. }
  33511. if (this._postProcessManager) {
  33512. this._postProcessManager._rebuild();
  33513. }
  33514. };
  33515. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  33516. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  33517. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  33518. return RenderTargetTexture;
  33519. }(BABYLON.Texture));
  33520. BABYLON.RenderTargetTexture = RenderTargetTexture;
  33521. })(BABYLON || (BABYLON = {}));
  33522. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  33523. var BABYLON;
  33524. (function (BABYLON) {
  33525. ;
  33526. var MultiRenderTarget = (function (_super) {
  33527. __extends(MultiRenderTarget, _super);
  33528. function MultiRenderTarget(name, size, count, scene, options) {
  33529. var _this = this;
  33530. options = options || {};
  33531. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  33532. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  33533. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  33534. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  33535. if (!_this.isSupported) {
  33536. _this.dispose();
  33537. return;
  33538. }
  33539. var types = [];
  33540. var samplingModes = [];
  33541. for (var i = 0; i < count; i++) {
  33542. if (options.types && options.types[i]) {
  33543. types.push(options.types[i]);
  33544. }
  33545. else {
  33546. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  33547. }
  33548. if (options.samplingModes && options.samplingModes[i]) {
  33549. samplingModes.push(options.samplingModes[i]);
  33550. }
  33551. else {
  33552. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33553. }
  33554. }
  33555. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33556. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33557. _this._count = count;
  33558. _this._size = size;
  33559. _this._multiRenderTargetOptions = {
  33560. samplingModes: samplingModes,
  33561. generateMipMaps: generateMipMaps,
  33562. generateDepthBuffer: generateDepthBuffer,
  33563. generateStencilBuffer: generateStencilBuffer,
  33564. generateDepthTexture: generateDepthTexture,
  33565. types: types,
  33566. textureCount: count
  33567. };
  33568. _this._createInternalTextures();
  33569. _this._createTextures();
  33570. return _this;
  33571. }
  33572. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33573. get: function () {
  33574. var engine = this.getScene().getEngine();
  33575. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33576. },
  33577. enumerable: true,
  33578. configurable: true
  33579. });
  33580. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33581. get: function () {
  33582. return this._textures;
  33583. },
  33584. enumerable: true,
  33585. configurable: true
  33586. });
  33587. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33588. get: function () {
  33589. return this._textures[this._textures.length - 1];
  33590. },
  33591. enumerable: true,
  33592. configurable: true
  33593. });
  33594. MultiRenderTarget.prototype._rebuild = function () {
  33595. this.releaseInternalTextures();
  33596. this._createInternalTextures();
  33597. for (var i = 0; i < this._internalTextures.length; i++) {
  33598. var texture = this._textures[i];
  33599. texture._texture = this._internalTextures[i];
  33600. }
  33601. // Keeps references to frame buffer and stencil/depth buffer
  33602. this._texture = this._internalTextures[0];
  33603. };
  33604. MultiRenderTarget.prototype._createInternalTextures = function () {
  33605. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  33606. };
  33607. MultiRenderTarget.prototype._createTextures = function () {
  33608. this._textures = [];
  33609. for (var i = 0; i < this._internalTextures.length; i++) {
  33610. var texture = new BABYLON.Texture(null, this.getScene());
  33611. texture._texture = this._internalTextures[i];
  33612. this._textures.push(texture);
  33613. }
  33614. // Keeps references to frame buffer and stencil/depth buffer
  33615. this._texture = this._internalTextures[0];
  33616. };
  33617. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33618. get: function () {
  33619. return this._samples;
  33620. },
  33621. set: function (value) {
  33622. if (this._samples === value) {
  33623. return;
  33624. }
  33625. for (var i = 0; i < this._internalTextures.length; i++) {
  33626. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  33627. }
  33628. },
  33629. enumerable: true,
  33630. configurable: true
  33631. });
  33632. MultiRenderTarget.prototype.resize = function (size) {
  33633. this.releaseInternalTextures();
  33634. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33635. this._createInternalTextures();
  33636. };
  33637. MultiRenderTarget.prototype.dispose = function () {
  33638. this.releaseInternalTextures();
  33639. _super.prototype.dispose.call(this);
  33640. };
  33641. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33642. if (!this._internalTextures) {
  33643. return;
  33644. }
  33645. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  33646. if (this._internalTextures[i] !== undefined) {
  33647. this._internalTextures[i].dispose();
  33648. this._internalTextures.splice(i, 1);
  33649. }
  33650. }
  33651. };
  33652. return MultiRenderTarget;
  33653. }(BABYLON.RenderTargetTexture));
  33654. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33655. })(BABYLON || (BABYLON = {}));
  33656. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33657. /// <reference path="babylon.renderTargetTexture.ts" />
  33658. var BABYLON;
  33659. (function (BABYLON) {
  33660. var MirrorTexture = (function (_super) {
  33661. __extends(MirrorTexture, _super);
  33662. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33663. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33665. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33666. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33667. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33668. _this._transformMatrix = BABYLON.Matrix.Zero();
  33669. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33670. _this._blurKernelX = 0;
  33671. _this._blurKernelY = 0;
  33672. _this._blurRatio = 1.0;
  33673. _this.onBeforeRenderObservable.add(function () {
  33674. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33675. _this._savedViewMatrix = scene.getViewMatrix();
  33676. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33677. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33678. scene.clipPlane = _this.mirrorPlane;
  33679. scene.getEngine().cullBackFaces = false;
  33680. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33681. });
  33682. _this.onAfterRenderObservable.add(function () {
  33683. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33684. scene.getEngine().cullBackFaces = true;
  33685. scene._mirroredCameraPosition = null;
  33686. delete scene.clipPlane;
  33687. });
  33688. return _this;
  33689. }
  33690. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33691. get: function () {
  33692. return this._blurRatio;
  33693. },
  33694. set: function (value) {
  33695. if (this._blurRatio === value) {
  33696. return;
  33697. }
  33698. this._blurRatio = value;
  33699. this._preparePostProcesses();
  33700. },
  33701. enumerable: true,
  33702. configurable: true
  33703. });
  33704. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33705. set: function (value) {
  33706. this.blurKernelX = value;
  33707. this.blurKernelY = value;
  33708. },
  33709. enumerable: true,
  33710. configurable: true
  33711. });
  33712. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33713. get: function () {
  33714. return this._blurKernelX;
  33715. },
  33716. set: function (value) {
  33717. if (this._blurKernelX === value) {
  33718. return;
  33719. }
  33720. this._blurKernelX = value;
  33721. this._preparePostProcesses();
  33722. },
  33723. enumerable: true,
  33724. configurable: true
  33725. });
  33726. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33727. get: function () {
  33728. return this._blurKernelY;
  33729. },
  33730. set: function (value) {
  33731. if (this._blurKernelY === value) {
  33732. return;
  33733. }
  33734. this._blurKernelY = value;
  33735. this._preparePostProcesses();
  33736. },
  33737. enumerable: true,
  33738. configurable: true
  33739. });
  33740. MirrorTexture.prototype._preparePostProcesses = function () {
  33741. this.clearPostProcesses(true);
  33742. if (this._blurKernelX && this._blurKernelY) {
  33743. var engine = this.getScene().getEngine();
  33744. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33745. 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);
  33746. this._blurX.autoClear = false;
  33747. if (this._blurRatio === 1 && this.samples < 2) {
  33748. this._blurX.outputTexture = this._texture;
  33749. }
  33750. else {
  33751. this._blurX.alwaysForcePOT = true;
  33752. }
  33753. 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);
  33754. this._blurY.autoClear = false;
  33755. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33756. this.addPostProcess(this._blurX);
  33757. this.addPostProcess(this._blurY);
  33758. }
  33759. };
  33760. MirrorTexture.prototype.clone = function () {
  33761. var textureSize = this.getSize();
  33762. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33763. // Base texture
  33764. newTexture.hasAlpha = this.hasAlpha;
  33765. newTexture.level = this.level;
  33766. // Mirror Texture
  33767. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33768. newTexture.renderList = this.renderList.slice(0);
  33769. return newTexture;
  33770. };
  33771. MirrorTexture.prototype.serialize = function () {
  33772. if (!this.name) {
  33773. return null;
  33774. }
  33775. var serializationObject = _super.prototype.serialize.call(this);
  33776. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33777. return serializationObject;
  33778. };
  33779. return MirrorTexture;
  33780. }(BABYLON.RenderTargetTexture));
  33781. BABYLON.MirrorTexture = MirrorTexture;
  33782. })(BABYLON || (BABYLON = {}));
  33783. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33784. /// <reference path="babylon.renderTargetTexture.ts" />
  33785. var BABYLON;
  33786. (function (BABYLON) {
  33787. /**
  33788. * Creates a refraction texture used by refraction channel of the standard material.
  33789. * @param name the texture name
  33790. * @param size size of the underlying texture
  33791. * @param scene root scene
  33792. */
  33793. var RefractionTexture = (function (_super) {
  33794. __extends(RefractionTexture, _super);
  33795. function RefractionTexture(name, size, scene, generateMipMaps) {
  33796. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33797. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33798. _this.depth = 2.0;
  33799. _this.onBeforeRenderObservable.add(function () {
  33800. scene.clipPlane = _this.refractionPlane;
  33801. });
  33802. _this.onAfterRenderObservable.add(function () {
  33803. delete scene.clipPlane;
  33804. });
  33805. return _this;
  33806. }
  33807. RefractionTexture.prototype.clone = function () {
  33808. var textureSize = this.getSize();
  33809. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33810. // Base texture
  33811. newTexture.hasAlpha = this.hasAlpha;
  33812. newTexture.level = this.level;
  33813. // Refraction Texture
  33814. newTexture.refractionPlane = this.refractionPlane.clone();
  33815. newTexture.renderList = this.renderList.slice(0);
  33816. newTexture.depth = this.depth;
  33817. return newTexture;
  33818. };
  33819. RefractionTexture.prototype.serialize = function () {
  33820. if (!this.name) {
  33821. return null;
  33822. }
  33823. var serializationObject = _super.prototype.serialize.call(this);
  33824. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33825. serializationObject.depth = this.depth;
  33826. return serializationObject;
  33827. };
  33828. return RefractionTexture;
  33829. }(BABYLON.RenderTargetTexture));
  33830. BABYLON.RefractionTexture = RefractionTexture;
  33831. })(BABYLON || (BABYLON = {}));
  33832. //# sourceMappingURL=babylon.refractionTexture.js.map
  33833. /// <reference path="babylon.texture.ts" />
  33834. var BABYLON;
  33835. (function (BABYLON) {
  33836. var DynamicTexture = (function (_super) {
  33837. __extends(DynamicTexture, _super);
  33838. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33840. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33841. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33842. _this.name = name;
  33843. var engine = _this.getScene().getEngine();
  33844. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33845. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33846. _this._generateMipMaps = generateMipMaps;
  33847. if (options.getContext) {
  33848. _this._canvas = options;
  33849. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33850. }
  33851. else {
  33852. _this._canvas = document.createElement("canvas");
  33853. if (options.width) {
  33854. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33855. }
  33856. else {
  33857. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33858. }
  33859. }
  33860. var textureSize = _this.getSize();
  33861. _this._canvas.width = textureSize.width;
  33862. _this._canvas.height = textureSize.height;
  33863. _this._context = _this._canvas.getContext("2d");
  33864. return _this;
  33865. }
  33866. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33867. get: function () {
  33868. return true;
  33869. },
  33870. enumerable: true,
  33871. configurable: true
  33872. });
  33873. DynamicTexture.prototype._recreate = function (textureSize) {
  33874. this._canvas.width = textureSize.width;
  33875. this._canvas.height = textureSize.height;
  33876. this.releaseInternalTexture();
  33877. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33878. };
  33879. DynamicTexture.prototype.scale = function (ratio) {
  33880. var textureSize = this.getSize();
  33881. textureSize.width *= ratio;
  33882. textureSize.height *= ratio;
  33883. this._recreate(textureSize);
  33884. };
  33885. DynamicTexture.prototype.scaleTo = function (width, height) {
  33886. var textureSize = this.getSize();
  33887. textureSize.width = width;
  33888. textureSize.height = height;
  33889. this._recreate(textureSize);
  33890. };
  33891. DynamicTexture.prototype.getContext = function () {
  33892. return this._context;
  33893. };
  33894. DynamicTexture.prototype.clear = function () {
  33895. var size = this.getSize();
  33896. this._context.fillRect(0, 0, size.width, size.height);
  33897. };
  33898. DynamicTexture.prototype.update = function (invertY) {
  33899. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33900. };
  33901. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33902. if (update === void 0) { update = true; }
  33903. var size = this.getSize();
  33904. if (clearColor) {
  33905. this._context.fillStyle = clearColor;
  33906. this._context.fillRect(0, 0, size.width, size.height);
  33907. }
  33908. this._context.font = font;
  33909. if (x === null || x === undefined) {
  33910. var textSize = this._context.measureText(text);
  33911. x = (size.width - textSize.width) / 2;
  33912. }
  33913. if (y === null || y === undefined) {
  33914. var fontSize = parseInt((font.replace(/\D/g, '')));
  33915. ;
  33916. y = (size.height / 2) + (fontSize / 3.65);
  33917. }
  33918. this._context.fillStyle = color;
  33919. this._context.fillText(text, x, y);
  33920. if (update) {
  33921. this.update(invertY);
  33922. }
  33923. };
  33924. DynamicTexture.prototype.clone = function () {
  33925. var textureSize = this.getSize();
  33926. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33927. // Base texture
  33928. newTexture.hasAlpha = this.hasAlpha;
  33929. newTexture.level = this.level;
  33930. // Dynamic Texture
  33931. newTexture.wrapU = this.wrapU;
  33932. newTexture.wrapV = this.wrapV;
  33933. return newTexture;
  33934. };
  33935. DynamicTexture.prototype._rebuild = function () {
  33936. this.update();
  33937. };
  33938. return DynamicTexture;
  33939. }(BABYLON.Texture));
  33940. BABYLON.DynamicTexture = DynamicTexture;
  33941. })(BABYLON || (BABYLON = {}));
  33942. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33943. var BABYLON;
  33944. (function (BABYLON) {
  33945. var VideoTexture = (function (_super) {
  33946. __extends(VideoTexture, _super);
  33947. /**
  33948. * Creates a video texture.
  33949. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33950. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33951. * @param {BABYLON.Scene} scene is obviously the current scene.
  33952. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33953. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33954. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33955. */
  33956. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33957. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33958. if (invertY === void 0) { invertY = false; }
  33959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33960. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33961. _this._autoLaunch = true;
  33962. var urls;
  33963. _this.name = name;
  33964. if (urlsOrVideo instanceof HTMLVideoElement) {
  33965. _this.video = urlsOrVideo;
  33966. }
  33967. else {
  33968. urls = urlsOrVideo;
  33969. _this.video = document.createElement("video");
  33970. _this.video.autoplay = false;
  33971. _this.video.loop = true;
  33972. }
  33973. _this._generateMipMaps = generateMipMaps;
  33974. _this._samplingMode = samplingMode;
  33975. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  33976. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33977. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33978. }
  33979. else {
  33980. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33981. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33982. _this._generateMipMaps = false;
  33983. }
  33984. if (urls) {
  33985. _this.video.addEventListener("canplay", function () {
  33986. _this._createTexture();
  33987. });
  33988. urls.forEach(function (url) {
  33989. var source = document.createElement("source");
  33990. source.src = url;
  33991. _this.video.appendChild(source);
  33992. });
  33993. }
  33994. else {
  33995. _this._createTexture();
  33996. }
  33997. _this._lastUpdate = BABYLON.Tools.Now;
  33998. return _this;
  33999. }
  34000. VideoTexture.prototype.__setTextureReady = function () {
  34001. this._texture.isReady = true;
  34002. };
  34003. VideoTexture.prototype._createTexture = function () {
  34004. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  34005. if (this._autoLaunch) {
  34006. this._autoLaunch = false;
  34007. this.video.play();
  34008. }
  34009. this._setTextureReady = this.__setTextureReady.bind(this);
  34010. this.video.addEventListener("playing", this._setTextureReady);
  34011. };
  34012. VideoTexture.prototype._rebuild = function () {
  34013. this.update();
  34014. };
  34015. VideoTexture.prototype.update = function () {
  34016. var now = BABYLON.Tools.Now;
  34017. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  34018. return false;
  34019. }
  34020. this._lastUpdate = now;
  34021. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  34022. return true;
  34023. };
  34024. VideoTexture.prototype.dispose = function () {
  34025. _super.prototype.dispose.call(this);
  34026. this.video.removeEventListener("playing", this._setTextureReady);
  34027. };
  34028. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  34029. var video = document.createElement("video");
  34030. var constraintsDeviceId;
  34031. if (constraints && constraints.deviceId) {
  34032. constraintsDeviceId = {
  34033. exact: constraints.deviceId
  34034. };
  34035. }
  34036. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  34037. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  34038. if (navigator.getUserMedia) {
  34039. navigator.getUserMedia({
  34040. video: {
  34041. deviceId: constraintsDeviceId,
  34042. width: {
  34043. min: (constraints && constraints.minWidth) || 256,
  34044. max: (constraints && constraints.maxWidth) || 640
  34045. },
  34046. height: {
  34047. min: (constraints && constraints.minHeight) || 256,
  34048. max: (constraints && constraints.maxHeight) || 480
  34049. }
  34050. }
  34051. }, function (stream) {
  34052. if (video.mozSrcObject !== undefined) {
  34053. video.mozSrcObject = stream;
  34054. }
  34055. else {
  34056. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  34057. }
  34058. video.play();
  34059. if (onReady) {
  34060. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  34061. }
  34062. }, function (e) {
  34063. BABYLON.Tools.Error(e.name);
  34064. });
  34065. }
  34066. };
  34067. return VideoTexture;
  34068. }(BABYLON.Texture));
  34069. BABYLON.VideoTexture = VideoTexture;
  34070. })(BABYLON || (BABYLON = {}));
  34071. //# sourceMappingURL=babylon.videoTexture.js.map
  34072. var BABYLON;
  34073. (function (BABYLON) {
  34074. var RawTexture = (function (_super) {
  34075. __extends(RawTexture, _super);
  34076. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34078. if (invertY === void 0) { invertY = false; }
  34079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34080. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34081. _this.format = format;
  34082. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34083. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34084. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34085. return _this;
  34086. }
  34087. RawTexture.prototype.update = function (data) {
  34088. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34089. };
  34090. // Statics
  34091. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34092. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34093. if (invertY === void 0) { invertY = false; }
  34094. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34095. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34096. };
  34097. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34098. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34099. if (invertY === void 0) { invertY = false; }
  34100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34101. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34102. };
  34103. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34104. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34105. if (invertY === void 0) { invertY = false; }
  34106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34107. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34108. };
  34109. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34110. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34111. if (invertY === void 0) { invertY = false; }
  34112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34113. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34114. };
  34115. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34116. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34117. if (invertY === void 0) { invertY = false; }
  34118. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34119. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34120. };
  34121. return RawTexture;
  34122. }(BABYLON.Texture));
  34123. BABYLON.RawTexture = RawTexture;
  34124. })(BABYLON || (BABYLON = {}));
  34125. //# sourceMappingURL=babylon.rawTexture.js.map
  34126. var BABYLON;
  34127. (function (BABYLON) {
  34128. var Internals;
  34129. (function (Internals) {
  34130. /*
  34131. * Based on jsTGALoader - Javascript loader for TGA file
  34132. * By Vincent Thibault
  34133. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  34134. */
  34135. var TGATools = (function () {
  34136. function TGATools() {
  34137. }
  34138. TGATools.GetTGAHeader = function (data) {
  34139. var offset = 0;
  34140. var header = {
  34141. id_length: data[offset++],
  34142. colormap_type: data[offset++],
  34143. image_type: data[offset++],
  34144. colormap_index: data[offset++] | data[offset++] << 8,
  34145. colormap_length: data[offset++] | data[offset++] << 8,
  34146. colormap_size: data[offset++],
  34147. origin: [
  34148. data[offset++] | data[offset++] << 8,
  34149. data[offset++] | data[offset++] << 8
  34150. ],
  34151. width: data[offset++] | data[offset++] << 8,
  34152. height: data[offset++] | data[offset++] << 8,
  34153. pixel_size: data[offset++],
  34154. flags: data[offset++]
  34155. };
  34156. return header;
  34157. };
  34158. TGATools.UploadContent = function (gl, data) {
  34159. // Not enough data to contain header ?
  34160. if (data.length < 19) {
  34161. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  34162. return;
  34163. }
  34164. // Read Header
  34165. var offset = 18;
  34166. var header = TGATools.GetTGAHeader(data);
  34167. // Assume it's a valid Targa file.
  34168. if (header.id_length + offset > data.length) {
  34169. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  34170. return;
  34171. }
  34172. // Skip not needed data
  34173. offset += header.id_length;
  34174. var use_rle = false;
  34175. var use_pal = false;
  34176. var use_rgb = false;
  34177. var use_grey = false;
  34178. // Get some informations.
  34179. switch (header.image_type) {
  34180. case TGATools._TYPE_RLE_INDEXED:
  34181. use_rle = true;
  34182. case TGATools._TYPE_INDEXED:
  34183. use_pal = true;
  34184. break;
  34185. case TGATools._TYPE_RLE_RGB:
  34186. use_rle = true;
  34187. case TGATools._TYPE_RGB:
  34188. use_rgb = true;
  34189. break;
  34190. case TGATools._TYPE_RLE_GREY:
  34191. use_rle = true;
  34192. case TGATools._TYPE_GREY:
  34193. use_grey = true;
  34194. break;
  34195. }
  34196. var pixel_data;
  34197. var numAlphaBits = header.flags & 0xf;
  34198. var pixel_size = header.pixel_size >> 3;
  34199. var pixel_total = header.width * header.height * pixel_size;
  34200. // Read palettes
  34201. var palettes;
  34202. if (use_pal) {
  34203. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  34204. }
  34205. // Read LRE
  34206. if (use_rle) {
  34207. pixel_data = new Uint8Array(pixel_total);
  34208. var c, count, i;
  34209. var localOffset = 0;
  34210. var pixels = new Uint8Array(pixel_size);
  34211. while (offset < pixel_total && localOffset < pixel_total) {
  34212. c = data[offset++];
  34213. count = (c & 0x7f) + 1;
  34214. // RLE pixels
  34215. if (c & 0x80) {
  34216. // Bind pixel tmp array
  34217. for (i = 0; i < pixel_size; ++i) {
  34218. pixels[i] = data[offset++];
  34219. }
  34220. // Copy pixel array
  34221. for (i = 0; i < count; ++i) {
  34222. pixel_data.set(pixels, localOffset + i * pixel_size);
  34223. }
  34224. localOffset += pixel_size * count;
  34225. }
  34226. else {
  34227. count *= pixel_size;
  34228. for (i = 0; i < count; ++i) {
  34229. pixel_data[localOffset + i] = data[offset++];
  34230. }
  34231. localOffset += count;
  34232. }
  34233. }
  34234. }
  34235. else {
  34236. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  34237. }
  34238. // Load to texture
  34239. var x_start, y_start, x_step, y_step, y_end, x_end;
  34240. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  34241. default:
  34242. case TGATools._ORIGIN_UL:
  34243. x_start = 0;
  34244. x_step = 1;
  34245. x_end = header.width;
  34246. y_start = 0;
  34247. y_step = 1;
  34248. y_end = header.height;
  34249. break;
  34250. case TGATools._ORIGIN_BL:
  34251. x_start = 0;
  34252. x_step = 1;
  34253. x_end = header.width;
  34254. y_start = header.height - 1;
  34255. y_step = -1;
  34256. y_end = -1;
  34257. break;
  34258. case TGATools._ORIGIN_UR:
  34259. x_start = header.width - 1;
  34260. x_step = -1;
  34261. x_end = -1;
  34262. y_start = 0;
  34263. y_step = 1;
  34264. y_end = header.height;
  34265. break;
  34266. case TGATools._ORIGIN_BR:
  34267. x_start = header.width - 1;
  34268. x_step = -1;
  34269. x_end = -1;
  34270. y_start = header.height - 1;
  34271. y_step = -1;
  34272. y_end = -1;
  34273. break;
  34274. }
  34275. // Load the specify method
  34276. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  34277. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  34278. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  34279. };
  34280. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34281. var image = pixel_data, colormap = palettes;
  34282. var width = header.width, height = header.height;
  34283. var color, i = 0, x, y;
  34284. var imageData = new Uint8Array(width * height * 4);
  34285. for (y = y_start; y !== y_end; y += y_step) {
  34286. for (x = x_start; x !== x_end; x += x_step, i++) {
  34287. color = image[i];
  34288. imageData[(x + width * y) * 4 + 3] = 255;
  34289. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  34290. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  34291. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  34292. }
  34293. }
  34294. return imageData;
  34295. };
  34296. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34297. var image = pixel_data;
  34298. var width = header.width, height = header.height;
  34299. var color, i = 0, x, y;
  34300. var imageData = new Uint8Array(width * height * 4);
  34301. for (y = y_start; y !== y_end; y += y_step) {
  34302. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34303. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  34304. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  34305. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  34306. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  34307. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  34308. }
  34309. }
  34310. return imageData;
  34311. };
  34312. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34313. var image = pixel_data;
  34314. var width = header.width, height = header.height;
  34315. var i = 0, x, y;
  34316. var imageData = new Uint8Array(width * height * 4);
  34317. for (y = y_start; y !== y_end; y += y_step) {
  34318. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  34319. imageData[(x + width * y) * 4 + 3] = 255;
  34320. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34321. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34322. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34323. }
  34324. }
  34325. return imageData;
  34326. };
  34327. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34328. var image = pixel_data;
  34329. var width = header.width, height = header.height;
  34330. var i = 0, x, y;
  34331. var imageData = new Uint8Array(width * height * 4);
  34332. for (y = y_start; y !== y_end; y += y_step) {
  34333. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  34334. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34335. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34336. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34337. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  34338. }
  34339. }
  34340. return imageData;
  34341. };
  34342. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34343. var image = pixel_data;
  34344. var width = header.width, height = header.height;
  34345. var color, i = 0, x, y;
  34346. var imageData = new Uint8Array(width * height * 4);
  34347. for (y = y_start; y !== y_end; y += y_step) {
  34348. for (x = x_start; x !== x_end; x += x_step, i++) {
  34349. color = image[i];
  34350. imageData[(x + width * y) * 4 + 0] = color;
  34351. imageData[(x + width * y) * 4 + 1] = color;
  34352. imageData[(x + width * y) * 4 + 2] = color;
  34353. imageData[(x + width * y) * 4 + 3] = 255;
  34354. }
  34355. }
  34356. return imageData;
  34357. };
  34358. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34359. var image = pixel_data;
  34360. var width = header.width, height = header.height;
  34361. var i = 0, x, y;
  34362. var imageData = new Uint8Array(width * height * 4);
  34363. for (y = y_start; y !== y_end; y += y_step) {
  34364. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34365. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  34366. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  34367. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34368. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  34369. }
  34370. }
  34371. return imageData;
  34372. };
  34373. TGATools._TYPE_NO_DATA = 0;
  34374. TGATools._TYPE_INDEXED = 1;
  34375. TGATools._TYPE_RGB = 2;
  34376. TGATools._TYPE_GREY = 3;
  34377. TGATools._TYPE_RLE_INDEXED = 9;
  34378. TGATools._TYPE_RLE_RGB = 10;
  34379. TGATools._TYPE_RLE_GREY = 11;
  34380. TGATools._ORIGIN_MASK = 0x30;
  34381. TGATools._ORIGIN_SHIFT = 0x04;
  34382. TGATools._ORIGIN_BL = 0x00;
  34383. TGATools._ORIGIN_BR = 0x01;
  34384. TGATools._ORIGIN_UL = 0x02;
  34385. TGATools._ORIGIN_UR = 0x03;
  34386. return TGATools;
  34387. }());
  34388. Internals.TGATools = TGATools;
  34389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34390. })(BABYLON || (BABYLON = {}));
  34391. //# sourceMappingURL=babylon.tga.js.map
  34392. var BABYLON;
  34393. (function (BABYLON) {
  34394. var Internals;
  34395. (function (Internals) {
  34396. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34397. // All values and structures referenced from:
  34398. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34399. var DDS_MAGIC = 0x20534444;
  34400. 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;
  34401. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34402. 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;
  34403. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34404. function FourCCToInt32(value) {
  34405. return value.charCodeAt(0) +
  34406. (value.charCodeAt(1) << 8) +
  34407. (value.charCodeAt(2) << 16) +
  34408. (value.charCodeAt(3) << 24);
  34409. }
  34410. function Int32ToFourCC(value) {
  34411. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34412. }
  34413. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34414. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34415. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34416. var FOURCC_DX10 = FourCCToInt32("DX10");
  34417. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  34418. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  34419. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  34420. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  34421. var headerLengthInt = 31; // The header length in 32 bit ints
  34422. // Offsets into the header array
  34423. var off_magic = 0;
  34424. var off_size = 1;
  34425. var off_flags = 2;
  34426. var off_height = 3;
  34427. var off_width = 4;
  34428. var off_mipmapCount = 7;
  34429. var off_pfFlags = 20;
  34430. var off_pfFourCC = 21;
  34431. var off_RGBbpp = 22;
  34432. var off_RMask = 23;
  34433. var off_GMask = 24;
  34434. var off_BMask = 25;
  34435. var off_AMask = 26;
  34436. var off_caps1 = 27;
  34437. var off_caps2 = 28;
  34438. var off_caps3 = 29;
  34439. var off_caps4 = 30;
  34440. var off_dxgiFormat = 32;
  34441. ;
  34442. var DDSTools = (function () {
  34443. function DDSTools() {
  34444. }
  34445. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34446. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34447. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  34448. var mipmapCount = 1;
  34449. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34450. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34451. }
  34452. var fourCC = header[off_pfFourCC];
  34453. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  34454. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34455. switch (fourCC) {
  34456. case FOURCC_D3DFMT_R16G16B16A16F:
  34457. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34458. break;
  34459. case FOURCC_D3DFMT_R32G32B32A32F:
  34460. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34461. break;
  34462. case FOURCC_DX10:
  34463. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  34464. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34465. break;
  34466. }
  34467. }
  34468. return {
  34469. width: header[off_width],
  34470. height: header[off_height],
  34471. mipmapCount: mipmapCount,
  34472. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34473. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34474. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34475. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  34476. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  34477. dxgiFormat: dxgiFormat,
  34478. textureType: textureType
  34479. };
  34480. };
  34481. DDSTools._ToHalfFloat = function (value) {
  34482. if (!DDSTools._FloatView) {
  34483. DDSTools._FloatView = new Float32Array(1);
  34484. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  34485. }
  34486. DDSTools._FloatView[0] = value;
  34487. var x = DDSTools._Int32View[0];
  34488. var bits = (x >> 16) & 0x8000; /* Get the sign */
  34489. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  34490. var e = (x >> 23) & 0xff; /* Using int is faster here */
  34491. /* If zero, or denormal, or exponent underflows too much for a denormal
  34492. * half, return signed zero. */
  34493. if (e < 103) {
  34494. return bits;
  34495. }
  34496. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34497. if (e > 142) {
  34498. bits |= 0x7c00;
  34499. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34500. * not Inf, so make sure we set one mantissa bit too. */
  34501. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  34502. return bits;
  34503. }
  34504. /* If exponent underflows but not too much, return a denormal */
  34505. if (e < 113) {
  34506. m |= 0x0800;
  34507. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34508. * to 1, which is OK. */
  34509. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  34510. return bits;
  34511. }
  34512. bits |= ((e - 112) << 10) | (m >> 1);
  34513. bits += m & 1;
  34514. return bits;
  34515. };
  34516. DDSTools._FromHalfFloat = function (value) {
  34517. var s = (value & 0x8000) >> 15;
  34518. var e = (value & 0x7C00) >> 10;
  34519. var f = value & 0x03FF;
  34520. if (e === 0) {
  34521. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  34522. }
  34523. else if (e == 0x1F) {
  34524. return f ? NaN : ((s ? -1 : 1) * Infinity);
  34525. }
  34526. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  34527. };
  34528. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34529. var destArray = new Float32Array(dataLength);
  34530. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34531. var index = 0;
  34532. for (var y = 0; y < height; y++) {
  34533. for (var x = 0; x < width; x++) {
  34534. var srcPos = (x + y * width) * 4;
  34535. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  34536. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  34537. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  34538. if (DDSTools.StoreLODInAlphaChannel) {
  34539. destArray[index + 3] = lod;
  34540. }
  34541. else {
  34542. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  34543. }
  34544. index += 4;
  34545. }
  34546. }
  34547. return destArray;
  34548. };
  34549. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34550. if (DDSTools.StoreLODInAlphaChannel) {
  34551. var destArray = new Uint16Array(dataLength);
  34552. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34553. var index = 0;
  34554. for (var y = 0; y < height; y++) {
  34555. for (var x = 0; x < width; x++) {
  34556. var srcPos = (x + y * width) * 4;
  34557. destArray[index] = srcData[srcPos];
  34558. destArray[index + 1] = srcData[srcPos + 1];
  34559. destArray[index + 2] = srcData[srcPos + 2];
  34560. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  34561. index += 4;
  34562. }
  34563. }
  34564. return destArray;
  34565. }
  34566. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  34567. };
  34568. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34569. if (DDSTools.StoreLODInAlphaChannel) {
  34570. var destArray = new Float32Array(dataLength);
  34571. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34572. var index = 0;
  34573. for (var y = 0; y < height; y++) {
  34574. for (var x = 0; x < width; x++) {
  34575. var srcPos = (x + y * width) * 4;
  34576. destArray[index] = srcData[srcPos];
  34577. destArray[index + 1] = srcData[srcPos + 1];
  34578. destArray[index + 2] = srcData[srcPos + 2];
  34579. destArray[index + 3] = lod;
  34580. index += 4;
  34581. }
  34582. }
  34583. return destArray;
  34584. }
  34585. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  34586. };
  34587. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34588. var destArray = new Uint8Array(dataLength);
  34589. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34590. var index = 0;
  34591. for (var y = 0; y < height; y++) {
  34592. for (var x = 0; x < width; x++) {
  34593. var srcPos = (x + y * width) * 4;
  34594. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  34595. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  34596. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  34597. if (DDSTools.StoreLODInAlphaChannel) {
  34598. destArray[index + 3] = lod;
  34599. }
  34600. else {
  34601. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  34602. }
  34603. index += 4;
  34604. }
  34605. }
  34606. return destArray;
  34607. };
  34608. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34609. var destArray = new Uint8Array(dataLength);
  34610. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34611. var index = 0;
  34612. for (var y = 0; y < height; y++) {
  34613. for (var x = 0; x < width; x++) {
  34614. var srcPos = (x + y * width) * 4;
  34615. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  34616. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  34617. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  34618. if (DDSTools.StoreLODInAlphaChannel) {
  34619. destArray[index + 3] = lod;
  34620. }
  34621. else {
  34622. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  34623. }
  34624. index += 4;
  34625. }
  34626. }
  34627. return destArray;
  34628. };
  34629. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34630. var byteArray = new Uint8Array(dataLength);
  34631. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34632. var index = 0;
  34633. for (var y = 0; y < height; y++) {
  34634. for (var x = 0; x < width; x++) {
  34635. var srcPos = (x + y * width) * 4;
  34636. byteArray[index] = srcData[srcPos + 2];
  34637. byteArray[index + 1] = srcData[srcPos + 1];
  34638. byteArray[index + 2] = srcData[srcPos];
  34639. byteArray[index + 3] = srcData[srcPos + 3];
  34640. index += 4;
  34641. }
  34642. }
  34643. return byteArray;
  34644. };
  34645. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34646. var byteArray = new Uint8Array(dataLength);
  34647. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34648. var index = 0;
  34649. for (var y = 0; y < height; y++) {
  34650. for (var x = 0; x < width; x++) {
  34651. var srcPos = (x + y * width) * 3;
  34652. byteArray[index] = srcData[srcPos + 2];
  34653. byteArray[index + 1] = srcData[srcPos + 1];
  34654. byteArray[index + 2] = srcData[srcPos];
  34655. index += 3;
  34656. }
  34657. }
  34658. return byteArray;
  34659. };
  34660. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34661. var byteArray = new Uint8Array(dataLength);
  34662. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34663. var index = 0;
  34664. for (var y = 0; y < height; y++) {
  34665. for (var x = 0; x < width; x++) {
  34666. var srcPos = (x + y * width);
  34667. byteArray[index] = srcData[srcPos];
  34668. index++;
  34669. }
  34670. }
  34671. return byteArray;
  34672. };
  34673. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34674. if (lodIndex === void 0) { lodIndex = -1; }
  34675. var ext = engine.getCaps().s3tc;
  34676. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34677. if (header[off_magic] != DDS_MAGIC) {
  34678. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34679. return;
  34680. }
  34681. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34682. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34683. return;
  34684. }
  34685. if (info.isCompressed && !ext) {
  34686. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34687. return;
  34688. }
  34689. var bpp = header[off_RGBbpp];
  34690. dataOffset = header[off_size] + 4;
  34691. var computeFormats = false;
  34692. if (info.isFourCC) {
  34693. fourCC = header[off_pfFourCC];
  34694. switch (fourCC) {
  34695. case FOURCC_DXT1:
  34696. blockBytes = 8;
  34697. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34698. break;
  34699. case FOURCC_DXT3:
  34700. blockBytes = 16;
  34701. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34702. break;
  34703. case FOURCC_DXT5:
  34704. blockBytes = 16;
  34705. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34706. break;
  34707. case FOURCC_D3DFMT_R16G16B16A16F:
  34708. computeFormats = true;
  34709. break;
  34710. case FOURCC_D3DFMT_R32G32B32A32F:
  34711. computeFormats = true;
  34712. break;
  34713. case FOURCC_DX10:
  34714. // There is an additionnal header so dataOffset need to be changed
  34715. dataOffset += 5 * 4; // 5 uints
  34716. var supported = false;
  34717. switch (info.dxgiFormat) {
  34718. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34719. computeFormats = true;
  34720. supported = true;
  34721. break;
  34722. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34723. info.isRGB = true;
  34724. info.isFourCC = false;
  34725. bpp = 32;
  34726. supported = true;
  34727. break;
  34728. }
  34729. if (supported) {
  34730. break;
  34731. }
  34732. default:
  34733. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34734. return;
  34735. }
  34736. }
  34737. if (computeFormats) {
  34738. format = engine._getWebGLTextureType(info.textureType);
  34739. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34740. }
  34741. mipmapCount = 1;
  34742. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34743. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34744. }
  34745. for (var face = 0; face < faces; face++) {
  34746. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34747. width = header[off_width];
  34748. height = header[off_height];
  34749. for (mip = 0; mip < mipmapCount; ++mip) {
  34750. if (lodIndex === -1 || lodIndex === mip) {
  34751. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34752. var i = (lodIndex === -1) ? mip : 0;
  34753. if (!info.isCompressed && info.isFourCC) {
  34754. dataLength = width * height * 4;
  34755. var floatArray;
  34756. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34757. if (bpp === 128) {
  34758. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34759. }
  34760. else if (bpp === 64) {
  34761. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34762. }
  34763. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34764. format = engine._getWebGLTextureType(info.textureType);
  34765. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34766. }
  34767. else {
  34768. if (bpp === 128) {
  34769. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34770. }
  34771. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34772. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34773. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34774. format = engine._getWebGLTextureType(info.textureType);
  34775. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34776. }
  34777. else {
  34778. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34779. }
  34780. }
  34781. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34782. }
  34783. else if (info.isRGB) {
  34784. if (bpp === 24) {
  34785. dataLength = width * height * 3;
  34786. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34787. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34788. }
  34789. else {
  34790. dataLength = width * height * 4;
  34791. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34792. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34793. }
  34794. }
  34795. else if (info.isLuminance) {
  34796. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34797. var unpaddedRowSize = width;
  34798. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34799. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34800. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34801. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34802. }
  34803. else {
  34804. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34805. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34806. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34807. }
  34808. }
  34809. dataOffset += width * height * (bpp / 8);
  34810. width *= 0.5;
  34811. height *= 0.5;
  34812. width = Math.max(1.0, width);
  34813. height = Math.max(1.0, height);
  34814. }
  34815. }
  34816. };
  34817. DDSTools.StoreLODInAlphaChannel = false;
  34818. return DDSTools;
  34819. }());
  34820. Internals.DDSTools = DDSTools;
  34821. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34822. })(BABYLON || (BABYLON = {}));
  34823. //# sourceMappingURL=babylon.dds.js.map
  34824. var BABYLON;
  34825. (function (BABYLON) {
  34826. var Internals;
  34827. (function (Internals) {
  34828. /**
  34829. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34830. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34831. */
  34832. var KhronosTextureContainer = (function () {
  34833. /**
  34834. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34835. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34836. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34837. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34838. */
  34839. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34840. this.arrayBuffer = arrayBuffer;
  34841. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34842. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34843. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34844. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34845. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34846. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34847. BABYLON.Tools.Error("texture missing KTX identifier");
  34848. return;
  34849. }
  34850. // load the reset of the header in native 32 bit int
  34851. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34852. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34853. var oppositeEndianess = header[0] === 0x01020304;
  34854. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34855. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34856. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34857. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34858. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34859. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34860. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34861. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34862. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34863. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34864. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34865. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34866. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34867. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34868. if (this.glType !== 0) {
  34869. BABYLON.Tools.Error("only compressed formats currently supported");
  34870. return;
  34871. }
  34872. else {
  34873. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34874. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34875. }
  34876. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34877. BABYLON.Tools.Error("only 2D textures currently supported");
  34878. return;
  34879. }
  34880. if (this.numberOfArrayElements !== 0) {
  34881. BABYLON.Tools.Error("texture arrays not currently supported");
  34882. return;
  34883. }
  34884. if (this.numberOfFaces !== facesExpected) {
  34885. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34886. return;
  34887. }
  34888. // we now have a completely validated file, so could use existence of loadType as success
  34889. // would need to make this more elaborate & adjust checks above to support more than one load type
  34890. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  34891. }
  34892. // not as fast hardware based, but will probably never need to use
  34893. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  34894. return ((val & 0xFF) << 24)
  34895. | ((val & 0xFF00) << 8)
  34896. | ((val >> 8) & 0xFF00)
  34897. | ((val >> 24) & 0xFF);
  34898. };
  34899. /**
  34900. * It is assumed that the texture has already been created & is currently bound
  34901. */
  34902. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  34903. switch (this.loadType) {
  34904. case KhronosTextureContainer.COMPRESSED_2D:
  34905. this._upload2DCompressedLevels(gl, loadMipmaps);
  34906. break;
  34907. case KhronosTextureContainer.TEX_2D:
  34908. case KhronosTextureContainer.COMPRESSED_3D:
  34909. case KhronosTextureContainer.TEX_3D:
  34910. }
  34911. };
  34912. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  34913. // initialize width & height for level 1
  34914. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  34915. var width = this.pixelWidth;
  34916. var height = this.pixelHeight;
  34917. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  34918. for (var level = 0; level < mipmapCount; level++) {
  34919. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  34920. for (var face = 0; face < this.numberOfFaces; face++) {
  34921. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34922. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  34923. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  34924. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  34925. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  34926. }
  34927. width = Math.max(1.0, width * 0.5);
  34928. height = Math.max(1.0, height * 0.5);
  34929. }
  34930. };
  34931. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  34932. // load types
  34933. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  34934. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  34935. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  34936. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  34937. return KhronosTextureContainer;
  34938. }());
  34939. Internals.KhronosTextureContainer = KhronosTextureContainer;
  34940. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34941. })(BABYLON || (BABYLON = {}));
  34942. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  34943. var BABYLON;
  34944. (function (BABYLON) {
  34945. var PostProcess = (function () {
  34946. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  34947. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34948. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34949. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  34950. if (blockCompilation === void 0) { blockCompilation = false; }
  34951. this.name = name;
  34952. this.width = -1;
  34953. this.height = -1;
  34954. this.autoClear = true;
  34955. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  34956. /*
  34957. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34958. Can only be used on a single postprocess or on the last one of a chain.
  34959. */
  34960. this.enablePixelPerfectMode = false;
  34961. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  34962. this.alwaysForcePOT = false;
  34963. this.samples = 1;
  34964. this._reusable = false;
  34965. this._textures = new BABYLON.SmartArray(2);
  34966. this._currentRenderTextureInd = 0;
  34967. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34968. this._texelSize = BABYLON.Vector2.Zero();
  34969. // Events
  34970. /**
  34971. * An event triggered when the postprocess is activated.
  34972. * @type {BABYLON.Observable}
  34973. */
  34974. this.onActivateObservable = new BABYLON.Observable();
  34975. /**
  34976. * An event triggered when the postprocess changes its size.
  34977. * @type {BABYLON.Observable}
  34978. */
  34979. this.onSizeChangedObservable = new BABYLON.Observable();
  34980. /**
  34981. * An event triggered when the postprocess applies its effect.
  34982. * @type {BABYLON.Observable}
  34983. */
  34984. this.onApplyObservable = new BABYLON.Observable();
  34985. /**
  34986. * An event triggered before rendering the postprocess
  34987. * @type {BABYLON.Observable}
  34988. */
  34989. this.onBeforeRenderObservable = new BABYLON.Observable();
  34990. /**
  34991. * An event triggered after rendering the postprocess
  34992. * @type {BABYLON.Observable}
  34993. */
  34994. this.onAfterRenderObservable = new BABYLON.Observable();
  34995. if (camera != null) {
  34996. this._camera = camera;
  34997. this._scene = camera.getScene();
  34998. camera.attachPostProcess(this);
  34999. this._engine = this._scene.getEngine();
  35000. this._scene.postProcesses.push(this);
  35001. }
  35002. else {
  35003. this._engine = engine;
  35004. this._engine.postProcesses.push(this);
  35005. }
  35006. this._options = options;
  35007. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35008. this._reusable = reusable || false;
  35009. this._textureType = textureType;
  35010. this._samplers = samplers || [];
  35011. this._samplers.push("textureSampler");
  35012. this._fragmentUrl = fragmentUrl;
  35013. this._vertexUrl = vertexUrl;
  35014. this._parameters = parameters || [];
  35015. this._parameters.push("scale");
  35016. this._indexParameters = indexParameters;
  35017. if (!blockCompilation) {
  35018. this.updateEffect(defines);
  35019. }
  35020. }
  35021. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35022. set: function (callback) {
  35023. if (this._onActivateObserver) {
  35024. this.onActivateObservable.remove(this._onActivateObserver);
  35025. }
  35026. this._onActivateObserver = this.onActivateObservable.add(callback);
  35027. },
  35028. enumerable: true,
  35029. configurable: true
  35030. });
  35031. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35032. set: function (callback) {
  35033. if (this._onSizeChangedObserver) {
  35034. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35035. }
  35036. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35037. },
  35038. enumerable: true,
  35039. configurable: true
  35040. });
  35041. Object.defineProperty(PostProcess.prototype, "onApply", {
  35042. set: function (callback) {
  35043. if (this._onApplyObserver) {
  35044. this.onApplyObservable.remove(this._onApplyObserver);
  35045. }
  35046. this._onApplyObserver = this.onApplyObservable.add(callback);
  35047. },
  35048. enumerable: true,
  35049. configurable: true
  35050. });
  35051. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35052. set: function (callback) {
  35053. if (this._onBeforeRenderObserver) {
  35054. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35055. }
  35056. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35062. set: function (callback) {
  35063. if (this._onAfterRenderObserver) {
  35064. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35065. }
  35066. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35067. },
  35068. enumerable: true,
  35069. configurable: true
  35070. });
  35071. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  35072. get: function () {
  35073. return this._textures.data[this._currentRenderTextureInd];
  35074. },
  35075. set: function (value) {
  35076. this._forcedOutputTexture = value;
  35077. },
  35078. enumerable: true,
  35079. configurable: true
  35080. });
  35081. PostProcess.prototype.getCamera = function () {
  35082. return this._camera;
  35083. };
  35084. Object.defineProperty(PostProcess.prototype, "texelSize", {
  35085. get: function () {
  35086. if (this._shareOutputWithPostProcess) {
  35087. return this._shareOutputWithPostProcess.texelSize;
  35088. }
  35089. if (this._forcedOutputTexture) {
  35090. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  35091. }
  35092. return this._texelSize;
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. PostProcess.prototype.getEngine = function () {
  35098. return this._engine;
  35099. };
  35100. PostProcess.prototype.getEffect = function () {
  35101. return this._effect;
  35102. };
  35103. PostProcess.prototype.shareOutputWith = function (postProcess) {
  35104. this._disposeTextures();
  35105. this._shareOutputWithPostProcess = postProcess;
  35106. return this;
  35107. };
  35108. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  35109. 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);
  35110. };
  35111. PostProcess.prototype.isReusable = function () {
  35112. return this._reusable;
  35113. };
  35114. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35115. PostProcess.prototype.markTextureDirty = function () {
  35116. this.width = -1;
  35117. };
  35118. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  35119. var _this = this;
  35120. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  35121. camera = camera || this._camera;
  35122. var scene = camera.getScene();
  35123. var engine = scene.getEngine();
  35124. var maxSize = engine.getCaps().maxTextureSize;
  35125. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35126. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35127. var desiredWidth = this._options.width || requiredWidth;
  35128. var desiredHeight = this._options.height || requiredHeight;
  35129. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  35130. if (!this._options.width) {
  35131. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  35132. }
  35133. if (!this._options.height) {
  35134. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  35135. }
  35136. }
  35137. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35138. if (this._textures.length > 0) {
  35139. for (var i = 0; i < this._textures.length; i++) {
  35140. this._engine._releaseTexture(this._textures.data[i]);
  35141. }
  35142. this._textures.reset();
  35143. }
  35144. this.width = desiredWidth;
  35145. this.height = desiredHeight;
  35146. var textureSize = { width: this.width, height: this.height };
  35147. var textureOptions = {
  35148. generateMipMaps: false,
  35149. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  35150. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  35151. samplingMode: this.renderTargetSamplingMode,
  35152. type: this._textureType
  35153. };
  35154. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35155. if (this._reusable) {
  35156. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35157. }
  35158. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  35159. this.onSizeChangedObservable.notifyObservers(this);
  35160. }
  35161. this._textures.forEach(function (texture) {
  35162. if (texture.samples !== _this.samples) {
  35163. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35164. }
  35165. });
  35166. }
  35167. var target;
  35168. if (this._shareOutputWithPostProcess) {
  35169. target = this._shareOutputWithPostProcess.outputTexture;
  35170. }
  35171. else if (this._forcedOutputTexture) {
  35172. target = this._forcedOutputTexture;
  35173. this.width = this._forcedOutputTexture.width;
  35174. this.height = this._forcedOutputTexture.height;
  35175. }
  35176. else {
  35177. target = this.outputTexture;
  35178. }
  35179. if (this.enablePixelPerfectMode) {
  35180. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35181. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  35182. }
  35183. else {
  35184. this._scaleRatio.copyFromFloats(1, 1);
  35185. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  35186. }
  35187. this.onActivateObservable.notifyObservers(camera);
  35188. // Clear
  35189. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  35190. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  35191. }
  35192. if (this._reusable) {
  35193. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35194. }
  35195. };
  35196. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35197. get: function () {
  35198. return this._effect.isSupported;
  35199. },
  35200. enumerable: true,
  35201. configurable: true
  35202. });
  35203. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  35204. get: function () {
  35205. if (this._shareOutputWithPostProcess) {
  35206. return this._shareOutputWithPostProcess.aspectRatio;
  35207. }
  35208. if (this._forcedOutputTexture) {
  35209. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  35210. }
  35211. return this.width / this.height;
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. PostProcess.prototype.apply = function () {
  35217. // Check
  35218. if (!this._effect || !this._effect.isReady())
  35219. return null;
  35220. // States
  35221. this._engine.enableEffect(this._effect);
  35222. this._engine.setState(false);
  35223. this._engine.setDepthBuffer(false);
  35224. this._engine.setDepthWrite(false);
  35225. // Alpha
  35226. this._engine.setAlphaMode(this.alphaMode);
  35227. if (this.alphaConstants) {
  35228. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  35229. }
  35230. // Texture
  35231. var source;
  35232. if (this._shareOutputWithPostProcess) {
  35233. source = this._shareOutputWithPostProcess.outputTexture;
  35234. }
  35235. else if (this._forcedOutputTexture) {
  35236. source = this._forcedOutputTexture;
  35237. }
  35238. else {
  35239. source = this.outputTexture;
  35240. }
  35241. this._effect._bindTexture("textureSampler", source);
  35242. // Parameters
  35243. this._effect.setVector2("scale", this._scaleRatio);
  35244. this.onApplyObservable.notifyObservers(this._effect);
  35245. return this._effect;
  35246. };
  35247. PostProcess.prototype._disposeTextures = function () {
  35248. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  35249. return;
  35250. }
  35251. if (this._textures.length > 0) {
  35252. for (var i = 0; i < this._textures.length; i++) {
  35253. this._engine._releaseTexture(this._textures.data[i]);
  35254. }
  35255. }
  35256. this._textures.dispose();
  35257. };
  35258. PostProcess.prototype.dispose = function (camera) {
  35259. camera = camera || this._camera;
  35260. this._disposeTextures();
  35261. if (this._scene) {
  35262. var index_1 = this._scene.postProcesses.indexOf(this);
  35263. if (index_1 !== -1) {
  35264. this._scene.postProcesses.splice(index_1, 1);
  35265. }
  35266. }
  35267. else {
  35268. var index_2 = this._engine.postProcesses.indexOf(this);
  35269. if (index_2 !== -1) {
  35270. this._engine.postProcesses.splice(index_2, 1);
  35271. }
  35272. }
  35273. if (!camera) {
  35274. return;
  35275. }
  35276. camera.detachPostProcess(this);
  35277. var index = camera._postProcesses.indexOf(this);
  35278. if (index === 0 && camera._postProcesses.length > 0) {
  35279. this._camera._postProcesses[0].markTextureDirty();
  35280. }
  35281. this.onActivateObservable.clear();
  35282. this.onAfterRenderObservable.clear();
  35283. this.onApplyObservable.clear();
  35284. this.onBeforeRenderObservable.clear();
  35285. this.onSizeChangedObservable.clear();
  35286. };
  35287. return PostProcess;
  35288. }());
  35289. BABYLON.PostProcess = PostProcess;
  35290. })(BABYLON || (BABYLON = {}));
  35291. //# sourceMappingURL=babylon.postProcess.js.map
  35292. var BABYLON;
  35293. (function (BABYLON) {
  35294. var PassPostProcess = (function (_super) {
  35295. __extends(PassPostProcess, _super);
  35296. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  35297. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35298. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  35299. }
  35300. return PassPostProcess;
  35301. }(BABYLON.PostProcess));
  35302. BABYLON.PassPostProcess = PassPostProcess;
  35303. })(BABYLON || (BABYLON = {}));
  35304. //# sourceMappingURL=babylon.passPostProcess.js.map
  35305. var BABYLON;
  35306. (function (BABYLON) {
  35307. var ShadowGenerator = (function () {
  35308. /**
  35309. * Creates a ShadowGenerator object.
  35310. * A ShadowGenerator is the required tool to use the shadows.
  35311. * Each light casting shadows needs to use its own ShadowGenerator.
  35312. * Required parameters :
  35313. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  35314. * - `light`: the light object generating the shadows.
  35315. * - `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.
  35316. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  35317. */
  35318. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  35319. // Members
  35320. this._bias = 0.00005;
  35321. this._blurBoxOffset = 1;
  35322. this._blurScale = 2;
  35323. this._blurKernel = 1;
  35324. this._useKernelBlur = false;
  35325. this._filter = ShadowGenerator.FILTER_NONE;
  35326. this._darkness = 0;
  35327. this._transparencyShadow = false;
  35328. /**
  35329. * Controls the extent to which the shadows fade out at the edge of the frustum
  35330. * Used only by directionals and spots
  35331. */
  35332. this.frustumEdgeFalloff = 0;
  35333. this.forceBackFacesOnly = false;
  35334. this._lightDirection = BABYLON.Vector3.Zero();
  35335. this._viewMatrix = BABYLON.Matrix.Zero();
  35336. this._projectionMatrix = BABYLON.Matrix.Zero();
  35337. this._transformMatrix = BABYLON.Matrix.Zero();
  35338. this._worldViewProjection = BABYLON.Matrix.Zero();
  35339. this._currentFaceIndex = 0;
  35340. this._currentFaceIndexCache = 0;
  35341. this._isCube = false;
  35342. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  35343. this._mapSize = mapSize;
  35344. this._light = light;
  35345. this._scene = light.getScene();
  35346. light._shadowGenerator = this;
  35347. // Texture type fallback from float to int if not supported.
  35348. var caps = this._scene.getEngine().getCaps();
  35349. if (!useFullFloatFirst) {
  35350. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35351. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35352. }
  35353. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35354. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35355. }
  35356. else {
  35357. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35358. }
  35359. }
  35360. else {
  35361. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35362. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35363. }
  35364. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35365. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35366. }
  35367. else {
  35368. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35369. }
  35370. }
  35371. this._initializeGenerator();
  35372. }
  35373. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  35374. // Static
  35375. get: function () {
  35376. return ShadowGenerator._FILTER_NONE;
  35377. },
  35378. enumerable: true,
  35379. configurable: true
  35380. });
  35381. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  35382. get: function () {
  35383. return ShadowGenerator._FILTER_POISSONSAMPLING;
  35384. },
  35385. enumerable: true,
  35386. configurable: true
  35387. });
  35388. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  35389. get: function () {
  35390. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  35391. },
  35392. enumerable: true,
  35393. configurable: true
  35394. });
  35395. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  35396. get: function () {
  35397. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  35398. },
  35399. enumerable: true,
  35400. configurable: true
  35401. });
  35402. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  35403. get: function () {
  35404. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35405. },
  35406. enumerable: true,
  35407. configurable: true
  35408. });
  35409. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  35410. get: function () {
  35411. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35412. },
  35413. enumerable: true,
  35414. configurable: true
  35415. });
  35416. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  35417. get: function () {
  35418. return this._bias;
  35419. },
  35420. set: function (bias) {
  35421. this._bias = bias;
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  35427. get: function () {
  35428. return this._blurBoxOffset;
  35429. },
  35430. set: function (value) {
  35431. if (this._blurBoxOffset === value) {
  35432. return;
  35433. }
  35434. this._blurBoxOffset = value;
  35435. this._disposeBlurPostProcesses();
  35436. },
  35437. enumerable: true,
  35438. configurable: true
  35439. });
  35440. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  35441. get: function () {
  35442. return this._blurScale;
  35443. },
  35444. set: function (value) {
  35445. if (this._blurScale === value) {
  35446. return;
  35447. }
  35448. this._blurScale = value;
  35449. this._disposeBlurPostProcesses();
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  35455. get: function () {
  35456. return this._blurKernel;
  35457. },
  35458. set: function (value) {
  35459. if (this._blurKernel === value) {
  35460. return;
  35461. }
  35462. this._blurKernel = value;
  35463. this._disposeBlurPostProcesses();
  35464. },
  35465. enumerable: true,
  35466. configurable: true
  35467. });
  35468. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  35469. get: function () {
  35470. return this._useKernelBlur;
  35471. },
  35472. set: function (value) {
  35473. if (this._useKernelBlur === value) {
  35474. return;
  35475. }
  35476. this._useKernelBlur = value;
  35477. this._disposeBlurPostProcesses();
  35478. },
  35479. enumerable: true,
  35480. configurable: true
  35481. });
  35482. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  35483. get: function () {
  35484. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  35485. },
  35486. set: function (value) {
  35487. this._depthScale = value;
  35488. },
  35489. enumerable: true,
  35490. configurable: true
  35491. });
  35492. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  35493. get: function () {
  35494. return this._filter;
  35495. },
  35496. set: function (value) {
  35497. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  35498. if (this._light.needCube()) {
  35499. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35500. this.useExponentialShadowMap = true;
  35501. return;
  35502. }
  35503. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35504. this.useCloseExponentialShadowMap = true;
  35505. return;
  35506. }
  35507. }
  35508. if (this._filter === value) {
  35509. return;
  35510. }
  35511. this._filter = value;
  35512. this._disposeBlurPostProcesses();
  35513. this._applyFilterValues();
  35514. this._light._markMeshesAsLightDirty();
  35515. },
  35516. enumerable: true,
  35517. configurable: true
  35518. });
  35519. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  35520. get: function () {
  35521. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  35522. },
  35523. set: function (value) {
  35524. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  35525. return;
  35526. }
  35527. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  35528. },
  35529. enumerable: true,
  35530. configurable: true
  35531. });
  35532. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  35533. get: function () {
  35534. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35535. return this.useExponentialShadowMap;
  35536. },
  35537. set: function (value) {
  35538. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35539. this.useExponentialShadowMap = value;
  35540. },
  35541. enumerable: true,
  35542. configurable: true
  35543. });
  35544. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  35545. get: function () {
  35546. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35547. return this.useBlurExponentialShadowMap;
  35548. },
  35549. set: function (value) {
  35550. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35551. this.useBlurExponentialShadowMap = value;
  35552. },
  35553. enumerable: true,
  35554. configurable: true
  35555. });
  35556. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  35557. get: function () {
  35558. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  35559. },
  35560. set: function (value) {
  35561. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  35562. return;
  35563. }
  35564. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35565. },
  35566. enumerable: true,
  35567. configurable: true
  35568. });
  35569. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  35570. get: function () {
  35571. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  35572. },
  35573. set: function (value) {
  35574. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35575. return;
  35576. }
  35577. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35578. },
  35579. enumerable: true,
  35580. configurable: true
  35581. });
  35582. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  35583. get: function () {
  35584. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35585. },
  35586. set: function (value) {
  35587. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  35588. return;
  35589. }
  35590. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35591. },
  35592. enumerable: true,
  35593. configurable: true
  35594. });
  35595. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  35596. get: function () {
  35597. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35598. },
  35599. set: function (value) {
  35600. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35601. return;
  35602. }
  35603. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35604. },
  35605. enumerable: true,
  35606. configurable: true
  35607. });
  35608. /**
  35609. * Returns the darkness value (float).
  35610. */
  35611. ShadowGenerator.prototype.getDarkness = function () {
  35612. return this._darkness;
  35613. };
  35614. /**
  35615. * Sets the ShadowGenerator darkness value (float <= 1.0).
  35616. * Returns the ShadowGenerator.
  35617. */
  35618. ShadowGenerator.prototype.setDarkness = function (darkness) {
  35619. if (darkness >= 1.0)
  35620. this._darkness = 1.0;
  35621. else if (darkness <= 0.0)
  35622. this._darkness = 0.0;
  35623. else
  35624. this._darkness = darkness;
  35625. return this;
  35626. };
  35627. /**
  35628. * Sets the ability to have transparent shadow (boolean).
  35629. * Returns the ShadowGenerator.
  35630. */
  35631. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  35632. this._transparencyShadow = hasShadow;
  35633. return this;
  35634. };
  35635. /**
  35636. * Returns a RenderTargetTexture object : the shadow map texture.
  35637. */
  35638. ShadowGenerator.prototype.getShadowMap = function () {
  35639. return this._shadowMap;
  35640. };
  35641. /**
  35642. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  35643. */
  35644. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  35645. if (this._shadowMap2) {
  35646. return this._shadowMap2;
  35647. }
  35648. return this._shadowMap;
  35649. };
  35650. /**
  35651. * Returns the associated light object.
  35652. */
  35653. ShadowGenerator.prototype.getLight = function () {
  35654. return this._light;
  35655. };
  35656. ShadowGenerator.prototype._initializeGenerator = function () {
  35657. this._light._markMeshesAsLightDirty();
  35658. this._initializeShadowMap();
  35659. };
  35660. ShadowGenerator.prototype._initializeShadowMap = function () {
  35661. var _this = this;
  35662. // Render target
  35663. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35664. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35665. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35666. this._shadowMap.anisotropicFilteringLevel = 1;
  35667. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35668. this._shadowMap.renderParticles = false;
  35669. // Record Face Index before render.
  35670. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35671. _this._currentFaceIndex = faceIndex;
  35672. });
  35673. // Custom render function.
  35674. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35675. // Blur if required afer render.
  35676. this._shadowMap.onAfterUnbindObservable.add(function () {
  35677. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35678. return;
  35679. }
  35680. if (!_this._blurPostProcesses) {
  35681. _this._initializeBlurRTTAndPostProcesses();
  35682. }
  35683. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35684. });
  35685. // Clear according to the chosen filter.
  35686. this._shadowMap.onClearObservable.add(function (engine) {
  35687. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35688. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35689. }
  35690. else {
  35691. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35692. }
  35693. });
  35694. };
  35695. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35696. var _this = this;
  35697. var engine = this._scene.getEngine();
  35698. var targetSize = this._mapSize / this.blurScale;
  35699. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35700. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35701. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35702. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35703. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35704. }
  35705. if (this.useKernelBlur) {
  35706. 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);
  35707. this._kernelBlurXPostprocess.width = targetSize;
  35708. this._kernelBlurXPostprocess.height = targetSize;
  35709. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35710. effect.setTexture("textureSampler", _this._shadowMap);
  35711. });
  35712. 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);
  35713. this._kernelBlurXPostprocess.autoClear = false;
  35714. this._kernelBlurYPostprocess.autoClear = false;
  35715. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35716. this._kernelBlurXPostprocess.packedFloat = true;
  35717. this._kernelBlurYPostprocess.packedFloat = true;
  35718. }
  35719. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35720. }
  35721. else {
  35722. 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);
  35723. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35724. effect.setFloat2("screenSize", targetSize, targetSize);
  35725. effect.setTexture("textureSampler", _this._shadowMap);
  35726. });
  35727. this._boxBlurPostprocess.autoClear = false;
  35728. this._blurPostProcesses = [this._boxBlurPostprocess];
  35729. }
  35730. };
  35731. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35732. var index;
  35733. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35734. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35735. }
  35736. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35737. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35738. }
  35739. if (this._transparencyShadow) {
  35740. for (index = 0; index < transparentSubMeshes.length; index++) {
  35741. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35742. }
  35743. }
  35744. };
  35745. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35746. var _this = this;
  35747. var mesh = subMesh.getRenderingMesh();
  35748. var scene = this._scene;
  35749. var engine = scene.getEngine();
  35750. // Culling
  35751. engine.setState(subMesh.getMaterial().backFaceCulling);
  35752. // Managing instances
  35753. var batch = mesh._getInstancesRenderList(subMesh._id);
  35754. if (batch.mustReturn) {
  35755. return;
  35756. }
  35757. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35758. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35759. engine.enableEffect(this._effect);
  35760. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35761. var material = subMesh.getMaterial();
  35762. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35763. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35764. this._effect.setVector3("lightPosition", this.getLight().position);
  35765. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35766. // Alpha test
  35767. if (material && material.needAlphaTesting()) {
  35768. var alphaTexture = material.getAlphaTestTexture();
  35769. if (alphaTexture) {
  35770. this._effect.setTexture("diffuseSampler", alphaTexture);
  35771. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35772. }
  35773. }
  35774. // Bones
  35775. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35776. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35777. }
  35778. if (this.forceBackFacesOnly) {
  35779. engine.setState(true, 0, false, true);
  35780. }
  35781. // Draw
  35782. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35783. if (this.forceBackFacesOnly) {
  35784. engine.setState(true, 0, false, false);
  35785. }
  35786. }
  35787. else {
  35788. // Need to reset refresh rate of the shadowMap
  35789. this._shadowMap.resetRefreshCounter();
  35790. }
  35791. };
  35792. ShadowGenerator.prototype._applyFilterValues = function () {
  35793. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35794. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35795. }
  35796. else {
  35797. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35798. }
  35799. };
  35800. /**
  35801. * Force shader compilation including textures ready check
  35802. */
  35803. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35804. var _this = this;
  35805. var scene = this._scene;
  35806. var engine = scene.getEngine();
  35807. var subMeshes = new Array();
  35808. var currentIndex = 0;
  35809. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35810. var mesh = _a[_i];
  35811. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35812. }
  35813. var checkReady = function () {
  35814. if (!_this._scene || !_this._scene.getEngine()) {
  35815. return;
  35816. }
  35817. var subMesh = subMeshes[currentIndex];
  35818. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35819. currentIndex++;
  35820. if (currentIndex >= subMeshes.length) {
  35821. if (onCompiled) {
  35822. onCompiled(_this);
  35823. }
  35824. return;
  35825. }
  35826. }
  35827. setTimeout(checkReady, 16);
  35828. };
  35829. if (subMeshes.length > 0) {
  35830. checkReady();
  35831. }
  35832. };
  35833. /**
  35834. * Boolean : true when the ShadowGenerator is finally computed.
  35835. */
  35836. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35837. var defines = [];
  35838. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35839. defines.push("#define FLOAT");
  35840. }
  35841. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35842. defines.push("#define ESM");
  35843. }
  35844. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35845. var mesh = subMesh.getMesh();
  35846. var material = subMesh.getMaterial();
  35847. // Alpha test
  35848. if (material && material.needAlphaTesting()) {
  35849. var alphaTexture = material.getAlphaTestTexture();
  35850. if (alphaTexture) {
  35851. defines.push("#define ALPHATEST");
  35852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35853. attribs.push(BABYLON.VertexBuffer.UVKind);
  35854. defines.push("#define UV1");
  35855. }
  35856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35857. if (alphaTexture.coordinatesIndex === 1) {
  35858. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35859. defines.push("#define UV2");
  35860. }
  35861. }
  35862. }
  35863. }
  35864. // Bones
  35865. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35866. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35867. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35868. if (mesh.numBoneInfluencers > 4) {
  35869. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35870. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35871. }
  35872. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35873. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35874. }
  35875. else {
  35876. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35877. }
  35878. // Instances
  35879. if (useInstances) {
  35880. defines.push("#define INSTANCES");
  35881. attribs.push("world0");
  35882. attribs.push("world1");
  35883. attribs.push("world2");
  35884. attribs.push("world3");
  35885. }
  35886. // Get correct effect
  35887. var join = defines.join("\n");
  35888. if (this._cachedDefines !== join) {
  35889. this._cachedDefines = join;
  35890. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  35891. }
  35892. return this._effect.isReady();
  35893. };
  35894. /**
  35895. * This creates the defines related to the standard BJS materials.
  35896. */
  35897. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  35898. var scene = this._scene;
  35899. var light = this._light;
  35900. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35901. return;
  35902. }
  35903. defines["SHADOW" + lightIndex] = true;
  35904. if (this.usePoissonSampling) {
  35905. defines["SHADOWPCF" + lightIndex] = true;
  35906. }
  35907. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35908. defines["SHADOWESM" + lightIndex] = true;
  35909. }
  35910. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  35911. defines["SHADOWCLOSEESM" + lightIndex] = true;
  35912. }
  35913. if (light.needCube()) {
  35914. defines["SHADOWCUBE" + lightIndex] = true;
  35915. }
  35916. };
  35917. /**
  35918. * This binds shadow lights related to the standard BJS materials.
  35919. * It implies the unifroms available on the materials are the standard BJS ones.
  35920. */
  35921. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  35922. var light = this._light;
  35923. var scene = this._scene;
  35924. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35925. return;
  35926. }
  35927. if (!light.needCube()) {
  35928. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  35929. }
  35930. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  35931. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  35932. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  35933. };
  35934. // Methods
  35935. /**
  35936. * Returns a Matrix object : the updated transformation matrix.
  35937. */
  35938. ShadowGenerator.prototype.getTransformMatrix = function () {
  35939. var scene = this._scene;
  35940. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  35941. return this._transformMatrix;
  35942. }
  35943. this._currentRenderID = scene.getRenderId();
  35944. this._currentFaceIndexCache = this._currentFaceIndex;
  35945. var lightPosition = this._light.position;
  35946. if (this._light.computeTransformedInformation()) {
  35947. lightPosition = this._light.transformedPosition;
  35948. }
  35949. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  35950. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  35951. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  35952. }
  35953. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  35954. this._cachedPosition = lightPosition.clone();
  35955. this._cachedDirection = this._lightDirection.clone();
  35956. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  35957. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  35958. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  35959. }
  35960. return this._transformMatrix;
  35961. };
  35962. ShadowGenerator.prototype.recreateShadowMap = function () {
  35963. // Track render list.
  35964. var renderList = this._shadowMap.renderList;
  35965. // Clean up existing data.
  35966. this._disposeRTTandPostProcesses();
  35967. // Reinitializes.
  35968. this._initializeGenerator();
  35969. // Reaffect the filter to ensure a correct fallback if necessary.
  35970. this.filter = this.filter;
  35971. // Reaffect the filter.
  35972. this._applyFilterValues();
  35973. // Reaffect Render List.
  35974. this._shadowMap.renderList = renderList;
  35975. };
  35976. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  35977. if (this._shadowMap2) {
  35978. this._shadowMap2.dispose();
  35979. this._shadowMap2 = null;
  35980. }
  35981. if (this._downSamplePostprocess) {
  35982. this._downSamplePostprocess.dispose();
  35983. this._downSamplePostprocess = null;
  35984. }
  35985. if (this._boxBlurPostprocess) {
  35986. this._boxBlurPostprocess.dispose();
  35987. this._boxBlurPostprocess = null;
  35988. }
  35989. if (this._kernelBlurXPostprocess) {
  35990. this._kernelBlurXPostprocess.dispose();
  35991. this._kernelBlurXPostprocess = null;
  35992. }
  35993. if (this._kernelBlurYPostprocess) {
  35994. this._kernelBlurYPostprocess.dispose();
  35995. this._kernelBlurYPostprocess = null;
  35996. }
  35997. this._blurPostProcesses = null;
  35998. };
  35999. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  36000. if (this._shadowMap) {
  36001. this._shadowMap.dispose();
  36002. this._shadowMap = null;
  36003. }
  36004. this._disposeBlurPostProcesses();
  36005. };
  36006. /**
  36007. * Disposes the ShadowGenerator.
  36008. * Returns nothing.
  36009. */
  36010. ShadowGenerator.prototype.dispose = function () {
  36011. this._disposeRTTandPostProcesses();
  36012. this._light._shadowGenerator = null;
  36013. this._light._markMeshesAsLightDirty();
  36014. };
  36015. /**
  36016. * Serializes the ShadowGenerator and returns a serializationObject.
  36017. */
  36018. ShadowGenerator.prototype.serialize = function () {
  36019. var serializationObject = {};
  36020. var shadowMap = this.getShadowMap();
  36021. serializationObject.lightId = this._light.id;
  36022. serializationObject.mapSize = shadowMap.getRenderSize();
  36023. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  36024. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  36025. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36026. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36027. serializationObject.usePoissonSampling = this.usePoissonSampling;
  36028. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  36029. serializationObject.depthScale = this.depthScale;
  36030. serializationObject.darkness = this.getDarkness();
  36031. serializationObject.blurBoxOffset = this.blurBoxOffset;
  36032. serializationObject.blurKernel = this.blurKernel;
  36033. serializationObject.blurScale = this.blurScale;
  36034. serializationObject.useKernelBlur = this.useKernelBlur;
  36035. serializationObject.transparencyShadow = this._transparencyShadow;
  36036. serializationObject.renderList = [];
  36037. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  36038. var mesh = shadowMap.renderList[meshIndex];
  36039. serializationObject.renderList.push(mesh.id);
  36040. }
  36041. return serializationObject;
  36042. };
  36043. /**
  36044. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  36045. */
  36046. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  36047. //casting to point light, as light is missing the position attr and typescript complains.
  36048. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  36049. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  36050. var shadowMap = shadowGenerator.getShadowMap();
  36051. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  36052. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  36053. meshes.forEach(function (mesh) {
  36054. shadowMap.renderList.push(mesh);
  36055. });
  36056. }
  36057. if (parsedShadowGenerator.usePoissonSampling) {
  36058. shadowGenerator.usePoissonSampling = true;
  36059. }
  36060. else if (parsedShadowGenerator.useExponentialShadowMap) {
  36061. shadowGenerator.useExponentialShadowMap = true;
  36062. }
  36063. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36064. shadowGenerator.useBlurExponentialShadowMap = true;
  36065. }
  36066. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  36067. shadowGenerator.useCloseExponentialShadowMap = true;
  36068. }
  36069. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36070. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  36071. }
  36072. else if (parsedShadowGenerator.useVarianceShadowMap) {
  36073. shadowGenerator.useExponentialShadowMap = true;
  36074. }
  36075. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  36076. shadowGenerator.useBlurExponentialShadowMap = true;
  36077. }
  36078. if (parsedShadowGenerator.depthScale) {
  36079. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  36080. }
  36081. if (parsedShadowGenerator.blurScale) {
  36082. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  36083. }
  36084. if (parsedShadowGenerator.blurBoxOffset) {
  36085. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  36086. }
  36087. if (parsedShadowGenerator.useKernelBlur) {
  36088. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  36089. }
  36090. if (parsedShadowGenerator.blurKernel) {
  36091. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  36092. }
  36093. if (parsedShadowGenerator.bias !== undefined) {
  36094. shadowGenerator.bias = parsedShadowGenerator.bias;
  36095. }
  36096. if (parsedShadowGenerator.darkness) {
  36097. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  36098. }
  36099. if (parsedShadowGenerator.transparencyShadow) {
  36100. shadowGenerator.setTransparencyShadow(true);
  36101. }
  36102. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  36103. return shadowGenerator;
  36104. };
  36105. ShadowGenerator._FILTER_NONE = 0;
  36106. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  36107. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  36108. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  36109. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  36110. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  36111. return ShadowGenerator;
  36112. }());
  36113. BABYLON.ShadowGenerator = ShadowGenerator;
  36114. })(BABYLON || (BABYLON = {}));
  36115. //# sourceMappingURL=babylon.shadowGenerator.js.map
  36116. var BABYLON;
  36117. (function (BABYLON) {
  36118. var ShadowLight = (function (_super) {
  36119. __extends(ShadowLight, _super);
  36120. function ShadowLight() {
  36121. var _this = _super !== null && _super.apply(this, arguments) || this;
  36122. _this._needProjectionMatrixCompute = true;
  36123. return _this;
  36124. }
  36125. Object.defineProperty(ShadowLight.prototype, "direction", {
  36126. get: function () {
  36127. return this._direction;
  36128. },
  36129. set: function (value) {
  36130. this._direction = value;
  36131. },
  36132. enumerable: true,
  36133. configurable: true
  36134. });
  36135. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36136. get: function () {
  36137. return this._shadowMinZ;
  36138. },
  36139. set: function (value) {
  36140. this._shadowMinZ = value;
  36141. this.forceProjectionMatrixCompute();
  36142. },
  36143. enumerable: true,
  36144. configurable: true
  36145. });
  36146. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36147. get: function () {
  36148. return this._shadowMaxZ;
  36149. },
  36150. set: function (value) {
  36151. this._shadowMaxZ = value;
  36152. this.forceProjectionMatrixCompute();
  36153. },
  36154. enumerable: true,
  36155. configurable: true
  36156. });
  36157. /**
  36158. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36159. */
  36160. ShadowLight.prototype.computeTransformedInformation = function () {
  36161. if (this.parent && this.parent.getWorldMatrix) {
  36162. if (!this.transformedPosition) {
  36163. this.transformedPosition = BABYLON.Vector3.Zero();
  36164. }
  36165. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36166. // In case the direction is present.
  36167. if (this.direction) {
  36168. if (!this.transformedDirection) {
  36169. this.transformedDirection = BABYLON.Vector3.Zero();
  36170. }
  36171. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36172. }
  36173. return true;
  36174. }
  36175. return false;
  36176. };
  36177. /**
  36178. * Return the depth scale used for the shadow map.
  36179. */
  36180. ShadowLight.prototype.getDepthScale = function () {
  36181. return 50.0;
  36182. };
  36183. /**
  36184. * Returns the light direction (Vector3) for any passed face index.
  36185. */
  36186. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36187. return this.transformedDirection ? this.transformedDirection : this.direction;
  36188. };
  36189. /**
  36190. * Returns the DirectionalLight absolute position in the World.
  36191. */
  36192. ShadowLight.prototype.getAbsolutePosition = function () {
  36193. return this.transformedPosition ? this.transformedPosition : this.position;
  36194. };
  36195. /**
  36196. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36197. * Returns the updated DirectionalLight direction (Vector3).
  36198. */
  36199. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36200. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36201. return this.direction;
  36202. };
  36203. /**
  36204. * Returns the light rotation (Vector3).
  36205. */
  36206. ShadowLight.prototype.getRotation = function () {
  36207. this.direction.normalize();
  36208. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36209. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36210. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36211. };
  36212. /**
  36213. * Boolean : false by default.
  36214. */
  36215. ShadowLight.prototype.needCube = function () {
  36216. return false;
  36217. };
  36218. /**
  36219. * Specifies wether or not the projection matrix should be recomputed this frame.
  36220. */
  36221. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36222. return this._needProjectionMatrixCompute;
  36223. };
  36224. /**
  36225. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36226. */
  36227. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36228. this._needProjectionMatrixCompute = true;
  36229. };
  36230. /**
  36231. * Get the world matrix of the sahdow lights.
  36232. */
  36233. ShadowLight.prototype._getWorldMatrix = function () {
  36234. if (!this._worldMatrix) {
  36235. this._worldMatrix = BABYLON.Matrix.Identity();
  36236. }
  36237. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36238. return this._worldMatrix;
  36239. };
  36240. /**
  36241. * Gets the minZ used for shadow according to both the scene and the light.
  36242. * @param activeCamera
  36243. */
  36244. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36245. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36246. };
  36247. /**
  36248. * Gets the maxZ used for shadow according to both the scene and the light.
  36249. * @param activeCamera
  36250. */
  36251. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36252. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36253. };
  36254. /**
  36255. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36256. * Returns the light.
  36257. */
  36258. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36259. if (this.customProjectionMatrixBuilder) {
  36260. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36261. }
  36262. else {
  36263. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36264. }
  36265. return this;
  36266. };
  36267. __decorate([
  36268. BABYLON.serializeAsVector3()
  36269. ], ShadowLight.prototype, "position", void 0);
  36270. __decorate([
  36271. BABYLON.serializeAsVector3()
  36272. ], ShadowLight.prototype, "direction", null);
  36273. __decorate([
  36274. BABYLON.serialize()
  36275. ], ShadowLight.prototype, "shadowMinZ", null);
  36276. __decorate([
  36277. BABYLON.serialize()
  36278. ], ShadowLight.prototype, "shadowMaxZ", null);
  36279. return ShadowLight;
  36280. }(BABYLON.Light));
  36281. BABYLON.ShadowLight = ShadowLight;
  36282. })(BABYLON || (BABYLON = {}));
  36283. //# sourceMappingURL=babylon.shadowLight.js.map
  36284. var BABYLON;
  36285. (function (BABYLON) {
  36286. var PointLight = (function (_super) {
  36287. __extends(PointLight, _super);
  36288. /**
  36289. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36290. * A PointLight emits the light in every direction.
  36291. * It can cast shadows.
  36292. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36293. * ```javascript
  36294. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36295. * ```
  36296. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36297. */
  36298. function PointLight(name, position, scene) {
  36299. var _this = _super.call(this, name, scene) || this;
  36300. _this._shadowAngle = Math.PI / 2;
  36301. _this.position = position;
  36302. return _this;
  36303. }
  36304. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36305. /**
  36306. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36307. * This specifies what angle the shadow will use to be created.
  36308. *
  36309. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36310. */
  36311. get: function () {
  36312. return this._shadowAngle;
  36313. },
  36314. /**
  36315. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36316. * This specifies what angle the shadow will use to be created.
  36317. *
  36318. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36319. */
  36320. set: function (value) {
  36321. this._shadowAngle = value;
  36322. this.forceProjectionMatrixCompute();
  36323. },
  36324. enumerable: true,
  36325. configurable: true
  36326. });
  36327. Object.defineProperty(PointLight.prototype, "direction", {
  36328. get: function () {
  36329. return this._direction;
  36330. },
  36331. /**
  36332. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36333. */
  36334. set: function (value) {
  36335. var previousNeedCube = this.needCube();
  36336. this._direction = value;
  36337. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36338. this._shadowGenerator.recreateShadowMap();
  36339. }
  36340. },
  36341. enumerable: true,
  36342. configurable: true
  36343. });
  36344. /**
  36345. * Returns the string "PointLight"
  36346. */
  36347. PointLight.prototype.getClassName = function () {
  36348. return "PointLight";
  36349. };
  36350. /**
  36351. * Returns the integer 0.
  36352. */
  36353. PointLight.prototype.getTypeID = function () {
  36354. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36355. };
  36356. /**
  36357. * Specifies wether or not the shadowmap should be a cube texture.
  36358. */
  36359. PointLight.prototype.needCube = function () {
  36360. return !this.direction;
  36361. };
  36362. /**
  36363. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36364. */
  36365. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36366. if (this.direction) {
  36367. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36368. }
  36369. else {
  36370. switch (faceIndex) {
  36371. case 0:
  36372. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36373. case 1:
  36374. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36375. case 2:
  36376. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36377. case 3:
  36378. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36379. case 4:
  36380. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36381. case 5:
  36382. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36383. }
  36384. }
  36385. return BABYLON.Vector3.Zero();
  36386. };
  36387. /**
  36388. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36389. * - fov = PI / 2
  36390. * - aspect ratio : 1.0
  36391. * - z-near and far equal to the active camera minZ and maxZ.
  36392. * Returns the PointLight.
  36393. */
  36394. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36395. var activeCamera = this.getScene().activeCamera;
  36396. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36397. };
  36398. PointLight.prototype._buildUniformLayout = function () {
  36399. this._uniformBuffer.addUniform("vLightData", 4);
  36400. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36401. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36402. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36403. this._uniformBuffer.addUniform("depthValues", 2);
  36404. this._uniformBuffer.create();
  36405. };
  36406. /**
  36407. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36408. * Returns the PointLight.
  36409. */
  36410. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36411. if (this.computeTransformedInformation()) {
  36412. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36413. return this;
  36414. }
  36415. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36416. return this;
  36417. };
  36418. __decorate([
  36419. BABYLON.serialize()
  36420. ], PointLight.prototype, "shadowAngle", null);
  36421. return PointLight;
  36422. }(BABYLON.ShadowLight));
  36423. BABYLON.PointLight = PointLight;
  36424. })(BABYLON || (BABYLON = {}));
  36425. //# sourceMappingURL=babylon.pointLight.js.map
  36426. /// <reference path="babylon.light.ts" />
  36427. var BABYLON;
  36428. (function (BABYLON) {
  36429. var DirectionalLight = (function (_super) {
  36430. __extends(DirectionalLight, _super);
  36431. /**
  36432. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36433. * The directional light is emitted from everywhere in the given direction.
  36434. * It can cast shawdows.
  36435. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36436. */
  36437. function DirectionalLight(name, direction, scene) {
  36438. var _this = _super.call(this, name, scene) || this;
  36439. _this._shadowFrustumSize = 0;
  36440. _this._shadowOrthoScale = 0.5;
  36441. _this.autoUpdateExtends = true;
  36442. // Cache
  36443. _this._orthoLeft = Number.MAX_VALUE;
  36444. _this._orthoRight = Number.MIN_VALUE;
  36445. _this._orthoTop = Number.MIN_VALUE;
  36446. _this._orthoBottom = Number.MAX_VALUE;
  36447. _this.position = direction.scale(-1.0);
  36448. _this.direction = direction;
  36449. return _this;
  36450. }
  36451. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36452. /**
  36453. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36454. */
  36455. get: function () {
  36456. return this._shadowFrustumSize;
  36457. },
  36458. /**
  36459. * Specifies a fix frustum size for the shadow generation.
  36460. */
  36461. set: function (value) {
  36462. this._shadowFrustumSize = value;
  36463. this.forceProjectionMatrixCompute();
  36464. },
  36465. enumerable: true,
  36466. configurable: true
  36467. });
  36468. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36469. get: function () {
  36470. return this._shadowOrthoScale;
  36471. },
  36472. set: function (value) {
  36473. this._shadowOrthoScale = value;
  36474. this.forceProjectionMatrixCompute();
  36475. },
  36476. enumerable: true,
  36477. configurable: true
  36478. });
  36479. /**
  36480. * Returns the string "DirectionalLight".
  36481. */
  36482. DirectionalLight.prototype.getClassName = function () {
  36483. return "DirectionalLight";
  36484. };
  36485. /**
  36486. * Returns the integer 1.
  36487. */
  36488. DirectionalLight.prototype.getTypeID = function () {
  36489. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36490. };
  36491. /**
  36492. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36493. * Returns the DirectionalLight Shadow projection matrix.
  36494. */
  36495. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36496. if (this.shadowFrustumSize > 0) {
  36497. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36498. }
  36499. else {
  36500. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36501. }
  36502. };
  36503. /**
  36504. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36505. * Returns the DirectionalLight Shadow projection matrix.
  36506. */
  36507. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36508. var activeCamera = this.getScene().activeCamera;
  36509. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36510. };
  36511. /**
  36512. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36513. * Returns the DirectionalLight Shadow projection matrix.
  36514. */
  36515. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36516. var activeCamera = this.getScene().activeCamera;
  36517. // Check extends
  36518. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36519. var tempVector3 = BABYLON.Vector3.Zero();
  36520. this._orthoLeft = Number.MAX_VALUE;
  36521. this._orthoRight = Number.MIN_VALUE;
  36522. this._orthoTop = Number.MIN_VALUE;
  36523. this._orthoBottom = Number.MAX_VALUE;
  36524. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36525. var mesh = renderList[meshIndex];
  36526. if (!mesh) {
  36527. continue;
  36528. }
  36529. var boundingInfo = mesh.getBoundingInfo();
  36530. if (!boundingInfo) {
  36531. continue;
  36532. }
  36533. var boundingBox = boundingInfo.boundingBox;
  36534. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36535. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36536. if (tempVector3.x < this._orthoLeft)
  36537. this._orthoLeft = tempVector3.x;
  36538. if (tempVector3.y < this._orthoBottom)
  36539. this._orthoBottom = tempVector3.y;
  36540. if (tempVector3.x > this._orthoRight)
  36541. this._orthoRight = tempVector3.x;
  36542. if (tempVector3.y > this._orthoTop)
  36543. this._orthoTop = tempVector3.y;
  36544. }
  36545. }
  36546. }
  36547. var xOffset = this._orthoRight - this._orthoLeft;
  36548. var yOffset = this._orthoTop - this._orthoBottom;
  36549. 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);
  36550. };
  36551. DirectionalLight.prototype._buildUniformLayout = function () {
  36552. this._uniformBuffer.addUniform("vLightData", 4);
  36553. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36554. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36555. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36556. this._uniformBuffer.addUniform("depthValues", 2);
  36557. this._uniformBuffer.create();
  36558. };
  36559. /**
  36560. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36561. * Returns the DirectionalLight.
  36562. */
  36563. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36564. if (this.computeTransformedInformation()) {
  36565. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36566. return this;
  36567. }
  36568. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36569. return this;
  36570. };
  36571. /**
  36572. * Gets the minZ used for shadow according to both the scene and the light.
  36573. *
  36574. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36575. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36576. * @param activeCamera
  36577. */
  36578. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36579. return 1;
  36580. };
  36581. /**
  36582. * Gets the maxZ used for shadow according to both the scene and the light.
  36583. *
  36584. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36585. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36586. * @param activeCamera
  36587. */
  36588. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36589. return 1;
  36590. };
  36591. __decorate([
  36592. BABYLON.serialize()
  36593. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36594. __decorate([
  36595. BABYLON.serialize()
  36596. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36597. __decorate([
  36598. BABYLON.serialize()
  36599. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36600. return DirectionalLight;
  36601. }(BABYLON.ShadowLight));
  36602. BABYLON.DirectionalLight = DirectionalLight;
  36603. })(BABYLON || (BABYLON = {}));
  36604. //# sourceMappingURL=babylon.directionalLight.js.map
  36605. var BABYLON;
  36606. (function (BABYLON) {
  36607. var SpotLight = (function (_super) {
  36608. __extends(SpotLight, _super);
  36609. /**
  36610. * Creates a SpotLight object in the scene with the passed parameters :
  36611. * - `position` (Vector3) is the initial SpotLight position,
  36612. * - `direction` (Vector3) is the initial SpotLight direction,
  36613. * - `angle` (float, in radians) is the spot light cone angle,
  36614. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36615. * A spot light is a simply light oriented cone.
  36616. * It can cast shadows.
  36617. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36618. */
  36619. function SpotLight(name, position, direction, angle, exponent, scene) {
  36620. var _this = _super.call(this, name, scene) || this;
  36621. _this.position = position;
  36622. _this.direction = direction;
  36623. _this.angle = angle;
  36624. _this.exponent = exponent;
  36625. return _this;
  36626. }
  36627. Object.defineProperty(SpotLight.prototype, "angle", {
  36628. get: function () {
  36629. return this._angle;
  36630. },
  36631. set: function (value) {
  36632. this._angle = value;
  36633. this.forceProjectionMatrixCompute();
  36634. },
  36635. enumerable: true,
  36636. configurable: true
  36637. });
  36638. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36639. get: function () {
  36640. return this._shadowAngleScale;
  36641. },
  36642. /**
  36643. * Allows scaling the angle of the light for shadow generation only.
  36644. */
  36645. set: function (value) {
  36646. this._shadowAngleScale = value;
  36647. this.forceProjectionMatrixCompute();
  36648. },
  36649. enumerable: true,
  36650. configurable: true
  36651. });
  36652. /**
  36653. * Returns the string "SpotLight".
  36654. */
  36655. SpotLight.prototype.getClassName = function () {
  36656. return "SpotLight";
  36657. };
  36658. /**
  36659. * Returns the integer 2.
  36660. */
  36661. SpotLight.prototype.getTypeID = function () {
  36662. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36663. };
  36664. /**
  36665. * 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.
  36666. * Returns the SpotLight.
  36667. */
  36668. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36669. var activeCamera = this.getScene().activeCamera;
  36670. this._shadowAngleScale = this._shadowAngleScale || 1;
  36671. var angle = this._shadowAngleScale * this._angle;
  36672. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36673. };
  36674. SpotLight.prototype._buildUniformLayout = function () {
  36675. this._uniformBuffer.addUniform("vLightData", 4);
  36676. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36677. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36678. this._uniformBuffer.addUniform("vLightDirection", 3);
  36679. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36680. this._uniformBuffer.addUniform("depthValues", 2);
  36681. this._uniformBuffer.create();
  36682. };
  36683. /**
  36684. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36685. * Return the SpotLight.
  36686. */
  36687. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36688. var normalizeDirection;
  36689. if (this.computeTransformedInformation()) {
  36690. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36691. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36692. }
  36693. else {
  36694. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36695. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36696. }
  36697. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36698. return this;
  36699. };
  36700. __decorate([
  36701. BABYLON.serialize()
  36702. ], SpotLight.prototype, "angle", null);
  36703. __decorate([
  36704. BABYLON.serialize()
  36705. /**
  36706. * Allows scaling the angle of the light for shadow generation only.
  36707. */
  36708. ], SpotLight.prototype, "shadowAngleScale", null);
  36709. __decorate([
  36710. BABYLON.serialize()
  36711. ], SpotLight.prototype, "exponent", void 0);
  36712. return SpotLight;
  36713. }(BABYLON.ShadowLight));
  36714. BABYLON.SpotLight = SpotLight;
  36715. })(BABYLON || (BABYLON = {}));
  36716. //# sourceMappingURL=babylon.spotLight.js.map
  36717. var BABYLON;
  36718. (function (BABYLON) {
  36719. var MultiMaterial = (function (_super) {
  36720. __extends(MultiMaterial, _super);
  36721. function MultiMaterial(name, scene) {
  36722. var _this = _super.call(this, name, scene, true) || this;
  36723. scene.multiMaterials.push(_this);
  36724. _this.subMaterials = new Array();
  36725. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36726. return _this;
  36727. }
  36728. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36729. get: function () {
  36730. return this._subMaterials;
  36731. },
  36732. set: function (value) {
  36733. this._subMaterials = value;
  36734. this._hookArray(value);
  36735. },
  36736. enumerable: true,
  36737. configurable: true
  36738. });
  36739. MultiMaterial.prototype._hookArray = function (array) {
  36740. var _this = this;
  36741. var oldPush = array.push;
  36742. array.push = function () {
  36743. var items = [];
  36744. for (var _i = 0; _i < arguments.length; _i++) {
  36745. items[_i] = arguments[_i];
  36746. }
  36747. var result = oldPush.apply(array, items);
  36748. _this._markAllSubMeshesAsTexturesDirty();
  36749. return result;
  36750. };
  36751. var oldSplice = array.splice;
  36752. array.splice = function (index, deleteCount) {
  36753. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36754. _this._markAllSubMeshesAsTexturesDirty();
  36755. return deleted;
  36756. };
  36757. };
  36758. // Properties
  36759. MultiMaterial.prototype.getSubMaterial = function (index) {
  36760. if (index < 0 || index >= this.subMaterials.length) {
  36761. return this.getScene().defaultMaterial;
  36762. }
  36763. return this.subMaterials[index];
  36764. };
  36765. MultiMaterial.prototype.getActiveTextures = function () {
  36766. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36767. var _a;
  36768. };
  36769. // Methods
  36770. MultiMaterial.prototype.getClassName = function () {
  36771. return "MultiMaterial";
  36772. };
  36773. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36774. for (var index = 0; index < this.subMaterials.length; index++) {
  36775. var subMaterial = this.subMaterials[index];
  36776. if (subMaterial) {
  36777. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36778. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36779. return false;
  36780. }
  36781. continue;
  36782. }
  36783. if (!this.subMaterials[index].isReady(mesh)) {
  36784. return false;
  36785. }
  36786. }
  36787. }
  36788. return true;
  36789. };
  36790. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36791. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36792. for (var index = 0; index < this.subMaterials.length; index++) {
  36793. var subMaterial = null;
  36794. if (cloneChildren) {
  36795. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36796. }
  36797. else {
  36798. subMaterial = this.subMaterials[index];
  36799. }
  36800. newMultiMaterial.subMaterials.push(subMaterial);
  36801. }
  36802. return newMultiMaterial;
  36803. };
  36804. MultiMaterial.prototype.serialize = function () {
  36805. var serializationObject = {};
  36806. serializationObject.name = this.name;
  36807. serializationObject.id = this.id;
  36808. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36809. serializationObject.materials = [];
  36810. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36811. var subMat = this.subMaterials[matIndex];
  36812. if (subMat) {
  36813. serializationObject.materials.push(subMat.id);
  36814. }
  36815. else {
  36816. serializationObject.materials.push(null);
  36817. }
  36818. }
  36819. return serializationObject;
  36820. };
  36821. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36822. var scene = this.getScene();
  36823. if (!scene) {
  36824. return;
  36825. }
  36826. var index = scene.multiMaterials.indexOf(this);
  36827. if (index >= 0) {
  36828. scene.multiMaterials.splice(index, 1);
  36829. }
  36830. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36831. };
  36832. return MultiMaterial;
  36833. }(BABYLON.Material));
  36834. BABYLON.MultiMaterial = MultiMaterial;
  36835. })(BABYLON || (BABYLON = {}));
  36836. //# sourceMappingURL=babylon.multiMaterial.js.map
  36837. var BABYLON;
  36838. (function (BABYLON) {
  36839. var PBRMaterialDefines = (function (_super) {
  36840. __extends(PBRMaterialDefines, _super);
  36841. function PBRMaterialDefines() {
  36842. var _this = _super.call(this) || this;
  36843. _this.PBR = true;
  36844. _this.MAINUV1 = false;
  36845. _this.MAINUV2 = false;
  36846. _this.UV1 = false;
  36847. _this.UV2 = false;
  36848. _this.ALBEDO = false;
  36849. _this.ALBEDODIRECTUV = 0;
  36850. _this.VERTEXCOLOR = false;
  36851. _this.AMBIENT = false;
  36852. _this.AMBIENTDIRECTUV = 0;
  36853. _this.AMBIENTINGRAYSCALE = false;
  36854. _this.OPACITY = false;
  36855. _this.VERTEXALPHA = false;
  36856. _this.OPACITYDIRECTUV = 0;
  36857. _this.OPACITYRGB = false;
  36858. _this.ALPHATEST = false;
  36859. _this.ALPHABLEND = false;
  36860. _this.ALPHAFROMALBEDO = false;
  36861. _this.ALPHATESTVALUE = 0.5;
  36862. _this.SPECULAROVERALPHA = false;
  36863. _this.RADIANCEOVERALPHA = false;
  36864. _this.ALPHAFRESNEL = false;
  36865. _this.PREMULTIPLYALPHA = false;
  36866. _this.EMISSIVE = false;
  36867. _this.EMISSIVEDIRECTUV = 0;
  36868. _this.REFLECTIVITY = false;
  36869. _this.REFLECTIVITYDIRECTUV = 0;
  36870. _this.SPECULARTERM = false;
  36871. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36872. _this.MICROSURFACEAUTOMATIC = false;
  36873. _this.LODBASEDMICROSFURACE = false;
  36874. _this.MICROSURFACEMAP = false;
  36875. _this.MICROSURFACEMAPDIRECTUV = 0;
  36876. _this.METALLICWORKFLOW = false;
  36877. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36878. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36879. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36880. _this.AOSTOREINMETALMAPRED = false;
  36881. _this.ENVIRONMENTBRDF = false;
  36882. _this.NORMAL = false;
  36883. _this.TANGENT = false;
  36884. _this.BUMP = false;
  36885. _this.BUMPDIRECTUV = 0;
  36886. _this.PARALLAX = false;
  36887. _this.PARALLAXOCCLUSION = false;
  36888. _this.NORMALXYSCALE = true;
  36889. _this.LIGHTMAP = false;
  36890. _this.LIGHTMAPDIRECTUV = 0;
  36891. _this.USELIGHTMAPASSHADOWMAP = false;
  36892. _this.REFLECTION = false;
  36893. _this.REFLECTIONMAP_3D = false;
  36894. _this.REFLECTIONMAP_SPHERICAL = false;
  36895. _this.REFLECTIONMAP_PLANAR = false;
  36896. _this.REFLECTIONMAP_CUBIC = false;
  36897. _this.REFLECTIONMAP_PROJECTION = false;
  36898. _this.REFLECTIONMAP_SKYBOX = false;
  36899. _this.REFLECTIONMAP_EXPLICIT = false;
  36900. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36901. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36902. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36903. _this.INVERTCUBICMAP = false;
  36904. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36905. _this.USESPHERICALINFRAGMENT = false;
  36906. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36907. _this.LODINREFLECTIONALPHA = false;
  36908. _this.GAMMAREFLECTION = false;
  36909. _this.REFRACTION = false;
  36910. _this.REFRACTIONMAP_3D = false;
  36911. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36912. _this.LODINREFRACTIONALPHA = false;
  36913. _this.GAMMAREFRACTION = false;
  36914. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36915. _this.INSTANCES = false;
  36916. _this.NUM_BONE_INFLUENCERS = 0;
  36917. _this.BonesPerMesh = 0;
  36918. _this.MORPHTARGETS = false;
  36919. _this.MORPHTARGETS_NORMAL = false;
  36920. _this.MORPHTARGETS_TANGENT = false;
  36921. _this.NUM_MORPH_INFLUENCERS = 0;
  36922. _this.IMAGEPROCESSING = false;
  36923. _this.VIGNETTE = false;
  36924. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36925. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36926. _this.TONEMAPPING = false;
  36927. _this.CONTRAST = false;
  36928. _this.COLORCURVES = false;
  36929. _this.COLORGRADING = false;
  36930. _this.SAMPLER3DGREENDEPTH = false;
  36931. _this.SAMPLER3DBGRMAP = false;
  36932. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36933. _this.EXPOSURE = false;
  36934. _this.USEPHYSICALLIGHTFALLOFF = false;
  36935. _this.TWOSIDEDLIGHTING = false;
  36936. _this.SHADOWFLOAT = false;
  36937. _this.USERIGHTHANDEDSYSTEM = false;
  36938. _this.CLIPPLANE = false;
  36939. _this.POINTSIZE = false;
  36940. _this.FOG = false;
  36941. _this.LOGARITHMICDEPTH = false;
  36942. _this.FORCENORMALFORWARD = false;
  36943. _this.rebuild();
  36944. return _this;
  36945. }
  36946. PBRMaterialDefines.prototype.reset = function () {
  36947. _super.prototype.reset.call(this);
  36948. this.ALPHATESTVALUE = 0.5;
  36949. this.PBR = true;
  36950. };
  36951. return PBRMaterialDefines;
  36952. }(BABYLON.MaterialDefines));
  36953. /**
  36954. * The Physically based material base class of BJS.
  36955. *
  36956. * This offers the main features of a standard PBR material.
  36957. * For more information, please refer to the documentation :
  36958. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36959. */
  36960. var PBRBaseMaterial = (function (_super) {
  36961. __extends(PBRBaseMaterial, _super);
  36962. /**
  36963. * Instantiates a new PBRMaterial instance.
  36964. *
  36965. * @param name The material name
  36966. * @param scene The scene the material will be use in.
  36967. */
  36968. function PBRBaseMaterial(name, scene) {
  36969. var _this = _super.call(this, name, scene) || this;
  36970. /**
  36971. * Intensity of the direct lights e.g. the four lights available in your scene.
  36972. * This impacts both the direct diffuse and specular highlights.
  36973. */
  36974. _this._directIntensity = 1.0;
  36975. /**
  36976. * Intensity of the emissive part of the material.
  36977. * This helps controlling the emissive effect without modifying the emissive color.
  36978. */
  36979. _this._emissiveIntensity = 1.0;
  36980. /**
  36981. * Intensity of the environment e.g. how much the environment will light the object
  36982. * either through harmonics for rough material or through the refelction for shiny ones.
  36983. */
  36984. _this._environmentIntensity = 1.0;
  36985. /**
  36986. * This is a special control allowing the reduction of the specular highlights coming from the
  36987. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36988. */
  36989. _this._specularIntensity = 1.0;
  36990. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36991. /**
  36992. * Debug Control allowing disabling the bump map on this material.
  36993. */
  36994. _this._disableBumpMap = false;
  36995. /**
  36996. * AKA Occlusion Texture Intensity in other nomenclature.
  36997. */
  36998. _this._ambientTextureStrength = 1.0;
  36999. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37000. /**
  37001. * AKA Diffuse Color in other nomenclature.
  37002. */
  37003. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37004. /**
  37005. * AKA Specular Color in other nomenclature.
  37006. */
  37007. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37008. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37009. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37010. /**
  37011. * AKA Glossiness in other nomenclature.
  37012. */
  37013. _this._microSurface = 0.9;
  37014. /**
  37015. * source material index of refraction (IOR)' / 'destination material IOR.
  37016. */
  37017. _this._indexOfRefraction = 0.66;
  37018. /**
  37019. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37020. */
  37021. _this._invertRefractionY = false;
  37022. /**
  37023. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37024. * Materials half opaque for instance using refraction could benefit from this control.
  37025. */
  37026. _this._linkRefractionWithTransparency = false;
  37027. _this._useLightmapAsShadowmap = false;
  37028. /**
  37029. * Specifies that the alpha is coming form the albedo channel alpha channel.
  37030. */
  37031. _this._useAlphaFromAlbedoTexture = false;
  37032. /**
  37033. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37034. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37035. */
  37036. _this._useSpecularOverAlpha = true;
  37037. /**
  37038. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37039. */
  37040. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37041. /**
  37042. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37043. */
  37044. _this._useRoughnessFromMetallicTextureAlpha = true;
  37045. /**
  37046. * Specifies if the metallic texture contains the roughness information in its green channel.
  37047. */
  37048. _this._useRoughnessFromMetallicTextureGreen = false;
  37049. /**
  37050. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37051. */
  37052. _this._useMetallnessFromMetallicTextureBlue = false;
  37053. /**
  37054. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37055. */
  37056. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37057. /**
  37058. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37059. */
  37060. _this._useAmbientInGrayScale = false;
  37061. /**
  37062. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37063. * The material will try to infer what glossiness each pixel should be.
  37064. */
  37065. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37066. /**
  37067. * BJS is using an harcoded light falloff based on a manually sets up range.
  37068. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37069. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37070. */
  37071. _this._usePhysicalLightFalloff = true;
  37072. /**
  37073. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37074. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37075. */
  37076. _this._useRadianceOverAlpha = true;
  37077. /**
  37078. * Allows using the bump map in parallax mode.
  37079. */
  37080. _this._useParallax = false;
  37081. /**
  37082. * Allows using the bump map in parallax occlusion mode.
  37083. */
  37084. _this._useParallaxOcclusion = false;
  37085. /**
  37086. * Controls the scale bias of the parallax mode.
  37087. */
  37088. _this._parallaxScaleBias = 0.05;
  37089. /**
  37090. * If sets to true, disables all the lights affecting the material.
  37091. */
  37092. _this._disableLighting = false;
  37093. /**
  37094. * Number of Simultaneous lights allowed on the material.
  37095. */
  37096. _this._maxSimultaneousLights = 4;
  37097. /**
  37098. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37099. */
  37100. _this._invertNormalMapX = false;
  37101. /**
  37102. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37103. */
  37104. _this._invertNormalMapY = false;
  37105. /**
  37106. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37107. */
  37108. _this._twoSidedLighting = false;
  37109. /**
  37110. * Defines the alpha limits in alpha test mode.
  37111. */
  37112. _this._alphaCutOff = 0.4;
  37113. /**
  37114. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37115. */
  37116. _this._forceAlphaTest = false;
  37117. /**
  37118. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  37119. * in your scene composition.
  37120. */
  37121. _this._preMultiplyAlpha = false;
  37122. /**
  37123. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37124. * And/Or occlude the blended part.
  37125. */
  37126. _this._useAlphaFresnel = false;
  37127. /**
  37128. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37129. * from cos thetav and roughness:
  37130. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37131. */
  37132. _this._environmentBRDFTexture = null;
  37133. /**
  37134. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37135. */
  37136. _this._forceIrradianceInFragment = false;
  37137. /**
  37138. * Force normal to face away from face.
  37139. * (Temporary internal fix to remove before 3.1)
  37140. */
  37141. _this._forceNormalForward = false;
  37142. _this._renderTargets = new BABYLON.SmartArray(16);
  37143. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37144. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37145. _this._tempColor = new BABYLON.Color3();
  37146. // Setup the default processing configuration to the scene.
  37147. _this._attachImageProcessingConfiguration(null);
  37148. _this.getRenderTargetTextures = function () {
  37149. _this._renderTargets.reset();
  37150. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37151. _this._renderTargets.push(_this._reflectionTexture);
  37152. }
  37153. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37154. _this._renderTargets.push(_this._refractionTexture);
  37155. }
  37156. return _this._renderTargets;
  37157. };
  37158. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37159. return _this;
  37160. }
  37161. /**
  37162. * Attaches a new image processing configuration to the PBR Material.
  37163. * @param configuration
  37164. */
  37165. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37166. var _this = this;
  37167. if (configuration === this._imageProcessingConfiguration) {
  37168. return;
  37169. }
  37170. // Detaches observer.
  37171. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37172. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37173. }
  37174. // Pick the scene configuration if needed.
  37175. if (!configuration) {
  37176. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37177. }
  37178. else {
  37179. this._imageProcessingConfiguration = configuration;
  37180. }
  37181. // Attaches observer.
  37182. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37183. _this._markAllSubMeshesAsImageProcessingDirty();
  37184. });
  37185. };
  37186. PBRBaseMaterial.prototype.getClassName = function () {
  37187. return "PBRBaseMaterial";
  37188. };
  37189. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37190. get: function () {
  37191. return this._useLogarithmicDepth;
  37192. },
  37193. set: function (value) {
  37194. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37195. },
  37196. enumerable: true,
  37197. configurable: true
  37198. });
  37199. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37200. if (this._linkRefractionWithTransparency) {
  37201. return false;
  37202. }
  37203. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37204. };
  37205. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37206. if (this._forceAlphaTest) {
  37207. return true;
  37208. }
  37209. if (this._linkRefractionWithTransparency) {
  37210. return false;
  37211. }
  37212. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  37213. };
  37214. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37215. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  37216. };
  37217. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37218. return this._albedoTexture;
  37219. };
  37220. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37221. if (this.isFrozen) {
  37222. if (this._wasPreviouslyReady) {
  37223. return true;
  37224. }
  37225. }
  37226. if (!subMesh._materialDefines) {
  37227. subMesh._materialDefines = new PBRMaterialDefines();
  37228. }
  37229. var scene = this.getScene();
  37230. var defines = subMesh._materialDefines;
  37231. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37232. if (defines._renderId === scene.getRenderId()) {
  37233. return true;
  37234. }
  37235. }
  37236. var engine = scene.getEngine();
  37237. // Lights
  37238. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37239. defines._needNormals = true;
  37240. // Textures
  37241. if (defines._areTexturesDirty) {
  37242. defines._needUVs = false;
  37243. if (scene.texturesEnabled) {
  37244. if (scene.getEngine().getCaps().textureLOD) {
  37245. defines.LODBASEDMICROSFURACE = true;
  37246. }
  37247. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37248. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37249. return false;
  37250. }
  37251. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37252. }
  37253. else {
  37254. defines.ALBEDO = false;
  37255. }
  37256. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37257. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37258. return false;
  37259. }
  37260. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37261. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37262. }
  37263. else {
  37264. defines.AMBIENT = false;
  37265. }
  37266. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37267. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37268. return false;
  37269. }
  37270. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37271. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37272. }
  37273. else {
  37274. defines.OPACITY = false;
  37275. }
  37276. var reflectionTexture = this._getReflectionTexture();
  37277. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37278. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37279. return false;
  37280. }
  37281. defines.REFLECTION = true;
  37282. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37283. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37284. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37285. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37286. defines.INVERTCUBICMAP = true;
  37287. }
  37288. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37289. switch (reflectionTexture.coordinatesMode) {
  37290. case BABYLON.Texture.CUBIC_MODE:
  37291. case BABYLON.Texture.INVCUBIC_MODE:
  37292. defines.REFLECTIONMAP_CUBIC = true;
  37293. break;
  37294. case BABYLON.Texture.EXPLICIT_MODE:
  37295. defines.REFLECTIONMAP_EXPLICIT = true;
  37296. break;
  37297. case BABYLON.Texture.PLANAR_MODE:
  37298. defines.REFLECTIONMAP_PLANAR = true;
  37299. break;
  37300. case BABYLON.Texture.PROJECTION_MODE:
  37301. defines.REFLECTIONMAP_PROJECTION = true;
  37302. break;
  37303. case BABYLON.Texture.SKYBOX_MODE:
  37304. defines.REFLECTIONMAP_SKYBOX = true;
  37305. break;
  37306. case BABYLON.Texture.SPHERICAL_MODE:
  37307. defines.REFLECTIONMAP_SPHERICAL = true;
  37308. break;
  37309. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37310. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37311. break;
  37312. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37313. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37314. break;
  37315. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37316. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37317. break;
  37318. }
  37319. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37320. if (reflectionTexture.sphericalPolynomial) {
  37321. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37322. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37323. defines.USESPHERICALINFRAGMENT = true;
  37324. }
  37325. }
  37326. }
  37327. }
  37328. else {
  37329. defines.REFLECTION = false;
  37330. defines.REFLECTIONMAP_3D = false;
  37331. defines.REFLECTIONMAP_SPHERICAL = false;
  37332. defines.REFLECTIONMAP_PLANAR = false;
  37333. defines.REFLECTIONMAP_CUBIC = false;
  37334. defines.REFLECTIONMAP_PROJECTION = false;
  37335. defines.REFLECTIONMAP_SKYBOX = false;
  37336. defines.REFLECTIONMAP_EXPLICIT = false;
  37337. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37338. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37339. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37340. defines.INVERTCUBICMAP = false;
  37341. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37342. defines.USESPHERICALINFRAGMENT = false;
  37343. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37344. defines.LODINREFLECTIONALPHA = false;
  37345. defines.GAMMAREFLECTION = false;
  37346. }
  37347. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37348. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37349. return false;
  37350. }
  37351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37352. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37353. }
  37354. else {
  37355. defines.LIGHTMAP = false;
  37356. }
  37357. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37358. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37359. return false;
  37360. }
  37361. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37362. }
  37363. else {
  37364. defines.EMISSIVE = false;
  37365. }
  37366. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37367. if (this._metallicTexture) {
  37368. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37369. return false;
  37370. }
  37371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37372. defines.METALLICWORKFLOW = true;
  37373. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37374. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37375. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37376. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37377. }
  37378. else if (this._reflectivityTexture) {
  37379. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37380. return false;
  37381. }
  37382. defines.METALLICWORKFLOW = false;
  37383. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37384. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37385. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37386. }
  37387. else {
  37388. defines.METALLICWORKFLOW = false;
  37389. defines.REFLECTIVITY = false;
  37390. }
  37391. if (this._microSurfaceTexture) {
  37392. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37393. return false;
  37394. }
  37395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37396. }
  37397. else {
  37398. defines.MICROSURFACEMAP = false;
  37399. }
  37400. }
  37401. else {
  37402. defines.REFLECTIVITY = false;
  37403. defines.MICROSURFACEMAP = false;
  37404. }
  37405. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37406. // Bump texure can not be none blocking.
  37407. if (!this._bumpTexture.isReady()) {
  37408. return false;
  37409. }
  37410. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37411. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37412. defines.PARALLAX = true;
  37413. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37414. }
  37415. else {
  37416. defines.PARALLAX = false;
  37417. }
  37418. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  37419. }
  37420. else {
  37421. defines.BUMP = false;
  37422. }
  37423. var refractionTexture = this._getRefractionTexture();
  37424. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37425. if (!refractionTexture.isReadyOrNotBlocking()) {
  37426. return false;
  37427. }
  37428. defines.REFRACTION = true;
  37429. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37430. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37431. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  37432. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37433. if (this._linkRefractionWithTransparency) {
  37434. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37435. }
  37436. }
  37437. else {
  37438. defines.REFRACTION = false;
  37439. }
  37440. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37441. // This is blocking.
  37442. if (!this._environmentBRDFTexture.isReady()) {
  37443. return false;
  37444. }
  37445. defines.ENVIRONMENTBRDF = true;
  37446. }
  37447. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37448. defines.ALPHAFROMALBEDO = true;
  37449. }
  37450. }
  37451. if (this._useSpecularOverAlpha) {
  37452. defines.SPECULAROVERALPHA = true;
  37453. }
  37454. if (this._usePhysicalLightFalloff) {
  37455. defines.USEPHYSICALLIGHTFALLOFF = true;
  37456. }
  37457. if (this._useRadianceOverAlpha) {
  37458. defines.RADIANCEOVERALPHA = true;
  37459. }
  37460. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37461. defines.METALLICWORKFLOW = true;
  37462. }
  37463. if (!this.backFaceCulling && this._twoSidedLighting) {
  37464. defines.TWOSIDEDLIGHTING = true;
  37465. }
  37466. defines.ALPHATESTVALUE = this._alphaCutOff;
  37467. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  37468. defines.ALPHABLEND = this.needAlphaBlending();
  37469. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  37470. }
  37471. if (defines._areImageProcessingDirty) {
  37472. if (!this._imageProcessingConfiguration.isReady()) {
  37473. return false;
  37474. }
  37475. this._imageProcessingConfiguration.prepareDefines(defines);
  37476. }
  37477. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37478. // Misc.
  37479. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37480. // Values that need to be evaluated on every frame
  37481. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  37482. // Attribs
  37483. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  37484. if (mesh) {
  37485. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37486. mesh.createNormals(true);
  37487. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  37488. }
  37489. }
  37490. }
  37491. // Get correct effect
  37492. if (defines.isDirty) {
  37493. defines.markAsProcessed();
  37494. scene.resetCachedMaterial();
  37495. // Fallbacks
  37496. var fallbacks = new BABYLON.EffectFallbacks();
  37497. if (defines.ENVIRONMENTBRDF) {
  37498. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  37499. }
  37500. if (defines.REFLECTION) {
  37501. fallbacks.addFallback(0, "REFLECTION");
  37502. }
  37503. if (defines.REFRACTION) {
  37504. fallbacks.addFallback(0, "REFRACTION");
  37505. }
  37506. if (defines.REFLECTIVITY) {
  37507. fallbacks.addFallback(0, "REFLECTIVITY");
  37508. }
  37509. if (defines.BUMP) {
  37510. fallbacks.addFallback(0, "BUMP");
  37511. }
  37512. if (defines.PARALLAX) {
  37513. fallbacks.addFallback(1, "PARALLAX");
  37514. }
  37515. if (defines.PARALLAXOCCLUSION) {
  37516. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37517. }
  37518. if (defines.SPECULAROVERALPHA) {
  37519. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37520. }
  37521. if (defines.FOG) {
  37522. fallbacks.addFallback(1, "FOG");
  37523. }
  37524. if (defines.POINTSIZE) {
  37525. fallbacks.addFallback(0, "POINTSIZE");
  37526. }
  37527. if (defines.LOGARITHMICDEPTH) {
  37528. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37529. }
  37530. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37531. if (defines.SPECULARTERM) {
  37532. fallbacks.addFallback(0, "SPECULARTERM");
  37533. }
  37534. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37535. fallbacks.addCPUSkinningFallback(0, mesh);
  37536. }
  37537. //Attributes
  37538. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37539. if (defines.NORMAL) {
  37540. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37541. }
  37542. if (defines.TANGENT) {
  37543. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37544. }
  37545. if (defines.UV1) {
  37546. attribs.push(BABYLON.VertexBuffer.UVKind);
  37547. }
  37548. if (defines.UV2) {
  37549. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37550. }
  37551. if (defines.VERTEXCOLOR) {
  37552. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37553. }
  37554. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37555. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37556. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37557. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37558. "vFogInfos", "vFogColor", "pointSize",
  37559. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37560. "mBones",
  37561. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37562. "vLightingIntensity",
  37563. "logarithmicDepthConstant",
  37564. "vSphericalX", "vSphericalY", "vSphericalZ",
  37565. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37566. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37567. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37568. "vNormalReoderParams"
  37569. ];
  37570. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37571. "bumpSampler", "lightmapSampler", "opacitySampler",
  37572. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37573. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37574. "microSurfaceSampler", "environmentBrdfSampler"];
  37575. var uniformBuffers = ["Material", "Scene"];
  37576. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37577. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37578. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37579. uniformsNames: uniforms,
  37580. uniformBuffersNames: uniformBuffers,
  37581. samplers: samplers,
  37582. defines: defines,
  37583. maxSimultaneousLights: this._maxSimultaneousLights
  37584. });
  37585. var onCompiled = function (effect) {
  37586. if (this.onCompiled) {
  37587. this.onCompiled(effect);
  37588. }
  37589. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37590. }.bind(this);
  37591. var join = defines.toString();
  37592. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37593. attributes: attribs,
  37594. uniformsNames: uniforms,
  37595. uniformBuffersNames: uniformBuffers,
  37596. samplers: samplers,
  37597. defines: join,
  37598. fallbacks: fallbacks,
  37599. onCompiled: onCompiled,
  37600. onError: this.onError,
  37601. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37602. }, engine), defines);
  37603. this.buildUniformLayout();
  37604. }
  37605. if (!subMesh.effect.isReady()) {
  37606. return false;
  37607. }
  37608. defines._renderId = scene.getRenderId();
  37609. this._wasPreviouslyReady = true;
  37610. return true;
  37611. };
  37612. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37613. // Order is important !
  37614. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37615. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37616. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37617. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37618. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37619. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37620. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37621. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37622. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37623. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37624. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37625. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37626. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37627. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37628. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37629. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37630. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37631. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37632. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  37633. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37634. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37635. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37636. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37637. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37638. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37639. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37640. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37641. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37642. this._uniformBuffer.addUniform("pointSize", 1);
  37643. this._uniformBuffer.create();
  37644. };
  37645. PBRBaseMaterial.prototype.unbind = function () {
  37646. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37647. this._uniformBuffer.setTexture("reflectionSampler", null);
  37648. }
  37649. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37650. this._uniformBuffer.setTexture("refractionSampler", null);
  37651. }
  37652. _super.prototype.unbind.call(this);
  37653. };
  37654. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37655. this._activeEffect.setMatrix("world", world);
  37656. };
  37657. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37658. var scene = this.getScene();
  37659. var defines = subMesh._materialDefines;
  37660. if (!defines) {
  37661. return;
  37662. }
  37663. var effect = subMesh.effect;
  37664. this._activeEffect = effect;
  37665. // Matrices
  37666. this.bindOnlyWorldMatrix(world);
  37667. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37668. // Bones
  37669. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37670. if (mustRebind) {
  37671. this._uniformBuffer.bindToEffect(effect, "Material");
  37672. this.bindViewProjection(effect);
  37673. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37674. // Texture uniforms
  37675. if (scene.texturesEnabled) {
  37676. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37677. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37678. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37679. }
  37680. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37681. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37682. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37683. }
  37684. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37685. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37686. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37687. }
  37688. var reflectionTexture = this._getReflectionTexture();
  37689. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37690. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37691. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37692. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37693. var polynomials = reflectionTexture.sphericalPolynomial;
  37694. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37695. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37696. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37697. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37698. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37699. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37700. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37701. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37702. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37703. }
  37704. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37705. }
  37706. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37707. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37708. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37709. }
  37710. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37711. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37712. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37713. }
  37714. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37715. if (this._metallicTexture) {
  37716. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37717. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37718. }
  37719. else if (this._reflectivityTexture) {
  37720. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37721. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37722. }
  37723. if (this._microSurfaceTexture) {
  37724. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37725. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37726. }
  37727. }
  37728. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37729. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37730. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37731. if (scene._mirroredCameraPosition) {
  37732. 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);
  37733. }
  37734. else {
  37735. 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);
  37736. }
  37737. }
  37738. var refractionTexture = this._getRefractionTexture();
  37739. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37740. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37741. var depth = 1.0;
  37742. if (!refractionTexture.isCube) {
  37743. if (refractionTexture.depth) {
  37744. depth = refractionTexture.depth;
  37745. }
  37746. }
  37747. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37748. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37749. }
  37750. }
  37751. // Point size
  37752. if (this.pointsCloud) {
  37753. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37754. }
  37755. // Colors
  37756. if (defines.METALLICWORKFLOW) {
  37757. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37758. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37759. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37760. }
  37761. else {
  37762. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37763. }
  37764. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37765. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37766. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37767. // Misc
  37768. this._lightingInfos.x = this._directIntensity;
  37769. this._lightingInfos.y = this._emissiveIntensity;
  37770. this._lightingInfos.z = this._environmentIntensity;
  37771. this._lightingInfos.w = this._specularIntensity;
  37772. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37773. }
  37774. // Textures
  37775. if (scene.texturesEnabled) {
  37776. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37777. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37778. }
  37779. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37780. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37781. }
  37782. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37783. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37784. }
  37785. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37786. if (defines.LODBASEDMICROSFURACE) {
  37787. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37788. }
  37789. else {
  37790. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37791. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37792. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37793. }
  37794. }
  37795. if (defines.ENVIRONMENTBRDF) {
  37796. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37797. }
  37798. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37799. if (defines.LODBASEDMICROSFURACE) {
  37800. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37801. }
  37802. else {
  37803. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37804. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37805. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37806. }
  37807. }
  37808. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37809. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37810. }
  37811. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37812. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37813. }
  37814. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37815. if (this._metallicTexture) {
  37816. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37817. }
  37818. else if (this._reflectivityTexture) {
  37819. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37820. }
  37821. if (this._microSurfaceTexture) {
  37822. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37823. }
  37824. }
  37825. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37826. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37827. }
  37828. }
  37829. // Clip plane
  37830. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37831. // Colors
  37832. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37833. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37834. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37835. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37836. }
  37837. if (mustRebind || !this.isFrozen) {
  37838. // Lights
  37839. if (scene.lightsEnabled && !this._disableLighting) {
  37840. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37841. }
  37842. // View
  37843. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37844. this.bindView(effect);
  37845. }
  37846. // Fog
  37847. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37848. // Morph targets
  37849. if (defines.NUM_MORPH_INFLUENCERS) {
  37850. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37851. }
  37852. // image processing
  37853. this._imageProcessingConfiguration.bind(this._activeEffect);
  37854. // Log. depth
  37855. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37856. }
  37857. this._uniformBuffer.update();
  37858. this._afterBind(mesh);
  37859. scene = null;
  37860. };
  37861. PBRBaseMaterial.prototype.getAnimatables = function () {
  37862. var results = [];
  37863. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37864. results.push(this._albedoTexture);
  37865. }
  37866. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37867. results.push(this._ambientTexture);
  37868. }
  37869. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37870. results.push(this._opacityTexture);
  37871. }
  37872. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37873. results.push(this._reflectionTexture);
  37874. }
  37875. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37876. results.push(this._emissiveTexture);
  37877. }
  37878. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37879. results.push(this._metallicTexture);
  37880. }
  37881. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37882. results.push(this._reflectivityTexture);
  37883. }
  37884. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37885. results.push(this._bumpTexture);
  37886. }
  37887. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37888. results.push(this._lightmapTexture);
  37889. }
  37890. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37891. results.push(this._refractionTexture);
  37892. }
  37893. return results;
  37894. };
  37895. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37896. if (this._reflectionTexture) {
  37897. return this._reflectionTexture;
  37898. }
  37899. return this.getScene().environmentTexture;
  37900. };
  37901. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37902. if (this._refractionTexture) {
  37903. return this._refractionTexture;
  37904. }
  37905. if (this._linkRefractionWithTransparency) {
  37906. return this.getScene().environmentTexture;
  37907. }
  37908. return null;
  37909. };
  37910. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37911. if (forceDisposeTextures) {
  37912. if (this._albedoTexture) {
  37913. this._albedoTexture.dispose();
  37914. }
  37915. if (this._ambientTexture) {
  37916. this._ambientTexture.dispose();
  37917. }
  37918. if (this._opacityTexture) {
  37919. this._opacityTexture.dispose();
  37920. }
  37921. if (this._reflectionTexture) {
  37922. this._reflectionTexture.dispose();
  37923. }
  37924. if (this._environmentBRDFTexture) {
  37925. this._environmentBRDFTexture.dispose();
  37926. }
  37927. if (this._emissiveTexture) {
  37928. this._emissiveTexture.dispose();
  37929. }
  37930. if (this._metallicTexture) {
  37931. this._metallicTexture.dispose();
  37932. }
  37933. if (this._reflectivityTexture) {
  37934. this._reflectivityTexture.dispose();
  37935. }
  37936. if (this._bumpTexture) {
  37937. this._bumpTexture.dispose();
  37938. }
  37939. if (this._lightmapTexture) {
  37940. this._lightmapTexture.dispose();
  37941. }
  37942. if (this._refractionTexture) {
  37943. this._refractionTexture.dispose();
  37944. }
  37945. }
  37946. this._renderTargets.dispose();
  37947. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37948. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37949. }
  37950. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37951. };
  37952. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37953. __decorate([
  37954. BABYLON.serializeAsImageProcessingConfiguration()
  37955. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37956. __decorate([
  37957. BABYLON.serialize()
  37958. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37959. return PBRBaseMaterial;
  37960. }(BABYLON.PushMaterial));
  37961. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37962. })(BABYLON || (BABYLON = {}));
  37963. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37964. var BABYLON;
  37965. (function (BABYLON) {
  37966. var Internals;
  37967. (function (Internals) {
  37968. /**
  37969. * The Physically based simple base material of BJS.
  37970. *
  37971. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37972. * It is used as the base class for both the specGloss and metalRough conventions.
  37973. */
  37974. var PBRBaseSimpleMaterial = (function (_super) {
  37975. __extends(PBRBaseSimpleMaterial, _super);
  37976. /**
  37977. * Instantiates a new PBRMaterial instance.
  37978. *
  37979. * @param name The material name
  37980. * @param scene The scene the material will be use in.
  37981. */
  37982. function PBRBaseSimpleMaterial(name, scene) {
  37983. var _this = _super.call(this, name, scene) || this;
  37984. /**
  37985. * Number of Simultaneous lights allowed on the material.
  37986. */
  37987. _this.maxSimultaneousLights = 4;
  37988. /**
  37989. * If sets to true, disables all the lights affecting the material.
  37990. */
  37991. _this.disableLighting = false;
  37992. /**
  37993. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37994. */
  37995. _this.invertNormalMapX = false;
  37996. /**
  37997. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37998. */
  37999. _this.invertNormalMapY = false;
  38000. /**
  38001. * Emissivie color used to self-illuminate the model.
  38002. */
  38003. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38004. /**
  38005. * Occlusion Channel Strenght.
  38006. */
  38007. _this.occlusionStrength = 1.0;
  38008. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38009. _this._useAmbientInGrayScale = true;
  38010. return _this;
  38011. }
  38012. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  38013. /**
  38014. * Gets the current transparency mode.
  38015. */
  38016. get: function () {
  38017. return this._transparencyMode;
  38018. },
  38019. /**
  38020. * Sets the transparency mode of the material.
  38021. */
  38022. set: function (value) {
  38023. if (this._transparencyMode === value) {
  38024. return;
  38025. }
  38026. this._transparencyMode = value;
  38027. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  38028. this._forceAlphaTest = true;
  38029. }
  38030. else {
  38031. this._forceAlphaTest = false;
  38032. }
  38033. this._markAllSubMeshesAsTexturesDirty();
  38034. },
  38035. enumerable: true,
  38036. configurable: true
  38037. });
  38038. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38039. /**
  38040. * Gets the current double sided mode.
  38041. */
  38042. get: function () {
  38043. return this._twoSidedLighting;
  38044. },
  38045. /**
  38046. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38047. */
  38048. set: function (value) {
  38049. if (this._twoSidedLighting === value) {
  38050. return;
  38051. }
  38052. this._twoSidedLighting = value;
  38053. this.backFaceCulling = !value;
  38054. this._markAllSubMeshesAsTexturesDirty();
  38055. },
  38056. enumerable: true,
  38057. configurable: true
  38058. });
  38059. /**
  38060. * Specifies wether or not the alpha value of the albedo texture should be used.
  38061. */
  38062. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38063. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38064. };
  38065. /**
  38066. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  38067. */
  38068. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  38069. if (this._linkRefractionWithTransparency) {
  38070. return false;
  38071. }
  38072. return (this.alpha < 1.0) ||
  38073. (this._shouldUseAlphaFromAlbedoTexture() &&
  38074. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  38075. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  38076. };
  38077. /**
  38078. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  38079. */
  38080. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  38081. if (this._linkRefractionWithTransparency) {
  38082. return false;
  38083. }
  38084. return this._shouldUseAlphaFromAlbedoTexture() &&
  38085. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  38086. };
  38087. /**
  38088. * Return the active textures of the material.
  38089. */
  38090. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38091. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38092. if (this.environmentTexture) {
  38093. activeTextures.push(this.environmentTexture);
  38094. }
  38095. if (this.normalTexture) {
  38096. activeTextures.push(this.normalTexture);
  38097. }
  38098. if (this.emissiveTexture) {
  38099. activeTextures.push(this.emissiveTexture);
  38100. }
  38101. if (this.occlusionTexture) {
  38102. activeTextures.push(this.occlusionTexture);
  38103. }
  38104. return activeTextures;
  38105. };
  38106. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38107. return "PBRBaseSimpleMaterial";
  38108. };
  38109. __decorate([
  38110. BABYLON.serialize(),
  38111. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38112. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38113. __decorate([
  38114. BABYLON.serialize(),
  38115. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38116. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38117. __decorate([
  38118. BABYLON.serializeAsTexture(),
  38119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38120. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38121. __decorate([
  38122. BABYLON.serialize(),
  38123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38124. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38125. __decorate([
  38126. BABYLON.serialize(),
  38127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38128. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38129. __decorate([
  38130. BABYLON.serializeAsTexture(),
  38131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38132. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38133. __decorate([
  38134. BABYLON.serializeAsColor3("emissive"),
  38135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38136. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38137. __decorate([
  38138. BABYLON.serializeAsTexture(),
  38139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38140. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38141. __decorate([
  38142. BABYLON.serialize(),
  38143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38144. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38145. __decorate([
  38146. BABYLON.serializeAsTexture(),
  38147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38148. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38149. __decorate([
  38150. BABYLON.serialize(),
  38151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38152. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38153. __decorate([
  38154. BABYLON.serialize()
  38155. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  38156. __decorate([
  38157. BABYLON.serialize()
  38158. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38159. return PBRBaseSimpleMaterial;
  38160. }(BABYLON.PBRBaseMaterial));
  38161. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38162. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38163. })(BABYLON || (BABYLON = {}));
  38164. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38165. var BABYLON;
  38166. (function (BABYLON) {
  38167. /**
  38168. * The Physically based material of BJS.
  38169. *
  38170. * This offers the main features of a standard PBR material.
  38171. * For more information, please refer to the documentation :
  38172. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38173. */
  38174. var PBRMaterial = (function (_super) {
  38175. __extends(PBRMaterial, _super);
  38176. /**
  38177. * Instantiates a new PBRMaterial instance.
  38178. *
  38179. * @param name The material name
  38180. * @param scene The scene the material will be use in.
  38181. */
  38182. function PBRMaterial(name, scene) {
  38183. var _this = _super.call(this, name, scene) || this;
  38184. /**
  38185. * Intensity of the direct lights e.g. the four lights available in your scene.
  38186. * This impacts both the direct diffuse and specular highlights.
  38187. */
  38188. _this.directIntensity = 1.0;
  38189. /**
  38190. * Intensity of the emissive part of the material.
  38191. * This helps controlling the emissive effect without modifying the emissive color.
  38192. */
  38193. _this.emissiveIntensity = 1.0;
  38194. /**
  38195. * Intensity of the environment e.g. how much the environment will light the object
  38196. * either through harmonics for rough material or through the refelction for shiny ones.
  38197. */
  38198. _this.environmentIntensity = 1.0;
  38199. /**
  38200. * This is a special control allowing the reduction of the specular highlights coming from the
  38201. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38202. */
  38203. _this.specularIntensity = 1.0;
  38204. /**
  38205. * Debug Control allowing disabling the bump map on this material.
  38206. */
  38207. _this.disableBumpMap = false;
  38208. /**
  38209. * AKA Occlusion Texture Intensity in other nomenclature.
  38210. */
  38211. _this.ambientTextureStrength = 1.0;
  38212. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38213. /**
  38214. * AKA Diffuse Color in other nomenclature.
  38215. */
  38216. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38217. /**
  38218. * AKA Specular Color in other nomenclature.
  38219. */
  38220. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38221. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38222. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38223. /**
  38224. * AKA Glossiness in other nomenclature.
  38225. */
  38226. _this.microSurface = 1.0;
  38227. /**
  38228. * source material index of refraction (IOR)' / 'destination material IOR.
  38229. */
  38230. _this.indexOfRefraction = 0.66;
  38231. /**
  38232. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38233. */
  38234. _this.invertRefractionY = false;
  38235. /**
  38236. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38237. * Materials half opaque for instance using refraction could benefit from this control.
  38238. */
  38239. _this.linkRefractionWithTransparency = false;
  38240. _this.useLightmapAsShadowmap = false;
  38241. /**
  38242. * Specifies that the alpha is coming form the albedo channel alpha channel.
  38243. */
  38244. _this.useAlphaFromAlbedoTexture = false;
  38245. /**
  38246. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38247. */
  38248. _this.forceAlphaTest = false;
  38249. /**
  38250. * Defines the alpha limits in alpha test mode.
  38251. */
  38252. _this.alphaCutOff = 0.4;
  38253. /**
  38254. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38255. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38256. */
  38257. _this.useSpecularOverAlpha = true;
  38258. /**
  38259. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38260. */
  38261. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38262. /**
  38263. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38264. */
  38265. _this.useRoughnessFromMetallicTextureAlpha = true;
  38266. /**
  38267. * Specifies if the metallic texture contains the roughness information in its green channel.
  38268. */
  38269. _this.useRoughnessFromMetallicTextureGreen = false;
  38270. /**
  38271. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38272. */
  38273. _this.useMetallnessFromMetallicTextureBlue = false;
  38274. /**
  38275. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38276. */
  38277. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38278. /**
  38279. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38280. */
  38281. _this.useAmbientInGrayScale = false;
  38282. /**
  38283. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38284. * The material will try to infer what glossiness each pixel should be.
  38285. */
  38286. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38287. /**
  38288. * BJS is using an harcoded light falloff based on a manually sets up range.
  38289. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38290. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38291. */
  38292. _this.usePhysicalLightFalloff = true;
  38293. /**
  38294. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38295. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38296. */
  38297. _this.useRadianceOverAlpha = true;
  38298. /**
  38299. * Allows using the bump map in parallax mode.
  38300. */
  38301. _this.useParallax = false;
  38302. /**
  38303. * Allows using the bump map in parallax occlusion mode.
  38304. */
  38305. _this.useParallaxOcclusion = false;
  38306. /**
  38307. * Controls the scale bias of the parallax mode.
  38308. */
  38309. _this.parallaxScaleBias = 0.05;
  38310. /**
  38311. * If sets to true, disables all the lights affecting the material.
  38312. */
  38313. _this.disableLighting = false;
  38314. /**
  38315. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38316. */
  38317. _this.forceIrradianceInFragment = false;
  38318. /**
  38319. * Number of Simultaneous lights allowed on the material.
  38320. */
  38321. _this.maxSimultaneousLights = 4;
  38322. /**
  38323. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38324. */
  38325. _this.invertNormalMapX = false;
  38326. /**
  38327. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38328. */
  38329. _this.invertNormalMapY = false;
  38330. /**
  38331. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38332. */
  38333. _this.twoSidedLighting = false;
  38334. /**
  38335. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  38336. * in your scene composition.
  38337. */
  38338. _this.preMultiplyAlpha = false;
  38339. /**
  38340. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38341. * And/Or occlude the blended part.
  38342. */
  38343. _this.useAlphaFresnel = false;
  38344. /**
  38345. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38346. * And/Or occlude the blended part.
  38347. */
  38348. _this.environmentBRDFTexture = null;
  38349. /**
  38350. * Force normal to face away from face.
  38351. * (Temporary internal fix to remove before 3.1)
  38352. */
  38353. _this.forceNormalForward = false;
  38354. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38355. return _this;
  38356. }
  38357. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38358. /**
  38359. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38360. */
  38361. get: function () {
  38362. return this._PBRMATERIAL_OPAQUE;
  38363. },
  38364. enumerable: true,
  38365. configurable: true
  38366. });
  38367. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38368. /**
  38369. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38370. */
  38371. get: function () {
  38372. return this._PBRMATERIAL_ALPHATEST;
  38373. },
  38374. enumerable: true,
  38375. configurable: true
  38376. });
  38377. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38378. /**
  38379. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38380. */
  38381. get: function () {
  38382. return this._PBRMATERIAL_ALPHABLEND;
  38383. },
  38384. enumerable: true,
  38385. configurable: true
  38386. });
  38387. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38388. /**
  38389. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38390. * They are also discarded below the alpha cutoff threshold to improve performances.
  38391. */
  38392. get: function () {
  38393. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38394. },
  38395. enumerable: true,
  38396. configurable: true
  38397. });
  38398. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38399. /**
  38400. * Gets the image processing configuration used either in this material.
  38401. */
  38402. get: function () {
  38403. return this._imageProcessingConfiguration;
  38404. },
  38405. /**
  38406. * Sets the Default image processing configuration used either in the this material.
  38407. *
  38408. * If sets to null, the scene one is in use.
  38409. */
  38410. set: function (value) {
  38411. this._attachImageProcessingConfiguration(value);
  38412. // Ensure the effect will be rebuilt.
  38413. this._markAllSubMeshesAsTexturesDirty();
  38414. },
  38415. enumerable: true,
  38416. configurable: true
  38417. });
  38418. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38419. /**
  38420. * Gets wether the color curves effect is enabled.
  38421. */
  38422. get: function () {
  38423. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38424. },
  38425. /**
  38426. * Sets wether the color curves effect is enabled.
  38427. */
  38428. set: function (value) {
  38429. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38430. },
  38431. enumerable: true,
  38432. configurable: true
  38433. });
  38434. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38435. /**
  38436. * Gets wether the color grading effect is enabled.
  38437. */
  38438. get: function () {
  38439. return this.imageProcessingConfiguration.colorGradingEnabled;
  38440. },
  38441. /**
  38442. * Gets wether the color grading effect is enabled.
  38443. */
  38444. set: function (value) {
  38445. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38451. /**
  38452. * Gets wether tonemapping is enabled or not.
  38453. */
  38454. get: function () {
  38455. return this._imageProcessingConfiguration.toneMappingEnabled;
  38456. },
  38457. /**
  38458. * Sets wether tonemapping is enabled or not
  38459. */
  38460. set: function (value) {
  38461. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38462. },
  38463. enumerable: true,
  38464. configurable: true
  38465. });
  38466. ;
  38467. ;
  38468. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38469. /**
  38470. * The camera exposure used on this material.
  38471. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38472. * This corresponds to a photographic exposure.
  38473. */
  38474. get: function () {
  38475. return this._imageProcessingConfiguration.exposure;
  38476. },
  38477. /**
  38478. * The camera exposure used on this material.
  38479. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38480. * This corresponds to a photographic exposure.
  38481. */
  38482. set: function (value) {
  38483. this._imageProcessingConfiguration.exposure = value;
  38484. },
  38485. enumerable: true,
  38486. configurable: true
  38487. });
  38488. ;
  38489. ;
  38490. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38491. /**
  38492. * Gets The camera contrast used on this material.
  38493. */
  38494. get: function () {
  38495. return this._imageProcessingConfiguration.contrast;
  38496. },
  38497. /**
  38498. * Sets The camera contrast used on this material.
  38499. */
  38500. set: function (value) {
  38501. this._imageProcessingConfiguration.contrast = value;
  38502. },
  38503. enumerable: true,
  38504. configurable: true
  38505. });
  38506. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38507. /**
  38508. * Gets the Color Grading 2D Lookup Texture.
  38509. */
  38510. get: function () {
  38511. return this._imageProcessingConfiguration.colorGradingTexture;
  38512. },
  38513. /**
  38514. * Sets the Color Grading 2D Lookup Texture.
  38515. */
  38516. set: function (value) {
  38517. this._imageProcessingConfiguration.colorGradingTexture = value;
  38518. },
  38519. enumerable: true,
  38520. configurable: true
  38521. });
  38522. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38523. /**
  38524. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38525. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38526. * 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;
  38527. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38528. */
  38529. get: function () {
  38530. return this._imageProcessingConfiguration.colorCurves;
  38531. },
  38532. /**
  38533. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38534. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38535. * 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;
  38536. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38537. */
  38538. set: function (value) {
  38539. this._imageProcessingConfiguration.colorCurves = value;
  38540. },
  38541. enumerable: true,
  38542. configurable: true
  38543. });
  38544. PBRMaterial.prototype.getClassName = function () {
  38545. return "PBRMaterial";
  38546. };
  38547. PBRMaterial.prototype.getActiveTextures = function () {
  38548. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38549. if (this._albedoTexture) {
  38550. activeTextures.push(this._albedoTexture);
  38551. }
  38552. if (this._ambientTexture) {
  38553. activeTextures.push(this._ambientTexture);
  38554. }
  38555. if (this._opacityTexture) {
  38556. activeTextures.push(this._opacityTexture);
  38557. }
  38558. if (this._reflectionTexture) {
  38559. activeTextures.push(this._reflectionTexture);
  38560. }
  38561. if (this._emissiveTexture) {
  38562. activeTextures.push(this._emissiveTexture);
  38563. }
  38564. if (this._reflectivityTexture) {
  38565. activeTextures.push(this._reflectivityTexture);
  38566. }
  38567. if (this._metallicTexture) {
  38568. activeTextures.push(this._metallicTexture);
  38569. }
  38570. if (this._microSurfaceTexture) {
  38571. activeTextures.push(this._microSurfaceTexture);
  38572. }
  38573. if (this._bumpTexture) {
  38574. activeTextures.push(this._bumpTexture);
  38575. }
  38576. if (this._lightmapTexture) {
  38577. activeTextures.push(this._lightmapTexture);
  38578. }
  38579. if (this._refractionTexture) {
  38580. activeTextures.push(this._refractionTexture);
  38581. }
  38582. return activeTextures;
  38583. };
  38584. PBRMaterial.prototype.hasTexture = function (texture) {
  38585. if (_super.prototype.hasTexture.call(this, texture)) {
  38586. return true;
  38587. }
  38588. if (this._albedoTexture === texture) {
  38589. return true;
  38590. }
  38591. if (this._ambientTexture === texture) {
  38592. return true;
  38593. }
  38594. if (this._opacityTexture === texture) {
  38595. return true;
  38596. }
  38597. if (this._reflectionTexture === texture) {
  38598. return true;
  38599. }
  38600. if (this._reflectivityTexture === texture) {
  38601. return true;
  38602. }
  38603. if (this._metallicTexture === texture) {
  38604. return true;
  38605. }
  38606. if (this._microSurfaceTexture === texture) {
  38607. return true;
  38608. }
  38609. if (this._bumpTexture === texture) {
  38610. return true;
  38611. }
  38612. if (this._lightmapTexture === texture) {
  38613. return true;
  38614. }
  38615. if (this._refractionTexture === texture) {
  38616. return true;
  38617. }
  38618. return false;
  38619. };
  38620. PBRMaterial.prototype.clone = function (name) {
  38621. var _this = this;
  38622. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38623. };
  38624. PBRMaterial.prototype.serialize = function () {
  38625. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38626. serializationObject.customType = "BABYLON.PBRMaterial";
  38627. return serializationObject;
  38628. };
  38629. // Statics
  38630. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38631. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38632. };
  38633. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38634. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38635. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38636. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38637. __decorate([
  38638. BABYLON.serialize(),
  38639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38640. ], PBRMaterial.prototype, "directIntensity", void 0);
  38641. __decorate([
  38642. BABYLON.serialize(),
  38643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38644. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38645. __decorate([
  38646. BABYLON.serialize(),
  38647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38648. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38649. __decorate([
  38650. BABYLON.serialize(),
  38651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38652. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38653. __decorate([
  38654. BABYLON.serialize(),
  38655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38656. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38657. __decorate([
  38658. BABYLON.serializeAsTexture(),
  38659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38660. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38661. __decorate([
  38662. BABYLON.serializeAsTexture(),
  38663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38664. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38665. __decorate([
  38666. BABYLON.serialize(),
  38667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38668. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38669. __decorate([
  38670. BABYLON.serializeAsTexture(),
  38671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38672. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38673. __decorate([
  38674. BABYLON.serializeAsTexture(),
  38675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38676. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38677. __decorate([
  38678. BABYLON.serializeAsTexture(),
  38679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38680. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38681. __decorate([
  38682. BABYLON.serializeAsTexture(),
  38683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38684. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38685. __decorate([
  38686. BABYLON.serializeAsTexture(),
  38687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38688. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38689. __decorate([
  38690. BABYLON.serialize(),
  38691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38692. ], PBRMaterial.prototype, "metallic", void 0);
  38693. __decorate([
  38694. BABYLON.serialize(),
  38695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38696. ], PBRMaterial.prototype, "roughness", void 0);
  38697. __decorate([
  38698. BABYLON.serializeAsTexture(),
  38699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38700. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38701. __decorate([
  38702. BABYLON.serializeAsTexture(),
  38703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38704. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38705. __decorate([
  38706. BABYLON.serializeAsTexture(),
  38707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38708. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38709. __decorate([
  38710. BABYLON.serializeAsTexture(),
  38711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38712. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38713. __decorate([
  38714. BABYLON.serializeAsColor3("ambient"),
  38715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38716. ], PBRMaterial.prototype, "ambientColor", void 0);
  38717. __decorate([
  38718. BABYLON.serializeAsColor3("albedo"),
  38719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38720. ], PBRMaterial.prototype, "albedoColor", void 0);
  38721. __decorate([
  38722. BABYLON.serializeAsColor3("reflectivity"),
  38723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38724. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38725. __decorate([
  38726. BABYLON.serializeAsColor3("reflection"),
  38727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38728. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38729. __decorate([
  38730. BABYLON.serializeAsColor3("emissive"),
  38731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38732. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38733. __decorate([
  38734. BABYLON.serialize(),
  38735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38736. ], PBRMaterial.prototype, "microSurface", void 0);
  38737. __decorate([
  38738. BABYLON.serialize(),
  38739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38740. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38741. __decorate([
  38742. BABYLON.serialize(),
  38743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38744. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38745. __decorate([
  38746. BABYLON.serialize(),
  38747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38748. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38749. __decorate([
  38750. BABYLON.serialize(),
  38751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38752. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38753. __decorate([
  38754. BABYLON.serialize(),
  38755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38756. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38757. __decorate([
  38758. BABYLON.serialize(),
  38759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38760. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38761. __decorate([
  38762. BABYLON.serialize(),
  38763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38764. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38765. __decorate([
  38766. BABYLON.serialize(),
  38767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38768. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38769. __decorate([
  38770. BABYLON.serialize(),
  38771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38772. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38773. __decorate([
  38774. BABYLON.serialize(),
  38775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38776. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38777. __decorate([
  38778. BABYLON.serialize(),
  38779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38780. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38781. __decorate([
  38782. BABYLON.serialize(),
  38783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38784. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38785. __decorate([
  38786. BABYLON.serialize(),
  38787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38788. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38789. __decorate([
  38790. BABYLON.serialize(),
  38791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38792. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38793. __decorate([
  38794. BABYLON.serialize(),
  38795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38796. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38797. __decorate([
  38798. BABYLON.serialize(),
  38799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38800. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38801. __decorate([
  38802. BABYLON.serialize(),
  38803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38804. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38805. __decorate([
  38806. BABYLON.serialize(),
  38807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38808. ], PBRMaterial.prototype, "useParallax", void 0);
  38809. __decorate([
  38810. BABYLON.serialize(),
  38811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38812. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38813. __decorate([
  38814. BABYLON.serialize(),
  38815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38816. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38817. __decorate([
  38818. BABYLON.serialize(),
  38819. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38820. ], PBRMaterial.prototype, "disableLighting", void 0);
  38821. __decorate([
  38822. BABYLON.serialize(),
  38823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38824. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38825. __decorate([
  38826. BABYLON.serialize(),
  38827. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38828. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38829. __decorate([
  38830. BABYLON.serialize(),
  38831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38832. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38833. __decorate([
  38834. BABYLON.serialize(),
  38835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38836. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38837. __decorate([
  38838. BABYLON.serialize(),
  38839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38840. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38841. __decorate([
  38842. BABYLON.serialize(),
  38843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38844. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38845. __decorate([
  38846. BABYLON.serialize(),
  38847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38848. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38849. __decorate([
  38850. BABYLON.serializeAsTexture(),
  38851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38852. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38853. __decorate([
  38854. BABYLON.serialize(),
  38855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38856. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38857. return PBRMaterial;
  38858. }(BABYLON.PBRBaseMaterial));
  38859. BABYLON.PBRMaterial = PBRMaterial;
  38860. })(BABYLON || (BABYLON = {}));
  38861. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38862. var BABYLON;
  38863. (function (BABYLON) {
  38864. /**
  38865. * The PBR material of BJS following the metal roughness convention.
  38866. *
  38867. * This fits to the PBR convention in the GLTF definition:
  38868. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38869. */
  38870. var PBRMetallicRoughnessMaterial = (function (_super) {
  38871. __extends(PBRMetallicRoughnessMaterial, _super);
  38872. /**
  38873. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38874. *
  38875. * @param name The material name
  38876. * @param scene The scene the material will be use in.
  38877. */
  38878. function PBRMetallicRoughnessMaterial(name, scene) {
  38879. var _this = _super.call(this, name, scene) || this;
  38880. _this._useRoughnessFromMetallicTextureAlpha = false;
  38881. _this._useRoughnessFromMetallicTextureGreen = true;
  38882. _this._useMetallnessFromMetallicTextureBlue = true;
  38883. return _this;
  38884. }
  38885. /**
  38886. * Return the currrent class name of the material.
  38887. */
  38888. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38889. return "PBRMetallicRoughnessMaterial";
  38890. };
  38891. /**
  38892. * Return the active textures of the material.
  38893. */
  38894. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38895. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38896. if (this.baseTexture) {
  38897. activeTextures.push(this.baseTexture);
  38898. }
  38899. if (this.metallicRoughnessTexture) {
  38900. activeTextures.push(this.metallicRoughnessTexture);
  38901. }
  38902. return activeTextures;
  38903. };
  38904. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38905. if (_super.prototype.hasTexture.call(this, texture)) {
  38906. return true;
  38907. }
  38908. if (this.baseTexture === texture) {
  38909. return true;
  38910. }
  38911. if (this.metallicRoughnessTexture === texture) {
  38912. return true;
  38913. }
  38914. return false;
  38915. };
  38916. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38917. var _this = this;
  38918. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38919. };
  38920. /**
  38921. * Serialize the material to a parsable JSON object.
  38922. */
  38923. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38924. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38925. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38926. return serializationObject;
  38927. };
  38928. /**
  38929. * Parses a JSON object correponding to the serialize function.
  38930. */
  38931. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38932. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38933. };
  38934. __decorate([
  38935. BABYLON.serializeAsColor3(),
  38936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38937. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38938. __decorate([
  38939. BABYLON.serializeAsTexture(),
  38940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38941. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38942. __decorate([
  38943. BABYLON.serialize(),
  38944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38945. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38946. __decorate([
  38947. BABYLON.serialize(),
  38948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38949. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38950. __decorate([
  38951. BABYLON.serializeAsTexture(),
  38952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38953. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38954. return PBRMetallicRoughnessMaterial;
  38955. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38956. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38957. })(BABYLON || (BABYLON = {}));
  38958. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38959. var BABYLON;
  38960. (function (BABYLON) {
  38961. /**
  38962. * The PBR material of BJS following the specular glossiness convention.
  38963. *
  38964. * This fits to the PBR convention in the GLTF definition:
  38965. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38966. */
  38967. var PBRSpecularGlossinessMaterial = (function (_super) {
  38968. __extends(PBRSpecularGlossinessMaterial, _super);
  38969. /**
  38970. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38971. *
  38972. * @param name The material name
  38973. * @param scene The scene the material will be use in.
  38974. */
  38975. function PBRSpecularGlossinessMaterial(name, scene) {
  38976. var _this = _super.call(this, name, scene) || this;
  38977. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38978. return _this;
  38979. }
  38980. /**
  38981. * Return the currrent class name of the material.
  38982. */
  38983. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38984. return "PBRSpecularGlossinessMaterial";
  38985. };
  38986. /**
  38987. * Return the active textures of the material.
  38988. */
  38989. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38990. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38991. if (this.diffuseTexture) {
  38992. activeTextures.push(this.diffuseTexture);
  38993. }
  38994. if (this.specularGlossinessTexture) {
  38995. activeTextures.push(this.specularGlossinessTexture);
  38996. }
  38997. return activeTextures;
  38998. };
  38999. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39000. if (_super.prototype.hasTexture.call(this, texture)) {
  39001. return true;
  39002. }
  39003. if (this.diffuseTexture === texture) {
  39004. return true;
  39005. }
  39006. if (this.specularGlossinessTexture === texture) {
  39007. return true;
  39008. }
  39009. return false;
  39010. };
  39011. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39012. var _this = this;
  39013. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39014. };
  39015. /**
  39016. * Serialize the material to a parsable JSON object.
  39017. */
  39018. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39019. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39020. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39021. return serializationObject;
  39022. };
  39023. /**
  39024. * Parses a JSON object correponding to the serialize function.
  39025. */
  39026. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39027. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39028. };
  39029. __decorate([
  39030. BABYLON.serializeAsColor3("diffuse"),
  39031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39032. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39033. __decorate([
  39034. BABYLON.serializeAsTexture(),
  39035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39036. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39037. __decorate([
  39038. BABYLON.serializeAsColor3("specular"),
  39039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39040. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39041. __decorate([
  39042. BABYLON.serialize(),
  39043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39044. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39045. __decorate([
  39046. BABYLON.serializeAsTexture(),
  39047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39048. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39049. return PBRSpecularGlossinessMaterial;
  39050. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39051. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39052. })(BABYLON || (BABYLON = {}));
  39053. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39054. var BABYLON;
  39055. (function (BABYLON) {
  39056. var ShaderMaterial = (function (_super) {
  39057. __extends(ShaderMaterial, _super);
  39058. function ShaderMaterial(name, scene, shaderPath, options) {
  39059. var _this = _super.call(this, name, scene) || this;
  39060. _this._textures = {};
  39061. _this._textureArrays = {};
  39062. _this._floats = {};
  39063. _this._floatsArrays = {};
  39064. _this._colors3 = {};
  39065. _this._colors3Arrays = {};
  39066. _this._colors4 = {};
  39067. _this._vectors2 = {};
  39068. _this._vectors3 = {};
  39069. _this._vectors4 = {};
  39070. _this._matrices = {};
  39071. _this._matrices3x3 = {};
  39072. _this._matrices2x2 = {};
  39073. _this._vectors3Arrays = {};
  39074. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39075. _this._shaderPath = shaderPath;
  39076. options.needAlphaBlending = options.needAlphaBlending || false;
  39077. options.needAlphaTesting = options.needAlphaTesting || false;
  39078. options.attributes = options.attributes || ["position", "normal", "uv"];
  39079. options.uniforms = options.uniforms || ["worldViewProjection"];
  39080. options.uniformBuffers = options.uniformBuffers || [];
  39081. options.samplers = options.samplers || [];
  39082. options.defines = options.defines || [];
  39083. _this._options = options;
  39084. return _this;
  39085. }
  39086. ShaderMaterial.prototype.getClassName = function () {
  39087. return "ShaderMaterial";
  39088. };
  39089. ShaderMaterial.prototype.needAlphaBlending = function () {
  39090. return this._options.needAlphaBlending;
  39091. };
  39092. ShaderMaterial.prototype.needAlphaTesting = function () {
  39093. return this._options.needAlphaTesting;
  39094. };
  39095. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39096. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39097. this._options.uniforms.push(uniformName);
  39098. }
  39099. };
  39100. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39101. if (this._options.samplers.indexOf(name) === -1) {
  39102. this._options.samplers.push(name);
  39103. }
  39104. this._textures[name] = texture;
  39105. return this;
  39106. };
  39107. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39108. if (this._options.samplers.indexOf(name) === -1) {
  39109. this._options.samplers.push(name);
  39110. }
  39111. this._checkUniform(name);
  39112. this._textureArrays[name] = textures;
  39113. return this;
  39114. };
  39115. ShaderMaterial.prototype.setFloat = function (name, value) {
  39116. this._checkUniform(name);
  39117. this._floats[name] = value;
  39118. return this;
  39119. };
  39120. ShaderMaterial.prototype.setFloats = function (name, value) {
  39121. this._checkUniform(name);
  39122. this._floatsArrays[name] = value;
  39123. return this;
  39124. };
  39125. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39126. this._checkUniform(name);
  39127. this._colors3[name] = value;
  39128. return this;
  39129. };
  39130. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  39131. this._checkUniform(name);
  39132. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  39133. color.toArray(arr, arr.length);
  39134. return arr;
  39135. }, []);
  39136. return this;
  39137. };
  39138. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39139. this._checkUniform(name);
  39140. this._colors4[name] = value;
  39141. return this;
  39142. };
  39143. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39144. this._checkUniform(name);
  39145. this._vectors2[name] = value;
  39146. return this;
  39147. };
  39148. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39149. this._checkUniform(name);
  39150. this._vectors3[name] = value;
  39151. return this;
  39152. };
  39153. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39154. this._checkUniform(name);
  39155. this._vectors4[name] = value;
  39156. return this;
  39157. };
  39158. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39159. this._checkUniform(name);
  39160. this._matrices[name] = value;
  39161. return this;
  39162. };
  39163. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39164. this._checkUniform(name);
  39165. this._matrices3x3[name] = value;
  39166. return this;
  39167. };
  39168. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39169. this._checkUniform(name);
  39170. this._matrices2x2[name] = value;
  39171. return this;
  39172. };
  39173. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39174. this._checkUniform(name);
  39175. this._vectors3Arrays[name] = value;
  39176. return this;
  39177. };
  39178. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39179. if (!mesh) {
  39180. return true;
  39181. }
  39182. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39183. return false;
  39184. }
  39185. return false;
  39186. };
  39187. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39188. var scene = this.getScene();
  39189. var engine = scene.getEngine();
  39190. if (!this.checkReadyOnEveryCall) {
  39191. if (this._renderId === scene.getRenderId()) {
  39192. if (this._checkCache(scene, mesh, useInstances)) {
  39193. return true;
  39194. }
  39195. }
  39196. }
  39197. // Instances
  39198. var defines = [];
  39199. var attribs = [];
  39200. var fallbacks = new BABYLON.EffectFallbacks();
  39201. if (useInstances) {
  39202. defines.push("#define INSTANCES");
  39203. }
  39204. for (var index = 0; index < this._options.defines.length; index++) {
  39205. defines.push(this._options.defines[index]);
  39206. }
  39207. for (var index = 0; index < this._options.attributes.length; index++) {
  39208. attribs.push(this._options.attributes[index]);
  39209. }
  39210. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39211. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39212. defines.push("#define VERTEXCOLOR");
  39213. }
  39214. // Bones
  39215. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39216. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39217. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39218. if (mesh.numBoneInfluencers > 4) {
  39219. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39220. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39221. }
  39222. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39223. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39224. fallbacks.addCPUSkinningFallback(0, mesh);
  39225. if (this._options.uniforms.indexOf("mBones") === -1) {
  39226. this._options.uniforms.push("mBones");
  39227. }
  39228. }
  39229. else {
  39230. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39231. }
  39232. // Textures
  39233. for (var name in this._textures) {
  39234. if (!this._textures[name].isReady()) {
  39235. return false;
  39236. }
  39237. }
  39238. // Alpha test
  39239. if (engine.getAlphaTesting()) {
  39240. defines.push("#define ALPHATEST");
  39241. }
  39242. var previousEffect = this._effect;
  39243. var join = defines.join("\n");
  39244. this._effect = engine.createEffect(this._shaderPath, {
  39245. attributes: attribs,
  39246. uniformsNames: this._options.uniforms,
  39247. uniformBuffersNames: this._options.uniformBuffers,
  39248. samplers: this._options.samplers,
  39249. defines: join,
  39250. fallbacks: fallbacks,
  39251. onCompiled: this.onCompiled,
  39252. onError: this.onError
  39253. }, engine);
  39254. if (!this._effect.isReady()) {
  39255. return false;
  39256. }
  39257. if (previousEffect !== this._effect) {
  39258. scene.resetCachedMaterial();
  39259. }
  39260. this._renderId = scene.getRenderId();
  39261. return true;
  39262. };
  39263. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39264. var scene = this.getScene();
  39265. if (this._options.uniforms.indexOf("world") !== -1) {
  39266. this._effect.setMatrix("world", world);
  39267. }
  39268. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39269. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39270. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39271. }
  39272. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39273. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39274. }
  39275. };
  39276. ShaderMaterial.prototype.bind = function (world, mesh) {
  39277. // Std values
  39278. this.bindOnlyWorldMatrix(world);
  39279. if (this.getScene().getCachedMaterial() !== this) {
  39280. if (this._options.uniforms.indexOf("view") !== -1) {
  39281. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39282. }
  39283. if (this._options.uniforms.indexOf("projection") !== -1) {
  39284. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39285. }
  39286. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39287. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39288. }
  39289. // Bones
  39290. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39291. var name;
  39292. // Texture
  39293. for (name in this._textures) {
  39294. this._effect.setTexture(name, this._textures[name]);
  39295. }
  39296. // Texture arrays
  39297. for (name in this._textureArrays) {
  39298. this._effect.setTextureArray(name, this._textureArrays[name]);
  39299. }
  39300. // Float
  39301. for (name in this._floats) {
  39302. this._effect.setFloat(name, this._floats[name]);
  39303. }
  39304. // Float s
  39305. for (name in this._floatsArrays) {
  39306. this._effect.setArray(name, this._floatsArrays[name]);
  39307. }
  39308. // Color3
  39309. for (name in this._colors3) {
  39310. this._effect.setColor3(name, this._colors3[name]);
  39311. }
  39312. for (name in this._colors3Arrays) {
  39313. this._effect.setArray3(name, this._colors3Arrays[name]);
  39314. }
  39315. // Color4
  39316. for (name in this._colors4) {
  39317. var color = this._colors4[name];
  39318. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39319. }
  39320. // Vector2
  39321. for (name in this._vectors2) {
  39322. this._effect.setVector2(name, this._vectors2[name]);
  39323. }
  39324. // Vector3
  39325. for (name in this._vectors3) {
  39326. this._effect.setVector3(name, this._vectors3[name]);
  39327. }
  39328. // Vector4
  39329. for (name in this._vectors4) {
  39330. this._effect.setVector4(name, this._vectors4[name]);
  39331. }
  39332. // Matrix
  39333. for (name in this._matrices) {
  39334. this._effect.setMatrix(name, this._matrices[name]);
  39335. }
  39336. // Matrix 3x3
  39337. for (name in this._matrices3x3) {
  39338. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39339. }
  39340. // Matrix 2x2
  39341. for (name in this._matrices2x2) {
  39342. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39343. }
  39344. // Vector3Array
  39345. for (name in this._vectors3Arrays) {
  39346. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39347. }
  39348. }
  39349. this._afterBind(mesh);
  39350. };
  39351. ShaderMaterial.prototype.getActiveTextures = function () {
  39352. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39353. for (var name in this._textures) {
  39354. activeTextures.push(this._textures[name]);
  39355. }
  39356. for (var name in this._textureArrays) {
  39357. var array = this._textureArrays[name];
  39358. for (var index = 0; index < array.length; index++) {
  39359. activeTextures.push(array[index]);
  39360. }
  39361. }
  39362. return activeTextures;
  39363. };
  39364. ShaderMaterial.prototype.hasTexture = function (texture) {
  39365. if (_super.prototype.hasTexture.call(this, texture)) {
  39366. return true;
  39367. }
  39368. for (var name in this._textures) {
  39369. if (this._textures[name] === texture) {
  39370. return true;
  39371. }
  39372. }
  39373. for (var name in this._textureArrays) {
  39374. var array = this._textureArrays[name];
  39375. for (var index = 0; index < array.length; index++) {
  39376. if (array[index] === texture) {
  39377. return true;
  39378. }
  39379. }
  39380. }
  39381. return false;
  39382. };
  39383. ShaderMaterial.prototype.clone = function (name) {
  39384. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39385. return newShaderMaterial;
  39386. };
  39387. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39388. if (forceDisposeTextures) {
  39389. var name;
  39390. for (name in this._textures) {
  39391. this._textures[name].dispose();
  39392. }
  39393. for (name in this._textureArrays) {
  39394. var array = this._textureArrays[name];
  39395. for (var index = 0; index < array.length; index++) {
  39396. array[index].dispose();
  39397. }
  39398. }
  39399. }
  39400. this._textures = {};
  39401. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39402. };
  39403. ShaderMaterial.prototype.serialize = function () {
  39404. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39405. serializationObject.customType = "BABYLON.ShaderMaterial";
  39406. serializationObject.options = this._options;
  39407. serializationObject.shaderPath = this._shaderPath;
  39408. var name;
  39409. // Texture
  39410. serializationObject.textures = {};
  39411. for (name in this._textures) {
  39412. serializationObject.textures[name] = this._textures[name].serialize();
  39413. }
  39414. // Texture arrays
  39415. serializationObject.textureArrays = {};
  39416. for (name in this._textureArrays) {
  39417. serializationObject.textureArrays[name] = [];
  39418. var array = this._textureArrays[name];
  39419. for (var index = 0; index < array.length; index++) {
  39420. serializationObject.textureArrays[name].push(array[index].serialize());
  39421. }
  39422. }
  39423. // Float
  39424. serializationObject.floats = {};
  39425. for (name in this._floats) {
  39426. serializationObject.floats[name] = this._floats[name];
  39427. }
  39428. // Float s
  39429. serializationObject.floatArrays = {};
  39430. for (name in this._floatsArrays) {
  39431. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39432. }
  39433. // Color3
  39434. serializationObject.colors3 = {};
  39435. for (name in this._colors3) {
  39436. serializationObject.colors3[name] = this._colors3[name].asArray();
  39437. }
  39438. // Color3 array
  39439. serializationObject.colors3Arrays = {};
  39440. for (name in this._colors3Arrays) {
  39441. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  39442. }
  39443. // Color4
  39444. serializationObject.colors4 = {};
  39445. for (name in this._colors4) {
  39446. serializationObject.colors4[name] = this._colors4[name].asArray();
  39447. }
  39448. // Vector2
  39449. serializationObject.vectors2 = {};
  39450. for (name in this._vectors2) {
  39451. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39452. }
  39453. // Vector3
  39454. serializationObject.vectors3 = {};
  39455. for (name in this._vectors3) {
  39456. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39457. }
  39458. // Vector4
  39459. serializationObject.vectors4 = {};
  39460. for (name in this._vectors4) {
  39461. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39462. }
  39463. // Matrix
  39464. serializationObject.matrices = {};
  39465. for (name in this._matrices) {
  39466. serializationObject.matrices[name] = this._matrices[name].asArray();
  39467. }
  39468. // Matrix 3x3
  39469. serializationObject.matrices3x3 = {};
  39470. for (name in this._matrices3x3) {
  39471. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39472. }
  39473. // Matrix 2x2
  39474. serializationObject.matrices2x2 = {};
  39475. for (name in this._matrices2x2) {
  39476. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39477. }
  39478. // Vector3Array
  39479. serializationObject.vectors3Arrays = {};
  39480. for (name in this._vectors3Arrays) {
  39481. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39482. }
  39483. return serializationObject;
  39484. };
  39485. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39486. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39487. var name;
  39488. // Texture
  39489. for (name in source.textures) {
  39490. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39491. }
  39492. // Texture arrays
  39493. for (name in source.textureArrays) {
  39494. var array = source.textureArrays[name];
  39495. var textureArray = new Array();
  39496. for (var index = 0; index < array.length; index++) {
  39497. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39498. }
  39499. material.setTextureArray(name, textureArray);
  39500. }
  39501. // Float
  39502. for (name in source.floats) {
  39503. material.setFloat(name, source.floats[name]);
  39504. }
  39505. // Float s
  39506. for (name in source.floatsArrays) {
  39507. material.setFloats(name, source.floatsArrays[name]);
  39508. }
  39509. // Color3
  39510. for (name in source.colors3) {
  39511. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39512. }
  39513. // Color3 arrays
  39514. for (name in source.colors3Arrays) {
  39515. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  39516. if (i % 3 === 0) {
  39517. arr.push([num]);
  39518. }
  39519. else {
  39520. arr[arr.length - 1].push(num);
  39521. }
  39522. return arr;
  39523. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  39524. material.setColor3Array(name, colors);
  39525. }
  39526. // Color4
  39527. for (name in source.colors4) {
  39528. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39529. }
  39530. // Vector2
  39531. for (name in source.vectors2) {
  39532. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39533. }
  39534. // Vector3
  39535. for (name in source.vectors3) {
  39536. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39537. }
  39538. // Vector4
  39539. for (name in source.vectors4) {
  39540. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39541. }
  39542. // Matrix
  39543. for (name in source.matrices) {
  39544. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39545. }
  39546. // Matrix 3x3
  39547. for (name in source.matrices3x3) {
  39548. material.setMatrix3x3(name, source.matrices3x3[name]);
  39549. }
  39550. // Matrix 2x2
  39551. for (name in source.matrices2x2) {
  39552. material.setMatrix2x2(name, source.matrices2x2[name]);
  39553. }
  39554. // Vector3Array
  39555. for (name in source.vectors3Arrays) {
  39556. material.setArray3(name, source.vectors3Arrays[name]);
  39557. }
  39558. return material;
  39559. };
  39560. return ShaderMaterial;
  39561. }(BABYLON.Material));
  39562. BABYLON.ShaderMaterial = ShaderMaterial;
  39563. })(BABYLON || (BABYLON = {}));
  39564. //# sourceMappingURL=babylon.shaderMaterial.js.map
  39565. var BABYLON;
  39566. (function (BABYLON) {
  39567. var MeshBuilder = (function () {
  39568. function MeshBuilder() {
  39569. }
  39570. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  39571. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  39572. return BABYLON.Mesh.DOUBLESIDE;
  39573. }
  39574. if (orientation === undefined || orientation === null) {
  39575. return BABYLON.Mesh.FRONTSIDE;
  39576. }
  39577. return orientation;
  39578. };
  39579. /**
  39580. * Creates a box mesh.
  39581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  39582. * The parameter `size` sets the size (float) of each box side (default 1).
  39583. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  39584. * 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).
  39585. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39587. * 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).
  39588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39590. */
  39591. MeshBuilder.CreateBox = function (name, options, scene) {
  39592. var box = new BABYLON.Mesh(name, scene);
  39593. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39594. box.sideOrientation = options.sideOrientation;
  39595. var vertexData = BABYLON.VertexData.CreateBox(options);
  39596. vertexData.applyToMesh(box, options.updatable);
  39597. return box;
  39598. };
  39599. /**
  39600. * Creates a sphere mesh.
  39601. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  39602. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  39603. * 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`).
  39604. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  39605. * 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
  39606. * 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).
  39607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39608. * 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).
  39609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39611. */
  39612. MeshBuilder.CreateSphere = function (name, options, scene) {
  39613. var sphere = new BABYLON.Mesh(name, scene);
  39614. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39615. sphere.sideOrientation = options.sideOrientation;
  39616. var vertexData = BABYLON.VertexData.CreateSphere(options);
  39617. vertexData.applyToMesh(sphere, options.updatable);
  39618. return sphere;
  39619. };
  39620. /**
  39621. * Creates a plane polygonal mesh. By default, this is a disc.
  39622. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  39623. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  39624. * 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.
  39625. * 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
  39626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39627. * 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).
  39628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39630. */
  39631. MeshBuilder.CreateDisc = function (name, options, scene) {
  39632. var disc = new BABYLON.Mesh(name, scene);
  39633. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39634. disc.sideOrientation = options.sideOrientation;
  39635. var vertexData = BABYLON.VertexData.CreateDisc(options);
  39636. vertexData.applyToMesh(disc, options.updatable);
  39637. return disc;
  39638. };
  39639. /**
  39640. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  39641. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  39642. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  39643. * 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`).
  39644. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  39645. * 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.
  39646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39647. * 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).
  39648. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39650. */
  39651. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  39652. var sphere = new BABYLON.Mesh(name, scene);
  39653. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39654. sphere.sideOrientation = options.sideOrientation;
  39655. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  39656. vertexData.applyToMesh(sphere, options.updatable);
  39657. return sphere;
  39658. };
  39659. ;
  39660. /**
  39661. * Creates a ribbon mesh.
  39662. * 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.
  39663. *
  39664. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39665. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39666. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39667. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39668. * 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.
  39669. * 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.
  39670. * 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
  39671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39672. * 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).
  39673. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39674. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39675. * 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.
  39676. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39677. * 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
  39678. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39679. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39680. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39681. */
  39682. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39683. var pathArray = options.pathArray;
  39684. var closeArray = options.closeArray;
  39685. var closePath = options.closePath;
  39686. var offset = options.offset;
  39687. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39688. var instance = options.instance;
  39689. var updatable = options.updatable;
  39690. if (instance) {
  39691. // positionFunction : ribbon case
  39692. // only pathArray and sideOrientation parameters are taken into account for positions update
  39693. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39694. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39695. var positionFunction = function (positions) {
  39696. var minlg = pathArray[0].length;
  39697. var i = 0;
  39698. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39699. for (var si = 1; si <= ns; si++) {
  39700. for (var p = 0; p < pathArray.length; p++) {
  39701. var path = pathArray[p];
  39702. var l = path.length;
  39703. minlg = (minlg < l) ? minlg : l;
  39704. var j = 0;
  39705. while (j < minlg) {
  39706. positions[i] = path[j].x;
  39707. positions[i + 1] = path[j].y;
  39708. positions[i + 2] = path[j].z;
  39709. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39710. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39711. }
  39712. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39713. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39714. }
  39715. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39716. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39717. }
  39718. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39719. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39720. }
  39721. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39722. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39723. }
  39724. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39725. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39726. }
  39727. j++;
  39728. i += 3;
  39729. }
  39730. if (instance._closePath) {
  39731. positions[i] = path[0].x;
  39732. positions[i + 1] = path[0].y;
  39733. positions[i + 2] = path[0].z;
  39734. i += 3;
  39735. }
  39736. }
  39737. }
  39738. };
  39739. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39740. positionFunction(positions);
  39741. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39742. instance._boundingInfo.update(instance._worldMatrix);
  39743. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39744. if (options.colors) {
  39745. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39746. for (var c = 0; c < options.colors.length; c++) {
  39747. colors[c * 4] = options.colors[c].r;
  39748. colors[c * 4 + 1] = options.colors[c].g;
  39749. colors[c * 4 + 2] = options.colors[c].b;
  39750. colors[c * 4 + 3] = options.colors[c].a;
  39751. }
  39752. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39753. }
  39754. if (options.uvs) {
  39755. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39756. for (var i = 0; i < options.uvs.length; i++) {
  39757. uvs[i * 2] = options.uvs[i].x;
  39758. uvs[i * 2 + 1] = options.uvs[i].y;
  39759. }
  39760. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39761. }
  39762. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39763. var indices = instance.getIndices();
  39764. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39765. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39766. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39767. if (instance._closePath) {
  39768. var indexFirst = 0;
  39769. var indexLast = 0;
  39770. for (var p = 0; p < pathArray.length; p++) {
  39771. indexFirst = instance._idx[p] * 3;
  39772. if (p + 1 < pathArray.length) {
  39773. indexLast = (instance._idx[p + 1] - 1) * 3;
  39774. }
  39775. else {
  39776. indexLast = normals.length - 3;
  39777. }
  39778. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39779. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39780. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39781. normals[indexLast] = normals[indexFirst];
  39782. normals[indexLast + 1] = normals[indexFirst + 1];
  39783. normals[indexLast + 2] = normals[indexFirst + 2];
  39784. }
  39785. }
  39786. if (!(instance.areNormalsFrozen)) {
  39787. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39788. }
  39789. }
  39790. return instance;
  39791. }
  39792. else {
  39793. var ribbon = new BABYLON.Mesh(name, scene);
  39794. ribbon.sideOrientation = sideOrientation;
  39795. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39796. if (closePath) {
  39797. ribbon._idx = vertexData._idx;
  39798. }
  39799. ribbon._closePath = closePath;
  39800. ribbon._closeArray = closeArray;
  39801. vertexData.applyToMesh(ribbon, updatable);
  39802. return ribbon;
  39803. }
  39804. };
  39805. /**
  39806. * Creates a cylinder or a cone mesh.
  39807. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39808. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39809. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39810. * 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.
  39811. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39812. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39813. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39814. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39815. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39816. * 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).
  39817. * 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
  39818. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39819. * 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
  39820. * 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.
  39821. * If `enclose` is false, a ring surface is one element.
  39822. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39823. * 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
  39824. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39825. * 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).
  39826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39828. */
  39829. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39830. var cylinder = new BABYLON.Mesh(name, scene);
  39831. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39832. cylinder.sideOrientation = options.sideOrientation;
  39833. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39834. vertexData.applyToMesh(cylinder, options.updatable);
  39835. return cylinder;
  39836. };
  39837. /**
  39838. * Creates a torus mesh.
  39839. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39840. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39841. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39842. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39844. * 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).
  39845. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39847. */
  39848. MeshBuilder.CreateTorus = function (name, options, scene) {
  39849. var torus = new BABYLON.Mesh(name, scene);
  39850. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39851. torus.sideOrientation = options.sideOrientation;
  39852. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39853. vertexData.applyToMesh(torus, options.updatable);
  39854. return torus;
  39855. };
  39856. /**
  39857. * Creates a torus knot mesh.
  39858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39859. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39860. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39861. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39862. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39864. * 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).
  39865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39867. */
  39868. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39869. var torusKnot = new BABYLON.Mesh(name, scene);
  39870. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39871. torusKnot.sideOrientation = options.sideOrientation;
  39872. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39873. vertexData.applyToMesh(torusKnot, options.updatable);
  39874. return torusKnot;
  39875. };
  39876. /**
  39877. * Creates a line system mesh.
  39878. * A line system is a pool of many lines gathered in a single mesh.
  39879. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39880. * 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.
  39881. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39882. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39883. * 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
  39884. * 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
  39885. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39887. */
  39888. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39889. var instance = options.instance;
  39890. var lines = options.lines;
  39891. if (instance) {
  39892. var positionFunction = function (positions) {
  39893. var i = 0;
  39894. for (var l = 0; l < lines.length; l++) {
  39895. var points = lines[l];
  39896. for (var p = 0; p < points.length; p++) {
  39897. positions[i] = points[p].x;
  39898. positions[i + 1] = points[p].y;
  39899. positions[i + 2] = points[p].z;
  39900. i += 3;
  39901. }
  39902. }
  39903. };
  39904. instance.updateMeshPositions(positionFunction, false);
  39905. return instance;
  39906. }
  39907. // line system creation
  39908. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39909. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39910. vertexData.applyToMesh(lineSystem, options.updatable);
  39911. return lineSystem;
  39912. };
  39913. /**
  39914. * Creates a line mesh.
  39915. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39916. * 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.
  39917. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39918. * The parameter `points` is an array successive Vector3.
  39919. * 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
  39920. * When updating an instance, remember that only point positions can change, not the number of points.
  39921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39922. */
  39923. MeshBuilder.CreateLines = function (name, options, scene) {
  39924. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39925. return lines;
  39926. };
  39927. /**
  39928. * Creates a dashed line mesh.
  39929. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39930. * 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.
  39931. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39932. * The parameter `points` is an array successive Vector3.
  39933. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39934. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39935. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39936. * 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
  39937. * When updating an instance, remember that only point positions can change, not the number of points.
  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.CreateDashedLines = function (name, options, scene) {
  39941. var points = options.points;
  39942. var instance = options.instance;
  39943. var gapSize = options.gapSize;
  39944. var dashNb = options.dashNb;
  39945. var dashSize = options.dashSize;
  39946. if (instance) {
  39947. var positionFunction = function (positions) {
  39948. var curvect = BABYLON.Vector3.Zero();
  39949. var nbSeg = positions.length / 6;
  39950. var lg = 0;
  39951. var nb = 0;
  39952. var shft = 0;
  39953. var dashshft = 0;
  39954. var curshft = 0;
  39955. var p = 0;
  39956. var i = 0;
  39957. var j = 0;
  39958. for (i = 0; i < points.length - 1; i++) {
  39959. points[i + 1].subtractToRef(points[i], curvect);
  39960. lg += curvect.length();
  39961. }
  39962. shft = lg / nbSeg;
  39963. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39964. for (i = 0; i < points.length - 1; i++) {
  39965. points[i + 1].subtractToRef(points[i], curvect);
  39966. nb = Math.floor(curvect.length() / shft);
  39967. curvect.normalize();
  39968. j = 0;
  39969. while (j < nb && p < positions.length) {
  39970. curshft = shft * j;
  39971. positions[p] = points[i].x + curshft * curvect.x;
  39972. positions[p + 1] = points[i].y + curshft * curvect.y;
  39973. positions[p + 2] = points[i].z + curshft * curvect.z;
  39974. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39975. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39976. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39977. p += 6;
  39978. j++;
  39979. }
  39980. }
  39981. while (p < positions.length) {
  39982. positions[p] = points[i].x;
  39983. positions[p + 1] = points[i].y;
  39984. positions[p + 2] = points[i].z;
  39985. p += 3;
  39986. }
  39987. };
  39988. instance.updateMeshPositions(positionFunction, false);
  39989. return instance;
  39990. }
  39991. // dashed lines creation
  39992. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39993. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39994. vertexData.applyToMesh(dashedLines, options.updatable);
  39995. dashedLines.dashSize = dashSize;
  39996. dashedLines.gapSize = gapSize;
  39997. return dashedLines;
  39998. };
  39999. /**
  40000. * Creates an extruded shape mesh.
  40001. * 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.
  40002. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40003. *
  40004. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40005. * 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
  40006. * extruded along the Z axis.
  40007. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40008. * 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.
  40009. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40010. * 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
  40011. * 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
  40012. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40014. * 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).
  40015. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40016. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40018. */
  40019. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40020. var path = options.path;
  40021. var shape = options.shape;
  40022. var scale = options.scale || 1;
  40023. var rotation = options.rotation || 0;
  40024. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40025. var updatable = options.updatable;
  40026. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40027. var instance = options.instance;
  40028. var invertUV = options.invertUV || false;
  40029. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40030. };
  40031. /**
  40032. * Creates an custom extruded shape mesh.
  40033. * 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.
  40034. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40035. *
  40036. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40037. * 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
  40038. * extruded along the Z axis.
  40039. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40040. * 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
  40041. * and the distance of this point from the begining of the path :
  40042. * ```javascript
  40043. * var rotationFunction = function(i, distance) {
  40044. * // do things
  40045. * return rotationValue; }
  40046. * ```
  40047. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40048. * 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
  40049. * and the distance of this point from the begining of the path :
  40050. * ```javascript
  40051. * var scaleFunction = function(i, distance) {
  40052. * // do things
  40053. * return scaleValue;}
  40054. * ```
  40055. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40056. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40057. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40058. * 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
  40059. * 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
  40060. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40062. * 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).
  40063. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40064. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40066. */
  40067. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40068. var path = options.path;
  40069. var shape = options.shape;
  40070. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40071. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40072. var ribbonCloseArray = options.ribbonCloseArray || false;
  40073. var ribbonClosePath = options.ribbonClosePath || false;
  40074. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40075. var updatable = options.updatable;
  40076. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40077. var instance = options.instance;
  40078. var invertUV = options.invertUV || false;
  40079. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40080. };
  40081. /**
  40082. * Creates lathe mesh.
  40083. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40084. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40085. *
  40086. * 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
  40087. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40088. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40089. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40090. * 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.
  40091. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40092. * 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
  40093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40094. * 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).
  40095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40096. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40098. */
  40099. MeshBuilder.CreateLathe = function (name, options, scene) {
  40100. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40101. var closed = (options.closed === undefined) ? true : options.closed;
  40102. var shape = options.shape;
  40103. var radius = options.radius || 1;
  40104. var tessellation = options.tessellation || 64;
  40105. var updatable = options.updatable;
  40106. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40107. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40108. var pi2 = Math.PI * 2;
  40109. var paths = new Array();
  40110. var invertUV = options.invertUV || false;
  40111. var i = 0;
  40112. var p = 0;
  40113. var step = pi2 / tessellation * arc;
  40114. var rotated;
  40115. var path = new Array();
  40116. ;
  40117. for (i = 0; i <= tessellation; i++) {
  40118. var path = [];
  40119. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40120. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40121. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40122. }
  40123. for (p = 0; p < shape.length; p++) {
  40124. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40125. path.push(rotated);
  40126. }
  40127. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40128. 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));
  40129. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40130. }
  40131. paths.push(path);
  40132. }
  40133. // lathe ribbon
  40134. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40135. return lathe;
  40136. };
  40137. /**
  40138. * Creates a plane mesh.
  40139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40140. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40141. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40142. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40143. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40144. * 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).
  40145. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40147. */
  40148. MeshBuilder.CreatePlane = function (name, options, scene) {
  40149. var plane = new BABYLON.Mesh(name, scene);
  40150. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40151. plane.sideOrientation = options.sideOrientation;
  40152. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40153. vertexData.applyToMesh(plane, options.updatable);
  40154. if (options.sourcePlane) {
  40155. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40156. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40157. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40158. plane.rotate(vectorProduct, product);
  40159. }
  40160. return plane;
  40161. };
  40162. /**
  40163. * Creates a ground mesh.
  40164. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40165. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40166. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40167. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40168. */
  40169. MeshBuilder.CreateGround = function (name, options, scene) {
  40170. var ground = new BABYLON.GroundMesh(name, scene);
  40171. ground._setReady(false);
  40172. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40173. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40174. ground._width = options.width || 1;
  40175. ground._height = options.height || 1;
  40176. ground._maxX = ground._width / 2;
  40177. ground._maxZ = ground._height / 2;
  40178. ground._minX = -ground._maxX;
  40179. ground._minZ = -ground._maxZ;
  40180. var vertexData = BABYLON.VertexData.CreateGround(options);
  40181. vertexData.applyToMesh(ground, options.updatable);
  40182. ground._setReady(true);
  40183. return ground;
  40184. };
  40185. /**
  40186. * Creates a tiled ground mesh.
  40187. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40188. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40189. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40190. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40191. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40192. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40193. * numbers of subdivisions on the ground width and height of each tile.
  40194. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40195. */
  40196. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40197. var tiledGround = new BABYLON.Mesh(name, scene);
  40198. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40199. vertexData.applyToMesh(tiledGround, options.updatable);
  40200. return tiledGround;
  40201. };
  40202. /**
  40203. * Creates a ground mesh from a height map.
  40204. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40205. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40206. * The parameter `url` sets the URL of the height map image resource.
  40207. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40208. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40209. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40210. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40211. * 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.
  40212. * 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).
  40213. * This function is passed the newly built mesh :
  40214. * ```javascript
  40215. * function(mesh) { // do things
  40216. * return; }
  40217. * ```
  40218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40219. */
  40220. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40221. var width = options.width || 10.0;
  40222. var height = options.height || 10.0;
  40223. var subdivisions = options.subdivisions || 1 | 0;
  40224. var minHeight = options.minHeight || 0.0;
  40225. var maxHeight = options.maxHeight || 10.0;
  40226. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40227. var updatable = options.updatable;
  40228. var onReady = options.onReady;
  40229. var ground = new BABYLON.GroundMesh(name, scene);
  40230. ground._subdivisionsX = subdivisions;
  40231. ground._subdivisionsY = subdivisions;
  40232. ground._width = width;
  40233. ground._height = height;
  40234. ground._maxX = ground._width / 2.0;
  40235. ground._maxZ = ground._height / 2.0;
  40236. ground._minX = -ground._maxX;
  40237. ground._minZ = -ground._maxZ;
  40238. ground._setReady(false);
  40239. var onload = function (img) {
  40240. // Getting height map data
  40241. var canvas = document.createElement("canvas");
  40242. var context = canvas.getContext("2d");
  40243. var bufferWidth = img.width;
  40244. var bufferHeight = img.height;
  40245. canvas.width = bufferWidth;
  40246. canvas.height = bufferHeight;
  40247. context.drawImage(img, 0, 0);
  40248. // Create VertexData from map data
  40249. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40250. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40251. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40252. width: width, height: height,
  40253. subdivisions: subdivisions,
  40254. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40255. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40256. });
  40257. vertexData.applyToMesh(ground, updatable);
  40258. ground._setReady(true);
  40259. //execute ready callback, if set
  40260. if (onReady) {
  40261. onReady(ground);
  40262. }
  40263. };
  40264. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40265. return ground;
  40266. };
  40267. /**
  40268. * Creates a polygon mesh.
  40269. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40270. * 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.
  40271. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40273. * 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).
  40274. * Remember you can only change the shape positions, not their number when updating a polygon.
  40275. */
  40276. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40277. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40278. var shape = options.shape;
  40279. var holes = options.holes || [];
  40280. var depth = options.depth || 0;
  40281. var contours = [];
  40282. var hole = [];
  40283. for (var i = 0; i < shape.length; i++) {
  40284. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40285. }
  40286. var epsilon = 0.00000001;
  40287. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40288. contours.pop();
  40289. }
  40290. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40291. for (var hNb = 0; hNb < holes.length; hNb++) {
  40292. hole = [];
  40293. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40294. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40295. }
  40296. polygonTriangulation.addHole(hole);
  40297. }
  40298. var polygon = polygonTriangulation.build(options.updatable, depth);
  40299. polygon.sideOrientation = options.sideOrientation;
  40300. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40301. vertexData.applyToMesh(polygon, options.updatable);
  40302. return polygon;
  40303. };
  40304. ;
  40305. /**
  40306. * Creates an extruded polygon mesh, with depth in the Y direction.
  40307. * 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).
  40308. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40309. */
  40310. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40311. return MeshBuilder.CreatePolygon(name, options, scene);
  40312. };
  40313. ;
  40314. /**
  40315. * Creates a tube mesh.
  40316. * 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.
  40317. *
  40318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40319. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40320. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40321. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40322. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40323. * 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.
  40324. * It must return a radius value (positive float) :
  40325. * ```javascript
  40326. * var radiusFunction = function(i, distance) {
  40327. * // do things
  40328. * return radius; }
  40329. * ```
  40330. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40331. * 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
  40332. * 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
  40333. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40334. * 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).
  40335. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40336. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40338. */
  40339. MeshBuilder.CreateTube = function (name, options, scene) {
  40340. var path = options.path;
  40341. var radius = options.radius || 1.0;
  40342. var tessellation = options.tessellation || 64 | 0;
  40343. var radiusFunction = options.radiusFunction;
  40344. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40345. var invertUV = options.invertUV || false;
  40346. var updatable = options.updatable;
  40347. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40348. var instance = options.instance;
  40349. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40350. // tube geometry
  40351. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40352. var tangents = path3D.getTangents();
  40353. var normals = path3D.getNormals();
  40354. var distances = path3D.getDistances();
  40355. var pi2 = Math.PI * 2;
  40356. var step = pi2 / tessellation * arc;
  40357. var returnRadius = function () { return radius; };
  40358. var radiusFunctionFinal = radiusFunction || returnRadius;
  40359. var circlePath;
  40360. var rad;
  40361. var normal;
  40362. var rotated;
  40363. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40364. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40365. for (var i = 0; i < path.length; i++) {
  40366. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40367. circlePath = Array(); // current circle array
  40368. normal = normals[i]; // current normal
  40369. for (var t = 0; t < tessellation; t++) {
  40370. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40371. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40372. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40373. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40374. circlePath[t] = rotated;
  40375. }
  40376. circlePaths[index] = circlePath;
  40377. index++;
  40378. }
  40379. // cap
  40380. var capPath = function (nbPoints, pathIndex) {
  40381. var pointCap = Array();
  40382. for (var i = 0; i < nbPoints; i++) {
  40383. pointCap.push(path[pathIndex]);
  40384. }
  40385. return pointCap;
  40386. };
  40387. switch (cap) {
  40388. case BABYLON.Mesh.NO_CAP:
  40389. break;
  40390. case BABYLON.Mesh.CAP_START:
  40391. circlePaths[0] = capPath(tessellation, 0);
  40392. circlePaths[1] = circlePaths[2].slice(0);
  40393. break;
  40394. case BABYLON.Mesh.CAP_END:
  40395. circlePaths[index] = circlePaths[index - 1].slice(0);
  40396. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40397. break;
  40398. case BABYLON.Mesh.CAP_ALL:
  40399. circlePaths[0] = capPath(tessellation, 0);
  40400. circlePaths[1] = circlePaths[2].slice(0);
  40401. circlePaths[index] = circlePaths[index - 1].slice(0);
  40402. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40403. break;
  40404. default:
  40405. break;
  40406. }
  40407. return circlePaths;
  40408. };
  40409. var path3D;
  40410. var pathArray;
  40411. if (instance) {
  40412. var arc = options.arc || instance.arc;
  40413. path3D = (instance.path3D).update(path);
  40414. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40415. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40416. instance.path3D = path3D;
  40417. instance.pathArray = pathArray;
  40418. instance.arc = arc;
  40419. return instance;
  40420. }
  40421. // tube creation
  40422. path3D = new BABYLON.Path3D(path);
  40423. var newPathArray = new Array();
  40424. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40425. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40426. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40427. tube.pathArray = pathArray;
  40428. tube.path3D = path3D;
  40429. tube.tessellation = tessellation;
  40430. tube.cap = cap;
  40431. tube.arc = options.arc;
  40432. return tube;
  40433. };
  40434. /**
  40435. * Creates a polyhedron mesh.
  40436. *
  40437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40438. * 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
  40439. * to choose the wanted type.
  40440. * The parameter `size` (positive float, default 1) sets the polygon size.
  40441. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40442. * 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`.
  40443. * 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
  40444. * 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)`).
  40445. * 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
  40446. * 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.
  40447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40448. * 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).
  40449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40451. */
  40452. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40453. var polyhedron = new BABYLON.Mesh(name, scene);
  40454. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40455. polyhedron.sideOrientation = options.sideOrientation;
  40456. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40457. vertexData.applyToMesh(polyhedron, options.updatable);
  40458. return polyhedron;
  40459. };
  40460. /**
  40461. * Creates a decal mesh.
  40462. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  40463. * 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.
  40464. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  40465. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  40466. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  40467. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  40468. */
  40469. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  40470. var indices = sourceMesh.getIndices();
  40471. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40472. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40473. var position = options.position || BABYLON.Vector3.Zero();
  40474. var normal = options.normal || BABYLON.Vector3.Up();
  40475. var size = options.size || BABYLON.Vector3.One();
  40476. var angle = options.angle || 0;
  40477. // Getting correct rotation
  40478. if (!normal) {
  40479. var target = new BABYLON.Vector3(0, 0, 1);
  40480. var camera = sourceMesh.getScene().activeCamera;
  40481. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  40482. normal = camera.globalPosition.subtract(cameraWorldTarget);
  40483. }
  40484. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  40485. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  40486. var pitch = Math.atan2(normal.y, len);
  40487. // Matrix
  40488. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  40489. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  40490. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  40491. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  40492. var vertexData = new BABYLON.VertexData();
  40493. vertexData.indices = [];
  40494. vertexData.positions = [];
  40495. vertexData.normals = [];
  40496. vertexData.uvs = [];
  40497. var currentVertexDataIndex = 0;
  40498. var extractDecalVector3 = function (indexId) {
  40499. var vertexId = indices[indexId];
  40500. var result = new BABYLON.PositionNormalVertex();
  40501. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  40502. // Send vector to decal local world
  40503. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  40504. // Get normal
  40505. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  40506. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  40507. return result;
  40508. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  40509. var clip = function (vertices, axis) {
  40510. if (vertices.length === 0) {
  40511. return vertices;
  40512. }
  40513. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  40514. var clipVertices = function (v0, v1) {
  40515. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  40516. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  40517. };
  40518. var result = new Array();
  40519. for (var index = 0; index < vertices.length; index += 3) {
  40520. var v1Out;
  40521. var v2Out;
  40522. var v3Out;
  40523. var total = 0;
  40524. var nV1, nV2, nV3, nV4;
  40525. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  40526. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  40527. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  40528. v1Out = d1 > 0;
  40529. v2Out = d2 > 0;
  40530. v3Out = d3 > 0;
  40531. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  40532. switch (total) {
  40533. case 0:
  40534. result.push(vertices[index]);
  40535. result.push(vertices[index + 1]);
  40536. result.push(vertices[index + 2]);
  40537. break;
  40538. case 1:
  40539. if (v1Out) {
  40540. nV1 = vertices[index + 1];
  40541. nV2 = vertices[index + 2];
  40542. nV3 = clipVertices(vertices[index], nV1);
  40543. nV4 = clipVertices(vertices[index], nV2);
  40544. }
  40545. if (v2Out) {
  40546. nV1 = vertices[index];
  40547. nV2 = vertices[index + 2];
  40548. nV3 = clipVertices(vertices[index + 1], nV1);
  40549. nV4 = clipVertices(vertices[index + 1], nV2);
  40550. result.push(nV3);
  40551. result.push(nV2.clone());
  40552. result.push(nV1.clone());
  40553. result.push(nV2.clone());
  40554. result.push(nV3.clone());
  40555. result.push(nV4);
  40556. break;
  40557. }
  40558. if (v3Out) {
  40559. nV1 = vertices[index];
  40560. nV2 = vertices[index + 1];
  40561. nV3 = clipVertices(vertices[index + 2], nV1);
  40562. nV4 = clipVertices(vertices[index + 2], nV2);
  40563. }
  40564. result.push(nV1.clone());
  40565. result.push(nV2.clone());
  40566. result.push(nV3);
  40567. result.push(nV4);
  40568. result.push(nV3.clone());
  40569. result.push(nV2.clone());
  40570. break;
  40571. case 2:
  40572. if (!v1Out) {
  40573. nV1 = vertices[index].clone();
  40574. nV2 = clipVertices(nV1, vertices[index + 1]);
  40575. nV3 = clipVertices(nV1, vertices[index + 2]);
  40576. result.push(nV1);
  40577. result.push(nV2);
  40578. result.push(nV3);
  40579. }
  40580. if (!v2Out) {
  40581. nV1 = vertices[index + 1].clone();
  40582. nV2 = clipVertices(nV1, vertices[index + 2]);
  40583. nV3 = clipVertices(nV1, vertices[index]);
  40584. result.push(nV1);
  40585. result.push(nV2);
  40586. result.push(nV3);
  40587. }
  40588. if (!v3Out) {
  40589. nV1 = vertices[index + 2].clone();
  40590. nV2 = clipVertices(nV1, vertices[index]);
  40591. nV3 = clipVertices(nV1, vertices[index + 1]);
  40592. result.push(nV1);
  40593. result.push(nV2);
  40594. result.push(nV3);
  40595. }
  40596. break;
  40597. case 3:
  40598. break;
  40599. }
  40600. }
  40601. return result;
  40602. };
  40603. for (var index = 0; index < indices.length; index += 3) {
  40604. var faceVertices = new Array();
  40605. faceVertices.push(extractDecalVector3(index));
  40606. faceVertices.push(extractDecalVector3(index + 1));
  40607. faceVertices.push(extractDecalVector3(index + 2));
  40608. // Clip
  40609. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  40610. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  40611. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  40612. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  40613. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  40614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  40615. if (faceVertices.length === 0) {
  40616. continue;
  40617. }
  40618. // Add UVs and get back to world
  40619. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  40620. var vertex = faceVertices[vIndex];
  40621. //TODO check for Int32Array | Uint32Array | Uint16Array
  40622. vertexData.indices.push(currentVertexDataIndex);
  40623. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  40624. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  40625. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  40626. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  40627. currentVertexDataIndex++;
  40628. }
  40629. }
  40630. // Return mesh
  40631. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  40632. vertexData.applyToMesh(decal);
  40633. decal.position = position.clone();
  40634. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  40635. return decal;
  40636. };
  40637. // Privates
  40638. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  40639. // extrusion geometry
  40640. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  40641. var tangents = path3D.getTangents();
  40642. var normals = path3D.getNormals();
  40643. var binormals = path3D.getBinormals();
  40644. var distances = path3D.getDistances();
  40645. var angle = 0;
  40646. var returnScale = function () { return scale; };
  40647. var returnRotation = function () { return rotation; };
  40648. var rotate = custom ? rotateFunction : returnRotation;
  40649. var scl = custom ? scaleFunction : returnScale;
  40650. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40651. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40652. for (var i = 0; i < curve.length; i++) {
  40653. var shapePath = new Array();
  40654. var angleStep = rotate(i, distances[i]);
  40655. var scaleRatio = scl(i, distances[i]);
  40656. for (var p = 0; p < shape.length; p++) {
  40657. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  40658. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  40659. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  40660. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  40661. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40662. shapePath[p] = rotated;
  40663. }
  40664. shapePaths[index] = shapePath;
  40665. angle += angleStep;
  40666. index++;
  40667. }
  40668. // cap
  40669. var capPath = function (shapePath) {
  40670. var pointCap = Array();
  40671. var barycenter = BABYLON.Vector3.Zero();
  40672. var i;
  40673. for (i = 0; i < shapePath.length; i++) {
  40674. barycenter.addInPlace(shapePath[i]);
  40675. }
  40676. barycenter.scaleInPlace(1.0 / shapePath.length);
  40677. for (i = 0; i < shapePath.length; i++) {
  40678. pointCap.push(barycenter);
  40679. }
  40680. return pointCap;
  40681. };
  40682. switch (cap) {
  40683. case BABYLON.Mesh.NO_CAP:
  40684. break;
  40685. case BABYLON.Mesh.CAP_START:
  40686. shapePaths[0] = capPath(shapePaths[2]);
  40687. shapePaths[1] = shapePaths[2];
  40688. break;
  40689. case BABYLON.Mesh.CAP_END:
  40690. shapePaths[index] = shapePaths[index - 1];
  40691. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40692. break;
  40693. case BABYLON.Mesh.CAP_ALL:
  40694. shapePaths[0] = capPath(shapePaths[2]);
  40695. shapePaths[1] = shapePaths[2];
  40696. shapePaths[index] = shapePaths[index - 1];
  40697. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40698. break;
  40699. default:
  40700. break;
  40701. }
  40702. return shapePaths;
  40703. };
  40704. var path3D;
  40705. var pathArray;
  40706. if (instance) {
  40707. path3D = (instance.path3D).update(curve);
  40708. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40709. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40710. return instance;
  40711. }
  40712. // extruded shape creation
  40713. path3D = new BABYLON.Path3D(curve);
  40714. var newShapePaths = new Array();
  40715. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40716. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40717. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40718. extrudedGeneric.pathArray = pathArray;
  40719. extrudedGeneric.path3D = path3D;
  40720. extrudedGeneric.cap = cap;
  40721. return extrudedGeneric;
  40722. };
  40723. return MeshBuilder;
  40724. }());
  40725. BABYLON.MeshBuilder = MeshBuilder;
  40726. })(BABYLON || (BABYLON = {}));
  40727. //# sourceMappingURL=babylon.meshBuilder.js.map
  40728. var BABYLON;
  40729. (function (BABYLON) {
  40730. var Layer = (function () {
  40731. function Layer(name, imgUrl, scene, isBackground, color) {
  40732. this.name = name;
  40733. this.scale = new BABYLON.Vector2(1, 1);
  40734. this.offset = new BABYLON.Vector2(0, 0);
  40735. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40736. this.layerMask = 0x0FFFFFFF;
  40737. this._vertexBuffers = {};
  40738. // Events
  40739. /**
  40740. * An event triggered when the layer is disposed.
  40741. * @type {BABYLON.Observable}
  40742. */
  40743. this.onDisposeObservable = new BABYLON.Observable();
  40744. /**
  40745. * An event triggered before rendering the scene
  40746. * @type {BABYLON.Observable}
  40747. */
  40748. this.onBeforeRenderObservable = new BABYLON.Observable();
  40749. /**
  40750. * An event triggered after rendering the scene
  40751. * @type {BABYLON.Observable}
  40752. */
  40753. this.onAfterRenderObservable = new BABYLON.Observable();
  40754. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40755. this.isBackground = isBackground === undefined ? true : isBackground;
  40756. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40757. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40758. this._scene.layers.push(this);
  40759. var engine = this._scene.getEngine();
  40760. // VBO
  40761. var vertices = [];
  40762. vertices.push(1, 1);
  40763. vertices.push(-1, 1);
  40764. vertices.push(-1, -1);
  40765. vertices.push(1, -1);
  40766. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40767. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40768. this._createIndexBuffer();
  40769. // Effects
  40770. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40771. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40772. }
  40773. Object.defineProperty(Layer.prototype, "onDispose", {
  40774. set: function (callback) {
  40775. if (this._onDisposeObserver) {
  40776. this.onDisposeObservable.remove(this._onDisposeObserver);
  40777. }
  40778. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40779. },
  40780. enumerable: true,
  40781. configurable: true
  40782. });
  40783. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40784. set: function (callback) {
  40785. if (this._onBeforeRenderObserver) {
  40786. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40787. }
  40788. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40789. },
  40790. enumerable: true,
  40791. configurable: true
  40792. });
  40793. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40794. set: function (callback) {
  40795. if (this._onAfterRenderObserver) {
  40796. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40797. }
  40798. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40799. },
  40800. enumerable: true,
  40801. configurable: true
  40802. });
  40803. Layer.prototype._createIndexBuffer = function () {
  40804. var engine = this._scene.getEngine();
  40805. // Indices
  40806. var indices = [];
  40807. indices.push(0);
  40808. indices.push(1);
  40809. indices.push(2);
  40810. indices.push(0);
  40811. indices.push(2);
  40812. indices.push(3);
  40813. this._indexBuffer = engine.createIndexBuffer(indices);
  40814. };
  40815. Layer.prototype._rebuild = function () {
  40816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  40817. this._createIndexBuffer();
  40818. };
  40819. Layer.prototype.render = function () {
  40820. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40821. // Check
  40822. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40823. return;
  40824. var engine = this._scene.getEngine();
  40825. this.onBeforeRenderObservable.notifyObservers(this);
  40826. // Render
  40827. engine.enableEffect(currentEffect);
  40828. engine.setState(false);
  40829. // Texture
  40830. currentEffect.setTexture("textureSampler", this.texture);
  40831. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40832. // Color
  40833. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40834. // Scale / offset
  40835. currentEffect.setVector2("offset", this.offset);
  40836. currentEffect.setVector2("scale", this.scale);
  40837. // VBOs
  40838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40839. // Draw order
  40840. if (!this.alphaTest) {
  40841. engine.setAlphaMode(this.alphaBlendingMode);
  40842. engine.draw(true, 0, 6);
  40843. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40844. }
  40845. else {
  40846. engine.draw(true, 0, 6);
  40847. }
  40848. this.onAfterRenderObservable.notifyObservers(this);
  40849. };
  40850. Layer.prototype.dispose = function () {
  40851. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40852. if (vertexBuffer) {
  40853. vertexBuffer.dispose();
  40854. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40855. }
  40856. if (this._indexBuffer) {
  40857. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40858. this._indexBuffer = null;
  40859. }
  40860. if (this.texture) {
  40861. this.texture.dispose();
  40862. this.texture = null;
  40863. }
  40864. // Remove from scene
  40865. var index = this._scene.layers.indexOf(this);
  40866. this._scene.layers.splice(index, 1);
  40867. // Callback
  40868. this.onDisposeObservable.notifyObservers(this);
  40869. this.onDisposeObservable.clear();
  40870. this.onAfterRenderObservable.clear();
  40871. this.onBeforeRenderObservable.clear();
  40872. };
  40873. return Layer;
  40874. }());
  40875. BABYLON.Layer = Layer;
  40876. })(BABYLON || (BABYLON = {}));
  40877. //# sourceMappingURL=babylon.layer.js.map
  40878. var BABYLON;
  40879. (function (BABYLON) {
  40880. var BlurPostProcess = (function (_super) {
  40881. __extends(BlurPostProcess, _super);
  40882. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40884. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40885. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40886. _this.direction = direction;
  40887. _this._packedFloat = false;
  40888. _this.onApplyObservable.add(function (effect) {
  40889. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40890. });
  40891. _this.kernel = kernel;
  40892. return _this;
  40893. }
  40894. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  40895. /**
  40896. * Gets the length in pixels of the blur sample region
  40897. */
  40898. get: function () {
  40899. return this._idealKernel;
  40900. },
  40901. /**
  40902. * Sets the length in pixels of the blur sample region
  40903. */
  40904. set: function (v) {
  40905. if (this._idealKernel === v) {
  40906. return;
  40907. }
  40908. v = Math.max(v, 1);
  40909. this._idealKernel = v;
  40910. this._kernel = this._nearestBestKernel(v);
  40911. this._updateParameters();
  40912. },
  40913. enumerable: true,
  40914. configurable: true
  40915. });
  40916. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  40917. /**
  40918. * Gets wether or not the blur is unpacking/repacking floats
  40919. */
  40920. get: function () {
  40921. return this._packedFloat;
  40922. },
  40923. /**
  40924. * Sets wether or not the blur needs to unpack/repack floats
  40925. */
  40926. set: function (v) {
  40927. if (this._packedFloat === v) {
  40928. return;
  40929. }
  40930. this._packedFloat = v;
  40931. this._updateParameters();
  40932. },
  40933. enumerable: true,
  40934. configurable: true
  40935. });
  40936. BlurPostProcess.prototype._updateParameters = function () {
  40937. // Generate sampling offsets and weights
  40938. var N = this._kernel;
  40939. var centerIndex = (N - 1) / 2;
  40940. // Generate Gaussian sampling weights over kernel
  40941. var offsets = [];
  40942. var weights = [];
  40943. var totalWeight = 0;
  40944. for (var i = 0; i < N; i++) {
  40945. var u = i / (N - 1);
  40946. var w = this._gaussianWeight(u * 2.0 - 1);
  40947. offsets[i] = (i - centerIndex);
  40948. weights[i] = w;
  40949. totalWeight += w;
  40950. }
  40951. // Normalize weights
  40952. for (var i = 0; i < weights.length; i++) {
  40953. weights[i] /= totalWeight;
  40954. }
  40955. // Optimize: combine samples to take advantage of hardware linear sampling
  40956. // Walk from left to center, combining pairs (symmetrically)
  40957. var linearSamplingWeights = [];
  40958. var linearSamplingOffsets = [];
  40959. var linearSamplingMap = [];
  40960. for (var i = 0; i <= centerIndex; i += 2) {
  40961. var j = Math.min(i + 1, Math.floor(centerIndex));
  40962. var singleCenterSample = i === j;
  40963. if (singleCenterSample) {
  40964. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40965. }
  40966. else {
  40967. var sharedCell = j === centerIndex;
  40968. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  40969. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  40970. if (offsetLinear === 0) {
  40971. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40972. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  40973. }
  40974. else {
  40975. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  40976. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  40977. }
  40978. }
  40979. }
  40980. for (var i = 0; i < linearSamplingMap.length; i++) {
  40981. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  40982. linearSamplingWeights[i] = linearSamplingMap[i].w;
  40983. }
  40984. // Replace with optimized
  40985. offsets = linearSamplingOffsets;
  40986. weights = linearSamplingWeights;
  40987. // Generate shaders
  40988. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  40989. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  40990. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  40991. var defines = "";
  40992. for (var i = 0; i < varyingCount; i++) {
  40993. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  40994. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  40995. }
  40996. var depCount = 0;
  40997. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  40998. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  40999. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  41000. depCount++;
  41001. }
  41002. if (this.packedFloat) {
  41003. defines += "#define PACKEDFLOAT 1";
  41004. }
  41005. this.updateEffect(defines, null, null, {
  41006. varyingCount: varyingCount,
  41007. depCount: depCount
  41008. });
  41009. };
  41010. /**
  41011. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  41012. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41013. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41014. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41015. * The gaps between physical kernels are compensated for in the weighting of the samples
  41016. * @param idealKernel Ideal blur kernel.
  41017. * @return Nearest best kernel.
  41018. */
  41019. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41020. var v = Math.round(idealKernel);
  41021. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41022. var k = _a[_i];
  41023. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41024. return Math.max(k, 3);
  41025. }
  41026. }
  41027. return Math.max(v, 3);
  41028. };
  41029. /**
  41030. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41031. * @param x The point on the Gaussian distribution to sample.
  41032. * @return the value of the Gaussian function at x.
  41033. */
  41034. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41035. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41036. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41037. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41038. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41039. // truncated at around 1.3% of peak strength.
  41040. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41041. var sigma = (1 / 3);
  41042. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41043. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41044. var weight = (1.0 / denominator) * Math.exp(exponent);
  41045. return weight;
  41046. };
  41047. /**
  41048. * Generates a string that can be used as a floating point number in GLSL.
  41049. * @param x Value to print.
  41050. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41051. * @return GLSL float string.
  41052. */
  41053. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41054. if (decimalFigures === void 0) { decimalFigures = 8; }
  41055. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41056. };
  41057. return BlurPostProcess;
  41058. }(BABYLON.PostProcess));
  41059. BABYLON.BlurPostProcess = BlurPostProcess;
  41060. })(BABYLON || (BABYLON = {}));
  41061. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41062. var BABYLON;
  41063. (function (BABYLON) {
  41064. var FxaaPostProcess = (function (_super) {
  41065. __extends(FxaaPostProcess, _super);
  41066. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41067. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41068. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  41069. _this.onApplyObservable.add(function (effect) {
  41070. var texelSize = _this.texelSize;
  41071. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41072. });
  41073. return _this;
  41074. }
  41075. return FxaaPostProcess;
  41076. }(BABYLON.PostProcess));
  41077. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41078. })(BABYLON || (BABYLON = {}));
  41079. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41080. var BABYLON;
  41081. (function (BABYLON) {
  41082. var HighlightsPostProcess = (function (_super) {
  41083. __extends(HighlightsPostProcess, _super);
  41084. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41085. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41086. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41087. }
  41088. return HighlightsPostProcess;
  41089. }(BABYLON.PostProcess));
  41090. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41091. })(BABYLON || (BABYLON = {}));
  41092. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41093. var BABYLON;
  41094. (function (BABYLON) {
  41095. var ImageProcessingPostProcess = (function (_super) {
  41096. __extends(ImageProcessingPostProcess, _super);
  41097. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41098. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41099. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41100. _this._fromLinearSpace = true;
  41101. /**
  41102. * Defines cache preventing GC.
  41103. */
  41104. _this._defines = {
  41105. IMAGEPROCESSING: false,
  41106. VIGNETTE: false,
  41107. VIGNETTEBLENDMODEMULTIPLY: false,
  41108. VIGNETTEBLENDMODEOPAQUE: false,
  41109. TONEMAPPING: false,
  41110. CONTRAST: false,
  41111. COLORCURVES: false,
  41112. COLORGRADING: false,
  41113. FROMLINEARSPACE: false,
  41114. SAMPLER3DGREENDEPTH: false,
  41115. SAMPLER3DBGRMAP: false,
  41116. IMAGEPROCESSINGPOSTPROCESS: false,
  41117. EXPOSURE: false,
  41118. };
  41119. // Setup the default processing configuration to the scene.
  41120. _this._attachImageProcessingConfiguration(null, true);
  41121. _this.imageProcessingConfiguration.applyByPostProcess = true;
  41122. _this.onApply = function (effect) {
  41123. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  41124. };
  41125. return _this;
  41126. }
  41127. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  41128. /**
  41129. * Gets the image processing configuration used either in this material.
  41130. */
  41131. get: function () {
  41132. return this._imageProcessingConfiguration;
  41133. },
  41134. /**
  41135. * Sets the Default image processing configuration used either in the this material.
  41136. *
  41137. * If sets to null, the scene one is in use.
  41138. */
  41139. set: function (value) {
  41140. this._attachImageProcessingConfiguration(value);
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. /**
  41146. * Attaches a new image processing configuration to the PBR Material.
  41147. * @param configuration
  41148. */
  41149. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  41150. var _this = this;
  41151. if (doNotBuild === void 0) { doNotBuild = false; }
  41152. if (configuration === this._imageProcessingConfiguration) {
  41153. return;
  41154. }
  41155. // Detaches observer.
  41156. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41157. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41158. }
  41159. // Pick the scene configuration if needed.
  41160. if (!configuration) {
  41161. var camera = this.getCamera();
  41162. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  41163. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  41164. }
  41165. else {
  41166. this._imageProcessingConfiguration = configuration;
  41167. }
  41168. // Attaches observer.
  41169. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41170. _this._updateParameters();
  41171. });
  41172. // Ensure the effect will be rebuilt.
  41173. if (!doNotBuild) {
  41174. this._updateParameters();
  41175. }
  41176. };
  41177. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  41178. /**
  41179. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41180. */
  41181. get: function () {
  41182. return this.imageProcessingConfiguration.colorCurves;
  41183. },
  41184. /**
  41185. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41186. */
  41187. set: function (value) {
  41188. this.imageProcessingConfiguration.colorCurves = value;
  41189. },
  41190. enumerable: true,
  41191. configurable: true
  41192. });
  41193. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41194. /**
  41195. * Gets wether the color curves effect is enabled.
  41196. */
  41197. get: function () {
  41198. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41199. },
  41200. /**
  41201. * Sets wether the color curves effect is enabled.
  41202. */
  41203. set: function (value) {
  41204. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41205. },
  41206. enumerable: true,
  41207. configurable: true
  41208. });
  41209. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41210. /**
  41211. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41212. */
  41213. get: function () {
  41214. return this.imageProcessingConfiguration.colorGradingTexture;
  41215. },
  41216. /**
  41217. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41218. */
  41219. set: function (value) {
  41220. this.imageProcessingConfiguration.colorGradingTexture = value;
  41221. },
  41222. enumerable: true,
  41223. configurable: true
  41224. });
  41225. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  41226. /**
  41227. * Gets wether the color grading effect is enabled.
  41228. */
  41229. get: function () {
  41230. return this.imageProcessingConfiguration.colorGradingEnabled;
  41231. },
  41232. /**
  41233. * Gets wether the color grading effect is enabled.
  41234. */
  41235. set: function (value) {
  41236. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41237. },
  41238. enumerable: true,
  41239. configurable: true
  41240. });
  41241. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  41242. /**
  41243. * Gets exposure used in the effect.
  41244. */
  41245. get: function () {
  41246. return this.imageProcessingConfiguration.exposure;
  41247. },
  41248. /**
  41249. * Sets exposure used in the effect.
  41250. */
  41251. set: function (value) {
  41252. this.imageProcessingConfiguration.exposure = value;
  41253. },
  41254. enumerable: true,
  41255. configurable: true
  41256. });
  41257. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  41258. /**
  41259. * Gets wether tonemapping is enabled or not.
  41260. */
  41261. get: function () {
  41262. return this._imageProcessingConfiguration.toneMappingEnabled;
  41263. },
  41264. /**
  41265. * Sets wether tonemapping is enabled or not
  41266. */
  41267. set: function (value) {
  41268. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41269. },
  41270. enumerable: true,
  41271. configurable: true
  41272. });
  41273. ;
  41274. ;
  41275. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  41276. /**
  41277. * Gets contrast used in the effect.
  41278. */
  41279. get: function () {
  41280. return this.imageProcessingConfiguration.contrast;
  41281. },
  41282. /**
  41283. * Sets contrast used in the effect.
  41284. */
  41285. set: function (value) {
  41286. this.imageProcessingConfiguration.contrast = value;
  41287. },
  41288. enumerable: true,
  41289. configurable: true
  41290. });
  41291. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  41292. /**
  41293. * Gets Vignette stretch size.
  41294. */
  41295. get: function () {
  41296. return this.imageProcessingConfiguration.vignetteStretch;
  41297. },
  41298. /**
  41299. * Sets Vignette stretch size.
  41300. */
  41301. set: function (value) {
  41302. this.imageProcessingConfiguration.vignetteStretch = value;
  41303. },
  41304. enumerable: true,
  41305. configurable: true
  41306. });
  41307. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  41308. /**
  41309. * Gets Vignette centre X Offset.
  41310. */
  41311. get: function () {
  41312. return this.imageProcessingConfiguration.vignetteCentreX;
  41313. },
  41314. /**
  41315. * Sets Vignette centre X Offset.
  41316. */
  41317. set: function (value) {
  41318. this.imageProcessingConfiguration.vignetteCentreX = value;
  41319. },
  41320. enumerable: true,
  41321. configurable: true
  41322. });
  41323. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  41324. /**
  41325. * Gets Vignette centre Y Offset.
  41326. */
  41327. get: function () {
  41328. return this.imageProcessingConfiguration.vignetteCentreY;
  41329. },
  41330. /**
  41331. * Sets Vignette centre Y Offset.
  41332. */
  41333. set: function (value) {
  41334. this.imageProcessingConfiguration.vignetteCentreY = value;
  41335. },
  41336. enumerable: true,
  41337. configurable: true
  41338. });
  41339. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  41340. /**
  41341. * Gets Vignette weight or intensity of the vignette effect.
  41342. */
  41343. get: function () {
  41344. return this.imageProcessingConfiguration.vignetteWeight;
  41345. },
  41346. /**
  41347. * Sets Vignette weight or intensity of the vignette effect.
  41348. */
  41349. set: function (value) {
  41350. this.imageProcessingConfiguration.vignetteWeight = value;
  41351. },
  41352. enumerable: true,
  41353. configurable: true
  41354. });
  41355. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  41356. /**
  41357. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41358. * if vignetteEnabled is set to true.
  41359. */
  41360. get: function () {
  41361. return this.imageProcessingConfiguration.vignetteColor;
  41362. },
  41363. /**
  41364. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41365. * if vignetteEnabled is set to true.
  41366. */
  41367. set: function (value) {
  41368. this.imageProcessingConfiguration.vignetteColor = value;
  41369. },
  41370. enumerable: true,
  41371. configurable: true
  41372. });
  41373. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  41374. /**
  41375. * Gets Camera field of view used by the Vignette effect.
  41376. */
  41377. get: function () {
  41378. return this.imageProcessingConfiguration.vignetteCameraFov;
  41379. },
  41380. /**
  41381. * Sets Camera field of view used by the Vignette effect.
  41382. */
  41383. set: function (value) {
  41384. this.imageProcessingConfiguration.vignetteCameraFov = value;
  41385. },
  41386. enumerable: true,
  41387. configurable: true
  41388. });
  41389. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41390. /**
  41391. * Gets the vignette blend mode allowing different kind of effect.
  41392. */
  41393. get: function () {
  41394. return this.imageProcessingConfiguration.vignetteBlendMode;
  41395. },
  41396. /**
  41397. * Sets the vignette blend mode allowing different kind of effect.
  41398. */
  41399. set: function (value) {
  41400. this.imageProcessingConfiguration.vignetteBlendMode = value;
  41401. },
  41402. enumerable: true,
  41403. configurable: true
  41404. });
  41405. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41406. /**
  41407. * Gets wether the vignette effect is enabled.
  41408. */
  41409. get: function () {
  41410. return this.imageProcessingConfiguration.vignetteEnabled;
  41411. },
  41412. /**
  41413. * Sets wether the vignette effect is enabled.
  41414. */
  41415. set: function (value) {
  41416. this.imageProcessingConfiguration.vignetteEnabled = value;
  41417. },
  41418. enumerable: true,
  41419. configurable: true
  41420. });
  41421. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41422. /**
  41423. * Gets wether the input of the processing is in Gamma or Linear Space.
  41424. */
  41425. get: function () {
  41426. return this._fromLinearSpace;
  41427. },
  41428. /**
  41429. * Sets wether the input of the processing is in Gamma or Linear Space.
  41430. */
  41431. set: function (value) {
  41432. if (this._fromLinearSpace === value) {
  41433. return;
  41434. }
  41435. this._fromLinearSpace = value;
  41436. this._updateParameters();
  41437. },
  41438. enumerable: true,
  41439. configurable: true
  41440. });
  41441. ImageProcessingPostProcess.prototype.getClassName = function () {
  41442. return "ImageProcessingPostProcess";
  41443. };
  41444. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41445. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  41446. this.imageProcessingConfiguration.prepareDefines(this._defines);
  41447. var defines = "";
  41448. for (var define in this._defines) {
  41449. if (this._defines[define]) {
  41450. defines += "#define " + define + ";\r\n";
  41451. }
  41452. }
  41453. var samplers = ["textureSampler"];
  41454. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  41455. var uniforms = ["scale"];
  41456. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  41457. this.updateEffect(defines, uniforms, samplers);
  41458. };
  41459. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  41460. _super.prototype.dispose.call(this, camera);
  41461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41463. }
  41464. this.imageProcessingConfiguration.applyByPostProcess = false;
  41465. };
  41466. __decorate([
  41467. BABYLON.serialize()
  41468. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  41469. return ImageProcessingPostProcess;
  41470. }(BABYLON.PostProcess));
  41471. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41472. })(BABYLON || (BABYLON = {}));
  41473. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41474. var BABYLON;
  41475. (function (BABYLON) {
  41476. /**
  41477. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41478. * It can help converting any input color in a desired output one. This can then be used to create effects
  41479. * from sepia, black and white to sixties or futuristic rendering...
  41480. *
  41481. * The only supported format is currently 3dl.
  41482. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41483. */
  41484. var ColorGradingTexture = (function (_super) {
  41485. __extends(ColorGradingTexture, _super);
  41486. /**
  41487. * Instantiates a ColorGradingTexture from the following parameters.
  41488. *
  41489. * @param url The location of the color gradind data (currently only supporting 3dl)
  41490. * @param scene The scene the texture will be used in
  41491. */
  41492. function ColorGradingTexture(url, scene) {
  41493. var _this = _super.call(this, scene) || this;
  41494. if (!url) {
  41495. return _this;
  41496. }
  41497. _this._textureMatrix = BABYLON.Matrix.Identity();
  41498. _this.name = url;
  41499. _this.url = url;
  41500. _this.hasAlpha = false;
  41501. _this.isCube = false;
  41502. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41503. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41504. _this.anisotropicFilteringLevel = 1;
  41505. _this._texture = _this._getFromCache(url, true);
  41506. if (!_this._texture) {
  41507. if (!scene.useDelayedTextureLoading) {
  41508. _this.loadTexture();
  41509. }
  41510. else {
  41511. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41512. }
  41513. }
  41514. return _this;
  41515. }
  41516. /**
  41517. * Returns the texture matrix used in most of the material.
  41518. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41519. */
  41520. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41521. return this._textureMatrix;
  41522. };
  41523. /**
  41524. * Occurs when the file being loaded is a .3dl LUT file.
  41525. */
  41526. ColorGradingTexture.prototype.load3dlTexture = function () {
  41527. var _this = this;
  41528. var mipLevels = 0;
  41529. var floatArrayView = null;
  41530. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41531. this._texture = texture;
  41532. var callback = function (text) {
  41533. var data;
  41534. var tempData;
  41535. var line;
  41536. var lines = text.split('\n');
  41537. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41538. var maxColor = 0;
  41539. for (var i = 0; i < lines.length; i++) {
  41540. line = lines[i];
  41541. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41542. continue;
  41543. if (line.indexOf('#') === 0)
  41544. continue;
  41545. var words = line.split(" ");
  41546. if (size === 0) {
  41547. // Number of space + one
  41548. size = words.length;
  41549. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41550. tempData = new Float32Array(size * size * size * 4);
  41551. continue;
  41552. }
  41553. if (size != 0) {
  41554. var r = Math.max(parseInt(words[0]), 0);
  41555. var g = Math.max(parseInt(words[1]), 0);
  41556. var b = Math.max(parseInt(words[2]), 0);
  41557. maxColor = Math.max(r, maxColor);
  41558. maxColor = Math.max(g, maxColor);
  41559. maxColor = Math.max(b, maxColor);
  41560. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41561. tempData[pixelStorageIndex + 0] = r;
  41562. tempData[pixelStorageIndex + 1] = g;
  41563. tempData[pixelStorageIndex + 2] = b;
  41564. pixelIndexSlice++;
  41565. if (pixelIndexSlice % size == 0) {
  41566. pixelIndexH++;
  41567. pixelIndexSlice = 0;
  41568. if (pixelIndexH % size == 0) {
  41569. pixelIndexW++;
  41570. pixelIndexH = 0;
  41571. }
  41572. }
  41573. }
  41574. }
  41575. for (var i = 0; i < tempData.length; i++) {
  41576. if (i > 0 && (i + 1) % 4 === 0) {
  41577. data[i] = 255;
  41578. }
  41579. else {
  41580. var value = tempData[i];
  41581. data[i] = (value / maxColor * 255);
  41582. }
  41583. }
  41584. texture.updateSize(size * size, size);
  41585. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41586. };
  41587. BABYLON.Tools.LoadFile(this.url, callback);
  41588. return this._texture;
  41589. };
  41590. /**
  41591. * Starts the loading process of the texture.
  41592. */
  41593. ColorGradingTexture.prototype.loadTexture = function () {
  41594. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41595. this.load3dlTexture();
  41596. }
  41597. };
  41598. /**
  41599. * Clones the color gradind texture.
  41600. */
  41601. ColorGradingTexture.prototype.clone = function () {
  41602. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41603. // Base texture
  41604. newTexture.level = this.level;
  41605. return newTexture;
  41606. };
  41607. /**
  41608. * Called during delayed load for textures.
  41609. */
  41610. ColorGradingTexture.prototype.delayLoad = function () {
  41611. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41612. return;
  41613. }
  41614. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41615. this._texture = this._getFromCache(this.url, true);
  41616. if (!this._texture) {
  41617. this.loadTexture();
  41618. }
  41619. };
  41620. /**
  41621. * Parses a color grading texture serialized by Babylon.
  41622. * @param parsedTexture The texture information being parsedTexture
  41623. * @param scene The scene to load the texture in
  41624. * @param rootUrl The root url of the data assets to load
  41625. * @return A color gradind texture
  41626. */
  41627. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41628. var texture = null;
  41629. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41630. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41631. texture.name = parsedTexture.name;
  41632. texture.level = parsedTexture.level;
  41633. }
  41634. return texture;
  41635. };
  41636. /**
  41637. * Serializes the LUT texture to json format.
  41638. */
  41639. ColorGradingTexture.prototype.serialize = function () {
  41640. if (!this.name) {
  41641. return null;
  41642. }
  41643. var serializationObject = {};
  41644. serializationObject.name = this.name;
  41645. serializationObject.level = this.level;
  41646. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41647. return serializationObject;
  41648. };
  41649. /**
  41650. * Empty line regex stored for GC.
  41651. */
  41652. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41653. return ColorGradingTexture;
  41654. }(BABYLON.BaseTexture));
  41655. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41656. })(BABYLON || (BABYLON = {}));
  41657. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41658. var BABYLON;
  41659. (function (BABYLON) {
  41660. /**
  41661. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41662. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41663. * 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;
  41664. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41665. */
  41666. var ColorCurves = (function () {
  41667. function ColorCurves() {
  41668. this._dirty = true;
  41669. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41670. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41671. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41672. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41673. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41674. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41675. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41676. this._globalHue = 30;
  41677. this._globalDensity = 0;
  41678. this._globalSaturation = 0;
  41679. this._globalExposure = 0;
  41680. this._highlightsHue = 30;
  41681. this._highlightsDensity = 0;
  41682. this._highlightsSaturation = 0;
  41683. this._highlightsExposure = 0;
  41684. this._midtonesHue = 30;
  41685. this._midtonesDensity = 0;
  41686. this._midtonesSaturation = 0;
  41687. this._midtonesExposure = 0;
  41688. this._shadowsHue = 30;
  41689. this._shadowsDensity = 0;
  41690. this._shadowsSaturation = 0;
  41691. this._shadowsExposure = 0;
  41692. }
  41693. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41694. /**
  41695. * Gets the global Hue value.
  41696. * 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).
  41697. */
  41698. get: function () {
  41699. return this._globalHue;
  41700. },
  41701. /**
  41702. * Sets the global Hue value.
  41703. * 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).
  41704. */
  41705. set: function (value) {
  41706. this._globalHue = value;
  41707. this._dirty = true;
  41708. },
  41709. enumerable: true,
  41710. configurable: true
  41711. });
  41712. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41713. /**
  41714. * Gets the global Density value.
  41715. * 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.
  41716. * Values less than zero provide a filter of opposite hue.
  41717. */
  41718. get: function () {
  41719. return this._globalDensity;
  41720. },
  41721. /**
  41722. * Sets the global Density value.
  41723. * 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.
  41724. * Values less than zero provide a filter of opposite hue.
  41725. */
  41726. set: function (value) {
  41727. this._globalDensity = value;
  41728. this._dirty = true;
  41729. },
  41730. enumerable: true,
  41731. configurable: true
  41732. });
  41733. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41734. /**
  41735. * Gets the global Saturation value.
  41736. * 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.
  41737. */
  41738. get: function () {
  41739. return this._globalSaturation;
  41740. },
  41741. /**
  41742. * Sets the global Saturation value.
  41743. * 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.
  41744. */
  41745. set: function (value) {
  41746. this._globalSaturation = value;
  41747. this._dirty = true;
  41748. },
  41749. enumerable: true,
  41750. configurable: true
  41751. });
  41752. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41753. /**
  41754. * Gets the highlights Hue value.
  41755. * 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).
  41756. */
  41757. get: function () {
  41758. return this._highlightsHue;
  41759. },
  41760. /**
  41761. * Sets the highlights Hue value.
  41762. * 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).
  41763. */
  41764. set: function (value) {
  41765. this._highlightsHue = value;
  41766. this._dirty = true;
  41767. },
  41768. enumerable: true,
  41769. configurable: true
  41770. });
  41771. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41772. /**
  41773. * Gets the highlights Density value.
  41774. * 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.
  41775. * Values less than zero provide a filter of opposite hue.
  41776. */
  41777. get: function () {
  41778. return this._highlightsDensity;
  41779. },
  41780. /**
  41781. * Sets the highlights Density value.
  41782. * 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.
  41783. * Values less than zero provide a filter of opposite hue.
  41784. */
  41785. set: function (value) {
  41786. this._highlightsDensity = value;
  41787. this._dirty = true;
  41788. },
  41789. enumerable: true,
  41790. configurable: true
  41791. });
  41792. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41793. /**
  41794. * Gets the highlights Saturation value.
  41795. * 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.
  41796. */
  41797. get: function () {
  41798. return this._highlightsSaturation;
  41799. },
  41800. /**
  41801. * Sets the highlights Saturation value.
  41802. * 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.
  41803. */
  41804. set: function (value) {
  41805. this._highlightsSaturation = value;
  41806. this._dirty = true;
  41807. },
  41808. enumerable: true,
  41809. configurable: true
  41810. });
  41811. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41812. /**
  41813. * Gets the highlights Exposure value.
  41814. * 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.
  41815. */
  41816. get: function () {
  41817. return this._highlightsExposure;
  41818. },
  41819. /**
  41820. * Sets the highlights Exposure value.
  41821. * 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.
  41822. */
  41823. set: function (value) {
  41824. this._highlightsExposure = value;
  41825. this._dirty = true;
  41826. },
  41827. enumerable: true,
  41828. configurable: true
  41829. });
  41830. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41831. /**
  41832. * Gets the midtones Hue value.
  41833. * 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).
  41834. */
  41835. get: function () {
  41836. return this._midtonesHue;
  41837. },
  41838. /**
  41839. * Sets the midtones Hue value.
  41840. * 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).
  41841. */
  41842. set: function (value) {
  41843. this._midtonesHue = value;
  41844. this._dirty = true;
  41845. },
  41846. enumerable: true,
  41847. configurable: true
  41848. });
  41849. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41850. /**
  41851. * Gets the midtones Density value.
  41852. * 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.
  41853. * Values less than zero provide a filter of opposite hue.
  41854. */
  41855. get: function () {
  41856. return this._midtonesDensity;
  41857. },
  41858. /**
  41859. * Sets the midtones Density value.
  41860. * 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.
  41861. * Values less than zero provide a filter of opposite hue.
  41862. */
  41863. set: function (value) {
  41864. this._midtonesDensity = value;
  41865. this._dirty = true;
  41866. },
  41867. enumerable: true,
  41868. configurable: true
  41869. });
  41870. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41871. /**
  41872. * Gets the midtones Saturation value.
  41873. * 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.
  41874. */
  41875. get: function () {
  41876. return this._midtonesSaturation;
  41877. },
  41878. /**
  41879. * Sets the midtones Saturation value.
  41880. * 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.
  41881. */
  41882. set: function (value) {
  41883. this._midtonesSaturation = value;
  41884. this._dirty = true;
  41885. },
  41886. enumerable: true,
  41887. configurable: true
  41888. });
  41889. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41890. /**
  41891. * Gets the midtones Exposure value.
  41892. * 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.
  41893. */
  41894. get: function () {
  41895. return this._midtonesExposure;
  41896. },
  41897. /**
  41898. * Sets the midtones Exposure value.
  41899. * 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.
  41900. */
  41901. set: function (value) {
  41902. this._midtonesExposure = value;
  41903. this._dirty = true;
  41904. },
  41905. enumerable: true,
  41906. configurable: true
  41907. });
  41908. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41909. /**
  41910. * Gets the shadows Hue value.
  41911. * 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).
  41912. */
  41913. get: function () {
  41914. return this._shadowsHue;
  41915. },
  41916. /**
  41917. * Sets the shadows Hue value.
  41918. * 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).
  41919. */
  41920. set: function (value) {
  41921. this._shadowsHue = value;
  41922. this._dirty = true;
  41923. },
  41924. enumerable: true,
  41925. configurable: true
  41926. });
  41927. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41928. /**
  41929. * Gets the shadows Density value.
  41930. * 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.
  41931. * Values less than zero provide a filter of opposite hue.
  41932. */
  41933. get: function () {
  41934. return this._shadowsDensity;
  41935. },
  41936. /**
  41937. * Sets the shadows Density value.
  41938. * 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.
  41939. * Values less than zero provide a filter of opposite hue.
  41940. */
  41941. set: function (value) {
  41942. this._shadowsDensity = value;
  41943. this._dirty = true;
  41944. },
  41945. enumerable: true,
  41946. configurable: true
  41947. });
  41948. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41949. /**
  41950. * Gets the shadows Saturation value.
  41951. * 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.
  41952. */
  41953. get: function () {
  41954. return this._shadowsSaturation;
  41955. },
  41956. /**
  41957. * Sets the shadows Saturation value.
  41958. * 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.
  41959. */
  41960. set: function (value) {
  41961. this._shadowsSaturation = value;
  41962. this._dirty = true;
  41963. },
  41964. enumerable: true,
  41965. configurable: true
  41966. });
  41967. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41968. /**
  41969. * Gets the shadows Exposure value.
  41970. * 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.
  41971. */
  41972. get: function () {
  41973. return this._shadowsExposure;
  41974. },
  41975. /**
  41976. * Sets the shadows Exposure value.
  41977. * 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.
  41978. */
  41979. set: function (value) {
  41980. this._shadowsExposure = value;
  41981. this._dirty = true;
  41982. },
  41983. enumerable: true,
  41984. configurable: true
  41985. });
  41986. ColorCurves.prototype.getClassName = function () {
  41987. return "ColorCurves";
  41988. };
  41989. /**
  41990. * Binds the color curves to the shader.
  41991. * @param colorCurves The color curve to bind
  41992. * @param effect The effect to bind to
  41993. */
  41994. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41995. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41996. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41997. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41998. if (colorCurves._dirty) {
  41999. colorCurves._dirty = false;
  42000. // Fill in global info.
  42001. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42002. // Compute highlights info.
  42003. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42004. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42005. // Compute midtones info.
  42006. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42007. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42008. // Compute shadows info.
  42009. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42010. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42011. // Compute deltas (neutral is midtones).
  42012. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42013. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42014. }
  42015. if (effect) {
  42016. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42017. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42018. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42019. }
  42020. };
  42021. /**
  42022. * Prepare the list of uniforms associated with the ColorCurves effects.
  42023. * @param uniformsList The list of uniforms used in the effect
  42024. */
  42025. ColorCurves.PrepareUniforms = function (uniformsList) {
  42026. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42027. };
  42028. /**
  42029. * Returns color grading data based on a hue, density, saturation and exposure value.
  42030. * @param filterHue The hue of the color filter.
  42031. * @param filterDensity The density of the color filter.
  42032. * @param saturation The saturation.
  42033. * @param exposure The exposure.
  42034. * @param result The result data container.
  42035. */
  42036. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42037. if (hue == null) {
  42038. return;
  42039. }
  42040. hue = ColorCurves.clamp(hue, 0, 360);
  42041. density = ColorCurves.clamp(density, -100, 100);
  42042. saturation = ColorCurves.clamp(saturation, -100, 100);
  42043. exposure = ColorCurves.clamp(exposure, -100, 100);
  42044. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42045. // so that the maximum filter density is only 50% control. This provides fine control
  42046. // for small values and reasonable range.
  42047. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42048. density *= 0.5;
  42049. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42050. if (density < 0) {
  42051. density *= -1;
  42052. hue = (hue + 180) % 360;
  42053. }
  42054. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42055. result.scaleToRef(2, result);
  42056. result.a = 1 + 0.01 * saturation;
  42057. };
  42058. /**
  42059. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42060. * @param value The input slider value in range [-100,100].
  42061. * @returns Adjusted value.
  42062. */
  42063. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42064. value /= 100;
  42065. var x = Math.abs(value);
  42066. x = Math.pow(x, 2);
  42067. if (value < 0) {
  42068. x *= -1;
  42069. }
  42070. x *= 100;
  42071. return x;
  42072. };
  42073. /**
  42074. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42075. * @param hue The hue (H) input.
  42076. * @param saturation The saturation (S) input.
  42077. * @param brightness The brightness (B) input.
  42078. * @result An RGBA color represented as Vector4.
  42079. */
  42080. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42081. var h = ColorCurves.clamp(hue, 0, 360);
  42082. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42083. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42084. if (s === 0) {
  42085. result.r = v;
  42086. result.g = v;
  42087. result.b = v;
  42088. }
  42089. else {
  42090. // sector 0 to 5
  42091. h /= 60;
  42092. var i = Math.floor(h);
  42093. // fractional part of h
  42094. var f = h - i;
  42095. var p = v * (1 - s);
  42096. var q = v * (1 - s * f);
  42097. var t = v * (1 - s * (1 - f));
  42098. switch (i) {
  42099. case 0:
  42100. result.r = v;
  42101. result.g = t;
  42102. result.b = p;
  42103. break;
  42104. case 1:
  42105. result.r = q;
  42106. result.g = v;
  42107. result.b = p;
  42108. break;
  42109. case 2:
  42110. result.r = p;
  42111. result.g = v;
  42112. result.b = t;
  42113. break;
  42114. case 3:
  42115. result.r = p;
  42116. result.g = q;
  42117. result.b = v;
  42118. break;
  42119. case 4:
  42120. result.r = t;
  42121. result.g = p;
  42122. result.b = v;
  42123. break;
  42124. default:// case 5:
  42125. result.r = v;
  42126. result.g = p;
  42127. result.b = q;
  42128. break;
  42129. }
  42130. }
  42131. result.a = 1;
  42132. };
  42133. /**
  42134. * Returns a value clamped between min and max
  42135. * @param value The value to clamp
  42136. * @param min The minimum of value
  42137. * @param max The maximum of value
  42138. * @returns The clamped value.
  42139. */
  42140. ColorCurves.clamp = function (value, min, max) {
  42141. return Math.min(Math.max(value, min), max);
  42142. };
  42143. /**
  42144. * Clones the current color curve instance.
  42145. * @return The cloned curves
  42146. */
  42147. ColorCurves.prototype.clone = function () {
  42148. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42149. };
  42150. /**
  42151. * Serializes the current color curve instance to a json representation.
  42152. * @return a JSON representation
  42153. */
  42154. ColorCurves.prototype.serialize = function () {
  42155. return BABYLON.SerializationHelper.Serialize(this);
  42156. };
  42157. /**
  42158. * Parses the color curve from a json representation.
  42159. * @param source the JSON source to parse
  42160. * @return The parsed curves
  42161. */
  42162. ColorCurves.Parse = function (source) {
  42163. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42164. };
  42165. __decorate([
  42166. BABYLON.serialize()
  42167. ], ColorCurves.prototype, "_globalHue", void 0);
  42168. __decorate([
  42169. BABYLON.serialize()
  42170. ], ColorCurves.prototype, "_globalDensity", void 0);
  42171. __decorate([
  42172. BABYLON.serialize()
  42173. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42174. __decorate([
  42175. BABYLON.serialize()
  42176. ], ColorCurves.prototype, "_globalExposure", void 0);
  42177. __decorate([
  42178. BABYLON.serialize()
  42179. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42180. __decorate([
  42181. BABYLON.serialize()
  42182. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42183. __decorate([
  42184. BABYLON.serialize()
  42185. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42186. __decorate([
  42187. BABYLON.serialize()
  42188. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42189. __decorate([
  42190. BABYLON.serialize()
  42191. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42192. __decorate([
  42193. BABYLON.serialize()
  42194. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42195. __decorate([
  42196. BABYLON.serialize()
  42197. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42198. __decorate([
  42199. BABYLON.serialize()
  42200. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42201. return ColorCurves;
  42202. }());
  42203. BABYLON.ColorCurves = ColorCurves;
  42204. })(BABYLON || (BABYLON = {}));
  42205. //# sourceMappingURL=babylon.colorCurves.js.map
  42206. var BABYLON;
  42207. (function (BABYLON) {
  42208. var PostProcessRenderPipelineManager = (function () {
  42209. function PostProcessRenderPipelineManager() {
  42210. this._renderPipelines = {};
  42211. }
  42212. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42213. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42214. };
  42215. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42216. var renderPipeline = this._renderPipelines[renderPipelineName];
  42217. if (!renderPipeline) {
  42218. return;
  42219. }
  42220. renderPipeline._attachCameras(cameras, unique);
  42221. };
  42222. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42223. var renderPipeline = this._renderPipelines[renderPipelineName];
  42224. if (!renderPipeline) {
  42225. return;
  42226. }
  42227. renderPipeline._detachCameras(cameras);
  42228. };
  42229. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42230. var renderPipeline = this._renderPipelines[renderPipelineName];
  42231. if (!renderPipeline) {
  42232. return;
  42233. }
  42234. renderPipeline._enableEffect(renderEffectName, cameras);
  42235. };
  42236. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42237. var renderPipeline = this._renderPipelines[renderPipelineName];
  42238. if (!renderPipeline) {
  42239. return;
  42240. }
  42241. renderPipeline._disableEffect(renderEffectName, cameras);
  42242. };
  42243. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42244. var renderPipeline = this._renderPipelines[renderPipelineName];
  42245. if (!renderPipeline) {
  42246. return;
  42247. }
  42248. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42249. };
  42250. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42251. var renderPipeline = this._renderPipelines[renderPipelineName];
  42252. if (!renderPipeline) {
  42253. return;
  42254. }
  42255. renderPipeline._disableDisplayOnlyPass(cameras);
  42256. };
  42257. PostProcessRenderPipelineManager.prototype.update = function () {
  42258. for (var renderPipelineName in this._renderPipelines) {
  42259. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42260. var pipeline = this._renderPipelines[renderPipelineName];
  42261. if (!pipeline.isSupported) {
  42262. pipeline.dispose();
  42263. delete this._renderPipelines[renderPipelineName];
  42264. }
  42265. else {
  42266. pipeline._update();
  42267. }
  42268. }
  42269. }
  42270. };
  42271. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  42272. for (var renderPipelineName in this._renderPipelines) {
  42273. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42274. var pipeline = this._renderPipelines[renderPipelineName];
  42275. pipeline._rebuild();
  42276. }
  42277. }
  42278. };
  42279. PostProcessRenderPipelineManager.prototype.dispose = function () {
  42280. for (var renderPipelineName in this._renderPipelines) {
  42281. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42282. var pipeline = this._renderPipelines[renderPipelineName];
  42283. pipeline.dispose();
  42284. }
  42285. }
  42286. };
  42287. return PostProcessRenderPipelineManager;
  42288. }());
  42289. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42290. })(BABYLON || (BABYLON = {}));
  42291. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42292. var BABYLON;
  42293. (function (BABYLON) {
  42294. var PostProcessRenderPass = (function () {
  42295. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42296. this._enabled = true;
  42297. this._refCount = 0;
  42298. this._name = name;
  42299. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42300. this.setRenderList(renderList);
  42301. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42302. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42303. this._scene = scene;
  42304. this._renderList = renderList;
  42305. }
  42306. // private
  42307. PostProcessRenderPass.prototype._incRefCount = function () {
  42308. if (this._refCount === 0) {
  42309. this._scene.customRenderTargets.push(this._renderTexture);
  42310. }
  42311. return ++this._refCount;
  42312. };
  42313. PostProcessRenderPass.prototype._decRefCount = function () {
  42314. this._refCount--;
  42315. if (this._refCount <= 0) {
  42316. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42317. }
  42318. return this._refCount;
  42319. };
  42320. PostProcessRenderPass.prototype._update = function () {
  42321. this.setRenderList(this._renderList);
  42322. };
  42323. // public
  42324. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42325. this._renderTexture.renderList = renderList;
  42326. };
  42327. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42328. return this._renderTexture;
  42329. };
  42330. return PostProcessRenderPass;
  42331. }());
  42332. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42333. })(BABYLON || (BABYLON = {}));
  42334. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42335. var BABYLON;
  42336. (function (BABYLON) {
  42337. var PostProcessRenderEffect = (function () {
  42338. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42339. this._engine = engine;
  42340. this._name = name;
  42341. this._singleInstance = singleInstance || true;
  42342. this._getPostProcess = getPostProcess;
  42343. this._cameras = [];
  42344. this._indicesForCamera = [];
  42345. this._postProcesses = {};
  42346. this._renderPasses = {};
  42347. this._renderEffectAsPasses = {};
  42348. }
  42349. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42350. get: function () {
  42351. for (var index in this._postProcesses) {
  42352. if (!this._postProcesses[index].isSupported) {
  42353. return false;
  42354. }
  42355. }
  42356. return true;
  42357. },
  42358. enumerable: true,
  42359. configurable: true
  42360. });
  42361. PostProcessRenderEffect.prototype._update = function () {
  42362. for (var renderPassName in this._renderPasses) {
  42363. this._renderPasses[renderPassName]._update();
  42364. }
  42365. };
  42366. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42367. this._renderPasses[renderPass._name] = renderPass;
  42368. this._linkParameters();
  42369. };
  42370. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42371. delete this._renderPasses[renderPass._name];
  42372. this._linkParameters();
  42373. };
  42374. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42375. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42376. this._linkParameters();
  42377. };
  42378. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42379. for (var renderPassName in this._renderPasses) {
  42380. if (renderPassName === passName) {
  42381. return this._renderPasses[passName];
  42382. }
  42383. }
  42384. };
  42385. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42386. this._renderPasses = {};
  42387. this._linkParameters();
  42388. };
  42389. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42390. var cameraKey;
  42391. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42392. for (var i = 0; i < _cam.length; i++) {
  42393. var camera = _cam[i];
  42394. var cameraName = camera.name;
  42395. if (this._singleInstance) {
  42396. cameraKey = 0;
  42397. }
  42398. else {
  42399. cameraKey = cameraName;
  42400. }
  42401. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42402. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42403. if (!this._indicesForCamera[cameraName]) {
  42404. this._indicesForCamera[cameraName] = [];
  42405. }
  42406. this._indicesForCamera[cameraName].push(index);
  42407. if (this._cameras.indexOf(camera) === -1) {
  42408. this._cameras[cameraName] = camera;
  42409. }
  42410. for (var passName in this._renderPasses) {
  42411. this._renderPasses[passName]._incRefCount();
  42412. }
  42413. }
  42414. this._linkParameters();
  42415. };
  42416. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42417. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42418. for (var i = 0; i < _cam.length; i++) {
  42419. var camera = _cam[i];
  42420. var cameraName = camera.name;
  42421. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42422. var index = this._cameras.indexOf(cameraName);
  42423. this._indicesForCamera.splice(index, 1);
  42424. this._cameras.splice(index, 1);
  42425. for (var passName in this._renderPasses) {
  42426. this._renderPasses[passName]._decRefCount();
  42427. }
  42428. }
  42429. };
  42430. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42431. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42432. for (var i = 0; i < _cam.length; i++) {
  42433. var camera = _cam[i];
  42434. var cameraName = camera.name;
  42435. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42436. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42437. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42438. }
  42439. }
  42440. for (var passName in this._renderPasses) {
  42441. this._renderPasses[passName]._incRefCount();
  42442. }
  42443. }
  42444. };
  42445. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42446. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42447. for (var i = 0; i < _cam.length; i++) {
  42448. var camera = _cam[i];
  42449. var cameraName = camera.Name;
  42450. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42451. for (var passName in this._renderPasses) {
  42452. this._renderPasses[passName]._decRefCount();
  42453. }
  42454. }
  42455. };
  42456. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42457. if (this._singleInstance) {
  42458. return this._postProcesses[0];
  42459. }
  42460. else {
  42461. return this._postProcesses[camera.name];
  42462. }
  42463. };
  42464. PostProcessRenderEffect.prototype._linkParameters = function () {
  42465. var _this = this;
  42466. for (var index in this._postProcesses) {
  42467. if (this.applyParameters) {
  42468. this.applyParameters(this._postProcesses[index]);
  42469. }
  42470. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42471. _this._linkTextures(effect);
  42472. });
  42473. }
  42474. };
  42475. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42476. for (var renderPassName in this._renderPasses) {
  42477. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42478. }
  42479. for (var renderEffectName in this._renderEffectAsPasses) {
  42480. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42481. }
  42482. };
  42483. return PostProcessRenderEffect;
  42484. }());
  42485. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42486. })(BABYLON || (BABYLON = {}));
  42487. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42488. var BABYLON;
  42489. (function (BABYLON) {
  42490. var PostProcessRenderPipeline = (function () {
  42491. function PostProcessRenderPipeline(engine, name) {
  42492. this._engine = engine;
  42493. this._name = name;
  42494. this._renderEffects = new Array();
  42495. this._renderEffectsForIsolatedPass = new Array();
  42496. this._cameras = [];
  42497. }
  42498. PostProcessRenderPipeline.prototype.getClassName = function () {
  42499. return "PostProcessRenderPipeline";
  42500. };
  42501. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42502. get: function () {
  42503. for (var renderEffectName in this._renderEffects) {
  42504. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42505. if (!this._renderEffects[renderEffectName].isSupported) {
  42506. return false;
  42507. }
  42508. }
  42509. }
  42510. return true;
  42511. },
  42512. enumerable: true,
  42513. configurable: true
  42514. });
  42515. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42516. this._renderEffects[renderEffect._name] = renderEffect;
  42517. };
  42518. // private
  42519. PostProcessRenderPipeline.prototype._rebuild = function () {
  42520. };
  42521. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42522. var renderEffects = this._renderEffects[renderEffectName];
  42523. if (!renderEffects) {
  42524. return;
  42525. }
  42526. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42527. };
  42528. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42529. var renderEffects = this._renderEffects[renderEffectName];
  42530. if (!renderEffects) {
  42531. return;
  42532. }
  42533. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42534. };
  42535. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42536. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42537. var indicesToDelete = [];
  42538. var i;
  42539. for (i = 0; i < _cam.length; i++) {
  42540. var camera = _cam[i];
  42541. var cameraName = camera.name;
  42542. if (this._cameras.indexOf(camera) === -1) {
  42543. this._cameras[cameraName] = camera;
  42544. }
  42545. else if (unique) {
  42546. indicesToDelete.push(i);
  42547. }
  42548. }
  42549. for (i = 0; i < indicesToDelete.length; i++) {
  42550. cameras.splice(indicesToDelete[i], 1);
  42551. }
  42552. for (var renderEffectName in this._renderEffects) {
  42553. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42554. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42555. }
  42556. }
  42557. };
  42558. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42559. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42560. for (var renderEffectName in this._renderEffects) {
  42561. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42562. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42563. }
  42564. }
  42565. for (var i = 0; i < _cam.length; i++) {
  42566. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42567. }
  42568. };
  42569. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42570. var _this = this;
  42571. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42572. var pass = null;
  42573. var renderEffectName;
  42574. for (renderEffectName in this._renderEffects) {
  42575. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42576. pass = this._renderEffects[renderEffectName].getPass(passName);
  42577. if (pass != null) {
  42578. break;
  42579. }
  42580. }
  42581. }
  42582. if (pass === null) {
  42583. return;
  42584. }
  42585. for (renderEffectName in this._renderEffects) {
  42586. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42587. this._renderEffects[renderEffectName]._disable(_cam);
  42588. }
  42589. }
  42590. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42591. for (var i = 0; i < _cam.length; i++) {
  42592. var camera = _cam[i];
  42593. var cameraName = camera.name;
  42594. 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); });
  42595. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42596. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42597. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42598. }
  42599. };
  42600. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42601. var _this = this;
  42602. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42603. for (var i = 0; i < _cam.length; i++) {
  42604. var camera = _cam[i];
  42605. var cameraName = camera.name;
  42606. 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); });
  42607. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42608. }
  42609. for (var renderEffectName in this._renderEffects) {
  42610. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42611. this._renderEffects[renderEffectName]._enable(_cam);
  42612. }
  42613. }
  42614. };
  42615. PostProcessRenderPipeline.prototype._update = function () {
  42616. for (var renderEffectName in this._renderEffects) {
  42617. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42618. this._renderEffects[renderEffectName]._update();
  42619. }
  42620. }
  42621. for (var i = 0; i < this._cameras.length; i++) {
  42622. var cameraName = this._cameras[i].name;
  42623. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42624. this._renderEffectsForIsolatedPass[cameraName]._update();
  42625. }
  42626. }
  42627. };
  42628. PostProcessRenderPipeline.prototype._reset = function () {
  42629. this._renderEffects = new Array();
  42630. this._renderEffectsForIsolatedPass = new Array();
  42631. };
  42632. PostProcessRenderPipeline.prototype.dispose = function () {
  42633. // Must be implemented by children
  42634. };
  42635. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42636. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42637. __decorate([
  42638. BABYLON.serialize()
  42639. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42640. return PostProcessRenderPipeline;
  42641. }());
  42642. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42643. })(BABYLON || (BABYLON = {}));
  42644. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42645. var BABYLON;
  42646. (function (BABYLON) {
  42647. var DefaultRenderingPipeline = (function (_super) {
  42648. __extends(DefaultRenderingPipeline, _super);
  42649. /**
  42650. * @constructor
  42651. * @param {string} name - The rendering pipeline name
  42652. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42653. * @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)
  42654. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42655. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  42656. */
  42657. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  42658. if (automaticBuild === void 0) { automaticBuild = true; }
  42659. var _this = _super.call(this, scene.getEngine(), name) || this;
  42660. _this.PassPostProcessId = "PassPostProcessEffect";
  42661. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42662. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42663. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42664. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42665. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42666. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42667. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42668. // IAnimatable
  42669. _this.animations = [];
  42670. // Values
  42671. _this._bloomEnabled = false;
  42672. _this._fxaaEnabled = false;
  42673. _this._imageProcessingEnabled = true;
  42674. _this._bloomScale = 0.6;
  42675. _this._buildAllowed = true;
  42676. /**
  42677. * Specifies the size of the bloom blur kernel, relative to the final output size
  42678. */
  42679. _this.bloomKernel = 64;
  42680. /**
  42681. * Specifies the weight of the bloom in the final rendering
  42682. */
  42683. _this._bloomWeight = 0.15;
  42684. _this._cameras = cameras || [];
  42685. _this._buildAllowed = automaticBuild;
  42686. // Initialize
  42687. _this._scene = scene;
  42688. var caps = _this._scene.getEngine().getCaps();
  42689. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  42690. // Misc
  42691. if (_this._hdr) {
  42692. if (caps.textureHalfFloatRender) {
  42693. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42694. }
  42695. else if (caps.textureFloatRender) {
  42696. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42697. }
  42698. }
  42699. else {
  42700. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42701. }
  42702. // Attach
  42703. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42704. _this._buildPipeline();
  42705. return _this;
  42706. }
  42707. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42708. get: function () {
  42709. return this._bloomWeight;
  42710. },
  42711. set: function (value) {
  42712. if (this._bloomWeight === value) {
  42713. return;
  42714. }
  42715. this._bloomWeight = value;
  42716. if (this._hdr && this.copyBack) {
  42717. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42718. }
  42719. },
  42720. enumerable: true,
  42721. configurable: true
  42722. });
  42723. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42724. get: function () {
  42725. return this._bloomScale;
  42726. },
  42727. set: function (value) {
  42728. if (this._bloomScale === value) {
  42729. return;
  42730. }
  42731. this._bloomScale = value;
  42732. this._buildPipeline();
  42733. },
  42734. enumerable: true,
  42735. configurable: true
  42736. });
  42737. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42738. get: function () {
  42739. return this._bloomEnabled;
  42740. },
  42741. set: function (enabled) {
  42742. if (this._bloomEnabled === enabled) {
  42743. return;
  42744. }
  42745. this._bloomEnabled = enabled;
  42746. this._buildPipeline();
  42747. },
  42748. enumerable: true,
  42749. configurable: true
  42750. });
  42751. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42752. get: function () {
  42753. return this._fxaaEnabled;
  42754. },
  42755. set: function (enabled) {
  42756. if (this._fxaaEnabled === enabled) {
  42757. return;
  42758. }
  42759. this._fxaaEnabled = enabled;
  42760. this._buildPipeline();
  42761. },
  42762. enumerable: true,
  42763. configurable: true
  42764. });
  42765. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42766. get: function () {
  42767. return this._imageProcessingEnabled;
  42768. },
  42769. set: function (enabled) {
  42770. if (this._imageProcessingEnabled === enabled) {
  42771. return;
  42772. }
  42773. this._imageProcessingEnabled = enabled;
  42774. this._buildPipeline();
  42775. },
  42776. enumerable: true,
  42777. configurable: true
  42778. });
  42779. /**
  42780. * Force the compilation of the entire pipeline.
  42781. */
  42782. DefaultRenderingPipeline.prototype.prepare = function () {
  42783. var previousState = this._buildAllowed;
  42784. this._buildAllowed = true;
  42785. this._buildPipeline();
  42786. this._buildAllowed = previousState;
  42787. };
  42788. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42789. var _this = this;
  42790. if (!this._buildAllowed) {
  42791. return;
  42792. }
  42793. var engine = this._scene.getEngine();
  42794. this._disposePostProcesses();
  42795. this._reset();
  42796. if (this.bloomEnabled) {
  42797. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42798. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42799. if (!this._hdr) {
  42800. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42801. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42802. this.highlights.autoClear = false;
  42803. this.highlights.alwaysForcePOT = true;
  42804. }
  42805. 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);
  42806. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42807. this.blurX.alwaysForcePOT = true;
  42808. this.blurX.autoClear = false;
  42809. this.blurX.onActivateObservable.add(function () {
  42810. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42811. _this.blurX.kernel = _this.bloomKernel * dw;
  42812. });
  42813. 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);
  42814. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42815. this.blurY.alwaysForcePOT = true;
  42816. this.blurY.autoClear = false;
  42817. this.blurY.onActivateObservable.add(function () {
  42818. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42819. _this.blurY.kernel = _this.bloomKernel * dh;
  42820. });
  42821. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42822. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42823. this.copyBack.alwaysForcePOT = true;
  42824. if (this._hdr) {
  42825. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42826. var w = this.bloomWeight;
  42827. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42828. }
  42829. else {
  42830. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42831. }
  42832. this.copyBack.autoClear = false;
  42833. }
  42834. if (this._imageProcessingEnabled) {
  42835. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42836. if (this._hdr) {
  42837. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42838. }
  42839. }
  42840. if (this.fxaaEnabled) {
  42841. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42842. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42843. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42844. }
  42845. else {
  42846. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42847. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42848. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42849. }
  42850. if (this.bloomEnabled) {
  42851. if (this._hdr) {
  42852. this.copyBack.shareOutputWith(this.blurX);
  42853. if (this.imageProcessing) {
  42854. this.imageProcessing.shareOutputWith(this.pass);
  42855. this.imageProcessing.autoClear = false;
  42856. }
  42857. else if (this.fxaa) {
  42858. this.fxaa.shareOutputWith(this.pass);
  42859. }
  42860. else {
  42861. this.finalMerge.shareOutputWith(this.pass);
  42862. }
  42863. }
  42864. else {
  42865. if (this.fxaa) {
  42866. this.fxaa.shareOutputWith(this.pass);
  42867. }
  42868. else {
  42869. this.finalMerge.shareOutputWith(this.pass);
  42870. }
  42871. }
  42872. }
  42873. if (this._cameras !== null) {
  42874. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42875. }
  42876. };
  42877. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42878. for (var i = 0; i < this._cameras.length; i++) {
  42879. var camera = this._cameras[i];
  42880. if (this.pass) {
  42881. this.pass.dispose(camera);
  42882. }
  42883. if (this.highlights) {
  42884. this.highlights.dispose(camera);
  42885. }
  42886. if (this.blurX) {
  42887. this.blurX.dispose(camera);
  42888. }
  42889. if (this.blurY) {
  42890. this.blurY.dispose(camera);
  42891. }
  42892. if (this.copyBack) {
  42893. this.copyBack.dispose(camera);
  42894. }
  42895. if (this.imageProcessing) {
  42896. this.imageProcessing.dispose(camera);
  42897. }
  42898. if (this.fxaa) {
  42899. this.fxaa.dispose(camera);
  42900. }
  42901. if (this.finalMerge) {
  42902. this.finalMerge.dispose(camera);
  42903. }
  42904. }
  42905. this.pass = null;
  42906. this.highlights = null;
  42907. this.blurX = null;
  42908. this.blurY = null;
  42909. this.copyBack = null;
  42910. this.imageProcessing = null;
  42911. this.fxaa = null;
  42912. this.finalMerge = null;
  42913. };
  42914. // Dispose
  42915. DefaultRenderingPipeline.prototype.dispose = function () {
  42916. this._disposePostProcesses();
  42917. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  42918. _super.prototype.dispose.call(this);
  42919. };
  42920. // Serialize rendering pipeline
  42921. DefaultRenderingPipeline.prototype.serialize = function () {
  42922. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42923. serializationObject.customType = "DefaultRenderingPipeline";
  42924. return serializationObject;
  42925. };
  42926. // Parse serialized pipeline
  42927. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  42928. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  42929. };
  42930. __decorate([
  42931. BABYLON.serialize()
  42932. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  42933. __decorate([
  42934. BABYLON.serialize()
  42935. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  42936. __decorate([
  42937. BABYLON.serialize()
  42938. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  42939. __decorate([
  42940. BABYLON.serialize()
  42941. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  42942. __decorate([
  42943. BABYLON.serialize()
  42944. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  42945. __decorate([
  42946. BABYLON.serialize()
  42947. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  42948. __decorate([
  42949. BABYLON.serialize()
  42950. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  42951. __decorate([
  42952. BABYLON.serialize()
  42953. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  42954. return DefaultRenderingPipeline;
  42955. }(BABYLON.PostProcessRenderPipeline));
  42956. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  42957. })(BABYLON || (BABYLON = {}));
  42958. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  42959. var BABYLON;
  42960. (function (BABYLON) {
  42961. /**
  42962. * This groups together the common properties used for image processing either in direct forward pass
  42963. * or through post processing effect depending on the use of the image processing pipeline in your scene
  42964. * or not.
  42965. */
  42966. var ImageProcessingConfiguration = (function () {
  42967. function ImageProcessingConfiguration() {
  42968. /**
  42969. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  42970. */
  42971. this.colorCurves = new BABYLON.ColorCurves();
  42972. this._colorCurvesEnabled = false;
  42973. this._colorGradingEnabled = false;
  42974. this._colorGradingWithGreenDepth = false;
  42975. this._colorGradingBGR = false;
  42976. this._exposure = 1.0;
  42977. this._toneMappingEnabled = false;
  42978. this._contrast = 1.0;
  42979. /**
  42980. * Vignette stretch size.
  42981. */
  42982. this.vignetteStretch = 0;
  42983. /**
  42984. * Vignette centre X Offset.
  42985. */
  42986. this.vignetteCentreX = 0;
  42987. /**
  42988. * Vignette centre Y Offset.
  42989. */
  42990. this.vignetteCentreY = 0;
  42991. /**
  42992. * Vignette weight or intensity of the vignette effect.
  42993. */
  42994. this.vignetteWeight = 1.5;
  42995. /**
  42996. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  42997. * if vignetteEnabled is set to true.
  42998. */
  42999. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  43000. /**
  43001. * Camera field of view used by the Vignette effect.
  43002. */
  43003. this.vignetteCameraFov = 0.5;
  43004. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  43005. this._vignetteEnabled = false;
  43006. this._applyByPostProcess = false;
  43007. /**
  43008. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  43009. * @type {BABYLON.Observable}
  43010. */
  43011. this.onUpdateParameters = new BABYLON.Observable();
  43012. }
  43013. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  43014. /**
  43015. * Gets wether the color curves effect is enabled.
  43016. */
  43017. get: function () {
  43018. return this._colorCurvesEnabled;
  43019. },
  43020. /**
  43021. * Sets wether the color curves effect is enabled.
  43022. */
  43023. set: function (value) {
  43024. if (this._colorCurvesEnabled === value) {
  43025. return;
  43026. }
  43027. this._colorCurvesEnabled = value;
  43028. this._updateParameters();
  43029. },
  43030. enumerable: true,
  43031. configurable: true
  43032. });
  43033. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  43034. /**
  43035. * Gets wether the color grading effect is enabled.
  43036. */
  43037. get: function () {
  43038. return this._colorGradingEnabled;
  43039. },
  43040. /**
  43041. * Sets wether the color grading effect is enabled.
  43042. */
  43043. set: function (value) {
  43044. if (this._colorGradingEnabled === value) {
  43045. return;
  43046. }
  43047. this._colorGradingEnabled = value;
  43048. this._updateParameters();
  43049. },
  43050. enumerable: true,
  43051. configurable: true
  43052. });
  43053. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  43054. /**
  43055. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  43056. */
  43057. get: function () {
  43058. return this._colorGradingWithGreenDepth;
  43059. },
  43060. /**
  43061. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  43062. */
  43063. set: function (value) {
  43064. if (this._colorGradingWithGreenDepth === value) {
  43065. return;
  43066. }
  43067. this._colorGradingWithGreenDepth = value;
  43068. this._updateParameters();
  43069. },
  43070. enumerable: true,
  43071. configurable: true
  43072. });
  43073. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  43074. /**
  43075. * Gets wether the color grading texture contains BGR values.
  43076. */
  43077. get: function () {
  43078. return this._colorGradingBGR;
  43079. },
  43080. /**
  43081. * Sets wether the color grading texture contains BGR values.
  43082. */
  43083. set: function (value) {
  43084. if (this._colorGradingBGR === value) {
  43085. return;
  43086. }
  43087. this._colorGradingBGR = value;
  43088. this._updateParameters();
  43089. },
  43090. enumerable: true,
  43091. configurable: true
  43092. });
  43093. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  43094. /**
  43095. * Gets the Exposure used in the effect.
  43096. */
  43097. get: function () {
  43098. return this._exposure;
  43099. },
  43100. /**
  43101. * Sets the Exposure used in the effect.
  43102. */
  43103. set: function (value) {
  43104. if (this._exposure === value) {
  43105. return;
  43106. }
  43107. this._exposure = value;
  43108. this._updateParameters();
  43109. },
  43110. enumerable: true,
  43111. configurable: true
  43112. });
  43113. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  43114. /**
  43115. * Gets wether the tone mapping effect is enabled.
  43116. */
  43117. get: function () {
  43118. return this._toneMappingEnabled;
  43119. },
  43120. /**
  43121. * Sets wether the tone mapping effect is enabled.
  43122. */
  43123. set: function (value) {
  43124. if (this._toneMappingEnabled === value) {
  43125. return;
  43126. }
  43127. this._toneMappingEnabled = value;
  43128. this._updateParameters();
  43129. },
  43130. enumerable: true,
  43131. configurable: true
  43132. });
  43133. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  43134. /**
  43135. * Gets the contrast used in the effect.
  43136. */
  43137. get: function () {
  43138. return this._contrast;
  43139. },
  43140. /**
  43141. * Sets the contrast used in the effect.
  43142. */
  43143. set: function (value) {
  43144. if (this._contrast === value) {
  43145. return;
  43146. }
  43147. this._contrast = value;
  43148. this._updateParameters();
  43149. },
  43150. enumerable: true,
  43151. configurable: true
  43152. });
  43153. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  43154. /**
  43155. * Gets the vignette blend mode allowing different kind of effect.
  43156. */
  43157. get: function () {
  43158. return this._vignetteBlendMode;
  43159. },
  43160. /**
  43161. * Sets the vignette blend mode allowing different kind of effect.
  43162. */
  43163. set: function (value) {
  43164. if (this._vignetteBlendMode === value) {
  43165. return;
  43166. }
  43167. this._vignetteBlendMode = value;
  43168. this._updateParameters();
  43169. },
  43170. enumerable: true,
  43171. configurable: true
  43172. });
  43173. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  43174. /**
  43175. * Gets wether the vignette effect is enabled.
  43176. */
  43177. get: function () {
  43178. return this._vignetteEnabled;
  43179. },
  43180. /**
  43181. * Sets wether the vignette effect is enabled.
  43182. */
  43183. set: function (value) {
  43184. if (this._vignetteEnabled === value) {
  43185. return;
  43186. }
  43187. this._vignetteEnabled = value;
  43188. this._updateParameters();
  43189. },
  43190. enumerable: true,
  43191. configurable: true
  43192. });
  43193. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  43194. /**
  43195. * Gets wether the image processing is applied through a post process or not.
  43196. */
  43197. get: function () {
  43198. return this._applyByPostProcess;
  43199. },
  43200. /**
  43201. * Sets wether the image processing is applied through a post process or not.
  43202. */
  43203. set: function (value) {
  43204. if (this._applyByPostProcess === value) {
  43205. return;
  43206. }
  43207. this._applyByPostProcess = value;
  43208. this._updateParameters();
  43209. },
  43210. enumerable: true,
  43211. configurable: true
  43212. });
  43213. /**
  43214. * Method called each time the image processing information changes requires to recompile the effect.
  43215. */
  43216. ImageProcessingConfiguration.prototype._updateParameters = function () {
  43217. this.onUpdateParameters.notifyObservers(this);
  43218. };
  43219. ImageProcessingConfiguration.prototype.getClassName = function () {
  43220. return "ImageProcessingConfiguration";
  43221. };
  43222. /**
  43223. * Prepare the list of uniforms associated with the Image Processing effects.
  43224. * @param uniformsList The list of uniforms used in the effect
  43225. * @param defines the list of defines currently in use
  43226. */
  43227. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  43228. if (defines.EXPOSURE) {
  43229. uniforms.push("exposureLinear");
  43230. }
  43231. if (defines.CONTRAST) {
  43232. uniforms.push("contrast");
  43233. }
  43234. if (defines.COLORGRADING) {
  43235. uniforms.push("colorTransformSettings");
  43236. }
  43237. if (defines.VIGNETTE) {
  43238. uniforms.push("vInverseScreenSize");
  43239. uniforms.push("vignetteSettings1");
  43240. uniforms.push("vignetteSettings2");
  43241. }
  43242. if (defines.COLORCURVES) {
  43243. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  43244. }
  43245. };
  43246. /**
  43247. * Prepare the list of samplers associated with the Image Processing effects.
  43248. * @param uniformsList The list of uniforms used in the effect
  43249. * @param defines the list of defines currently in use
  43250. */
  43251. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  43252. if (defines.COLORGRADING) {
  43253. samplersList.push("txColorTransform");
  43254. }
  43255. };
  43256. /**
  43257. * Prepare the list of defines associated to the shader.
  43258. * @param defines the list of defines to complete
  43259. */
  43260. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  43261. defines.VIGNETTE = this.vignetteEnabled;
  43262. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  43263. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  43264. defines.TONEMAPPING = this.toneMappingEnabled;
  43265. defines.CONTRAST = (this.contrast !== 1.0);
  43266. defines.EXPOSURE = (this.exposure !== 1.0);
  43267. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  43268. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  43269. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  43270. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  43271. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  43272. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  43273. };
  43274. /**
  43275. * Returns true if all the image processing information are ready.
  43276. */
  43277. ImageProcessingConfiguration.prototype.isReady = function () {
  43278. // Color Grading texure can not be none blocking.
  43279. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  43280. };
  43281. /**
  43282. * Binds the image processing to the shader.
  43283. * @param effect The effect to bind to
  43284. */
  43285. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  43286. if (aspectRatio === void 0) { aspectRatio = 1; }
  43287. // Color Curves
  43288. if (this._colorCurvesEnabled) {
  43289. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  43290. }
  43291. // Vignette
  43292. if (this._vignetteEnabled) {
  43293. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  43294. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  43295. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  43296. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  43297. var vignetteScaleX = vignetteScaleY * aspectRatio;
  43298. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  43299. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  43300. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  43301. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  43302. var vignettePower = -2.0 * this.vignetteWeight;
  43303. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  43304. }
  43305. // Exposure
  43306. effect.setFloat("exposureLinear", this.exposure);
  43307. // Contrast
  43308. effect.setFloat("contrast", this.contrast);
  43309. // Color transform settings
  43310. if (this.colorGradingTexture) {
  43311. effect.setTexture("txColorTransform", this.colorGradingTexture);
  43312. var textureSize = this.colorGradingTexture.getSize().height;
  43313. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  43314. 0.5 / textureSize, // textureOffset
  43315. textureSize, // textureSize
  43316. this.colorGradingTexture.level // weight
  43317. );
  43318. }
  43319. };
  43320. /**
  43321. * Clones the current image processing instance.
  43322. * @return The cloned image processing
  43323. */
  43324. ImageProcessingConfiguration.prototype.clone = function () {
  43325. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  43326. };
  43327. /**
  43328. * Serializes the current image processing instance to a json representation.
  43329. * @return a JSON representation
  43330. */
  43331. ImageProcessingConfiguration.prototype.serialize = function () {
  43332. return BABYLON.SerializationHelper.Serialize(this);
  43333. };
  43334. /**
  43335. * Parses the image processing from a json representation.
  43336. * @param source the JSON source to parse
  43337. * @return The parsed image processing
  43338. */
  43339. ImageProcessingConfiguration.Parse = function (source) {
  43340. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  43341. };
  43342. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  43343. /**
  43344. * Used to apply the vignette as a mix with the pixel color.
  43345. */
  43346. get: function () {
  43347. return this._VIGNETTEMODE_MULTIPLY;
  43348. },
  43349. enumerable: true,
  43350. configurable: true
  43351. });
  43352. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  43353. /**
  43354. * Used to apply the vignette as a replacement of the pixel color.
  43355. */
  43356. get: function () {
  43357. return this._VIGNETTEMODE_OPAQUE;
  43358. },
  43359. enumerable: true,
  43360. configurable: true
  43361. });
  43362. // Static constants associated to the image processing.
  43363. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  43364. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  43365. __decorate([
  43366. BABYLON.serializeAsColorCurves()
  43367. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  43368. __decorate([
  43369. BABYLON.serialize()
  43370. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  43371. __decorate([
  43372. BABYLON.serializeAsTexture()
  43373. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  43374. __decorate([
  43375. BABYLON.serialize()
  43376. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  43377. __decorate([
  43378. BABYLON.serialize()
  43379. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  43380. __decorate([
  43381. BABYLON.serialize()
  43382. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  43383. __decorate([
  43384. BABYLON.serialize()
  43385. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  43386. __decorate([
  43387. BABYLON.serialize()
  43388. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  43389. __decorate([
  43390. BABYLON.serialize()
  43391. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  43392. __decorate([
  43393. BABYLON.serialize()
  43394. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  43395. __decorate([
  43396. BABYLON.serialize()
  43397. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  43398. __decorate([
  43399. BABYLON.serialize()
  43400. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  43401. __decorate([
  43402. BABYLON.serialize()
  43403. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  43404. __decorate([
  43405. BABYLON.serializeAsColor4()
  43406. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  43407. __decorate([
  43408. BABYLON.serialize()
  43409. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  43410. __decorate([
  43411. BABYLON.serialize()
  43412. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  43413. __decorate([
  43414. BABYLON.serialize()
  43415. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  43416. __decorate([
  43417. BABYLON.serialize()
  43418. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  43419. return ImageProcessingConfiguration;
  43420. }());
  43421. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  43422. })(BABYLON || (BABYLON = {}));
  43423. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  43424. /// <reference path="babylon.mesh.ts" />
  43425. var BABYLON;
  43426. (function (BABYLON) {
  43427. var GroundMesh = (function (_super) {
  43428. __extends(GroundMesh, _super);
  43429. function GroundMesh(name, scene) {
  43430. var _this = _super.call(this, name, scene) || this;
  43431. _this.generateOctree = false;
  43432. _this._worldInverse = new BABYLON.Matrix();
  43433. return _this;
  43434. }
  43435. GroundMesh.prototype.getClassName = function () {
  43436. return "GroundMesh";
  43437. };
  43438. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43439. get: function () {
  43440. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43441. },
  43442. enumerable: true,
  43443. configurable: true
  43444. });
  43445. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43446. get: function () {
  43447. return this._subdivisionsX;
  43448. },
  43449. enumerable: true,
  43450. configurable: true
  43451. });
  43452. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43453. get: function () {
  43454. return this._subdivisionsY;
  43455. },
  43456. enumerable: true,
  43457. configurable: true
  43458. });
  43459. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43460. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43461. this._subdivisionsX = chunksCount;
  43462. this._subdivisionsY = chunksCount;
  43463. this.subdivide(chunksCount);
  43464. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43465. };
  43466. /**
  43467. * Returns a height (y) value in the Worl system :
  43468. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43469. * Returns the ground y position if (x, z) are outside the ground surface.
  43470. */
  43471. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43472. var world = this.getWorldMatrix();
  43473. var invMat = BABYLON.Tmp.Matrix[5];
  43474. world.invertToRef(invMat);
  43475. var tmpVect = BABYLON.Tmp.Vector3[8];
  43476. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43477. x = tmpVect.x;
  43478. z = tmpVect.z;
  43479. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43480. return this.position.y;
  43481. }
  43482. if (!this._heightQuads || this._heightQuads.length == 0) {
  43483. this._initHeightQuads();
  43484. this._computeHeightQuads();
  43485. }
  43486. var facet = this._getFacetAt(x, z);
  43487. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43488. // return y in the World system
  43489. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43490. return tmpVect.y;
  43491. };
  43492. /**
  43493. * Returns a normalized vector (Vector3) orthogonal to the ground
  43494. * at the ground coordinates (x, z) expressed in the World system.
  43495. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43496. */
  43497. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43498. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43499. this.getNormalAtCoordinatesToRef(x, z, normal);
  43500. return normal;
  43501. };
  43502. /**
  43503. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43504. * at the ground coordinates (x, z) expressed in the World system.
  43505. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43506. * Returns the GroundMesh.
  43507. */
  43508. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43509. var world = this.getWorldMatrix();
  43510. var tmpMat = BABYLON.Tmp.Matrix[5];
  43511. world.invertToRef(tmpMat);
  43512. var tmpVect = BABYLON.Tmp.Vector3[8];
  43513. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43514. x = tmpVect.x;
  43515. z = tmpVect.z;
  43516. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43517. return this;
  43518. }
  43519. if (!this._heightQuads || this._heightQuads.length == 0) {
  43520. this._initHeightQuads();
  43521. this._computeHeightQuads();
  43522. }
  43523. var facet = this._getFacetAt(x, z);
  43524. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43525. return this;
  43526. };
  43527. /**
  43528. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43529. * if the ground has been updated.
  43530. * This can be used in the render loop.
  43531. * Returns the GroundMesh.
  43532. */
  43533. GroundMesh.prototype.updateCoordinateHeights = function () {
  43534. if (!this._heightQuads || this._heightQuads.length == 0) {
  43535. this._initHeightQuads();
  43536. }
  43537. this._computeHeightQuads();
  43538. return this;
  43539. };
  43540. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43541. GroundMesh.prototype._getFacetAt = function (x, z) {
  43542. // retrieve col and row from x, z coordinates in the ground local system
  43543. var subdivisionsX = this._subdivisionsX;
  43544. var subdivisionsY = this._subdivisionsY;
  43545. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43546. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43547. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43548. var facet;
  43549. if (z < quad.slope.x * x + quad.slope.y) {
  43550. facet = quad.facet1;
  43551. }
  43552. else {
  43553. facet = quad.facet2;
  43554. }
  43555. return facet;
  43556. };
  43557. // Creates and populates the heightMap array with "facet" elements :
  43558. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43559. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43560. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43561. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43562. // Returns the GroundMesh.
  43563. GroundMesh.prototype._initHeightQuads = function () {
  43564. var subdivisionsX = this._subdivisionsX;
  43565. var subdivisionsY = this._subdivisionsY;
  43566. this._heightQuads = new Array();
  43567. for (var row = 0; row < subdivisionsY; row++) {
  43568. for (var col = 0; col < subdivisionsX; col++) {
  43569. 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) };
  43570. this._heightQuads[row * subdivisionsX + col] = quad;
  43571. }
  43572. }
  43573. return this;
  43574. };
  43575. // Compute each quad element values and update the the heightMap array :
  43576. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43577. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43578. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43579. // Returns the GroundMesh.
  43580. GroundMesh.prototype._computeHeightQuads = function () {
  43581. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43582. var v1 = BABYLON.Tmp.Vector3[3];
  43583. var v2 = BABYLON.Tmp.Vector3[2];
  43584. var v3 = BABYLON.Tmp.Vector3[1];
  43585. var v4 = BABYLON.Tmp.Vector3[0];
  43586. var v1v2 = BABYLON.Tmp.Vector3[4];
  43587. var v1v3 = BABYLON.Tmp.Vector3[5];
  43588. var v1v4 = BABYLON.Tmp.Vector3[6];
  43589. var norm1 = BABYLON.Tmp.Vector3[7];
  43590. var norm2 = BABYLON.Tmp.Vector3[8];
  43591. var i = 0;
  43592. var j = 0;
  43593. var k = 0;
  43594. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43595. var h = 0;
  43596. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43597. var d2 = 0;
  43598. var subdivisionsX = this._subdivisionsX;
  43599. var subdivisionsY = this._subdivisionsY;
  43600. for (var row = 0; row < subdivisionsY; row++) {
  43601. for (var col = 0; col < subdivisionsX; col++) {
  43602. i = col * 3;
  43603. j = row * (subdivisionsX + 1) * 3;
  43604. k = (row + 1) * (subdivisionsX + 1) * 3;
  43605. v1.x = positions[j + i];
  43606. v1.y = positions[j + i + 1];
  43607. v1.z = positions[j + i + 2];
  43608. v2.x = positions[j + i + 3];
  43609. v2.y = positions[j + i + 4];
  43610. v2.z = positions[j + i + 5];
  43611. v3.x = positions[k + i];
  43612. v3.y = positions[k + i + 1];
  43613. v3.z = positions[k + i + 2];
  43614. v4.x = positions[k + i + 3];
  43615. v4.y = positions[k + i + 4];
  43616. v4.z = positions[k + i + 5];
  43617. // 2D slope V1V4
  43618. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43619. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43620. // facet equations :
  43621. // we compute each facet normal vector
  43622. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43623. // we compute the value d by applying the equation to v1 which belongs to the plane
  43624. // then we store the facet equation in a Vector4
  43625. v2.subtractToRef(v1, v1v2);
  43626. v3.subtractToRef(v1, v1v3);
  43627. v4.subtractToRef(v1, v1v4);
  43628. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43629. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43630. norm1.normalize();
  43631. norm2.normalize();
  43632. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43633. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43634. var quad = this._heightQuads[row * subdivisionsX + col];
  43635. quad.slope.copyFromFloats(cd, h);
  43636. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43637. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43638. }
  43639. }
  43640. return this;
  43641. };
  43642. GroundMesh.prototype.serialize = function (serializationObject) {
  43643. _super.prototype.serialize.call(this, serializationObject);
  43644. serializationObject.subdivisionsX = this._subdivisionsX;
  43645. serializationObject.subdivisionsY = this._subdivisionsY;
  43646. serializationObject.minX = this._minX;
  43647. serializationObject.maxX = this._maxX;
  43648. serializationObject.minZ = this._minZ;
  43649. serializationObject.maxZ = this._maxZ;
  43650. serializationObject.width = this._width;
  43651. serializationObject.height = this._height;
  43652. };
  43653. GroundMesh.Parse = function (parsedMesh, scene) {
  43654. var result = new GroundMesh(parsedMesh.name, scene);
  43655. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43656. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43657. result._minX = parsedMesh.minX;
  43658. result._maxX = parsedMesh.maxX;
  43659. result._minZ = parsedMesh.minZ;
  43660. result._maxZ = parsedMesh.maxZ;
  43661. result._width = parsedMesh.width;
  43662. result._height = parsedMesh.height;
  43663. return result;
  43664. };
  43665. return GroundMesh;
  43666. }(BABYLON.Mesh));
  43667. BABYLON.GroundMesh = GroundMesh;
  43668. })(BABYLON || (BABYLON = {}));
  43669. //# sourceMappingURL=babylon.groundMesh.js.map
  43670. var BABYLON;
  43671. (function (BABYLON) {
  43672. /**
  43673. * Creates an instance based on a source mesh.
  43674. */
  43675. var InstancedMesh = (function (_super) {
  43676. __extends(InstancedMesh, _super);
  43677. function InstancedMesh(name, source) {
  43678. var _this = _super.call(this, name, source.getScene()) || this;
  43679. source.instances.push(_this);
  43680. _this._sourceMesh = source;
  43681. _this.position.copyFrom(source.position);
  43682. _this.rotation.copyFrom(source.rotation);
  43683. _this.scaling.copyFrom(source.scaling);
  43684. if (source.rotationQuaternion) {
  43685. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43686. }
  43687. _this.infiniteDistance = source.infiniteDistance;
  43688. _this.setPivotMatrix(source.getPivotMatrix());
  43689. _this.refreshBoundingInfo();
  43690. _this._syncSubMeshes();
  43691. return _this;
  43692. }
  43693. /**
  43694. * Returns the string "InstancedMesh".
  43695. */
  43696. InstancedMesh.prototype.getClassName = function () {
  43697. return "InstancedMesh";
  43698. };
  43699. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43700. // Methods
  43701. get: function () {
  43702. return this._sourceMesh.receiveShadows;
  43703. },
  43704. enumerable: true,
  43705. configurable: true
  43706. });
  43707. Object.defineProperty(InstancedMesh.prototype, "material", {
  43708. get: function () {
  43709. return this._sourceMesh.material;
  43710. },
  43711. enumerable: true,
  43712. configurable: true
  43713. });
  43714. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43715. get: function () {
  43716. return this._sourceMesh.visibility;
  43717. },
  43718. enumerable: true,
  43719. configurable: true
  43720. });
  43721. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43722. get: function () {
  43723. return this._sourceMesh.skeleton;
  43724. },
  43725. enumerable: true,
  43726. configurable: true
  43727. });
  43728. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43729. get: function () {
  43730. return this._sourceMesh.renderingGroupId;
  43731. },
  43732. enumerable: true,
  43733. configurable: true
  43734. });
  43735. /**
  43736. * Returns the total number of vertices (integer).
  43737. */
  43738. InstancedMesh.prototype.getTotalVertices = function () {
  43739. return this._sourceMesh.getTotalVertices();
  43740. };
  43741. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43742. get: function () {
  43743. return this._sourceMesh;
  43744. },
  43745. enumerable: true,
  43746. configurable: true
  43747. });
  43748. /**
  43749. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43750. */
  43751. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43752. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43753. };
  43754. /**
  43755. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43756. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43757. * The `data` are either a numeric array either a Float32Array.
  43758. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43759. * 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).
  43760. * Note that a new underlying VertexBuffer object is created each call.
  43761. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43762. *
  43763. * Possible `kind` values :
  43764. * - BABYLON.VertexBuffer.PositionKind
  43765. * - BABYLON.VertexBuffer.UVKind
  43766. * - BABYLON.VertexBuffer.UV2Kind
  43767. * - BABYLON.VertexBuffer.UV3Kind
  43768. * - BABYLON.VertexBuffer.UV4Kind
  43769. * - BABYLON.VertexBuffer.UV5Kind
  43770. * - BABYLON.VertexBuffer.UV6Kind
  43771. * - BABYLON.VertexBuffer.ColorKind
  43772. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43773. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43774. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43775. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43776. *
  43777. * Returns the Mesh.
  43778. */
  43779. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43780. if (this.sourceMesh) {
  43781. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43782. }
  43783. return this.sourceMesh;
  43784. };
  43785. /**
  43786. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43787. * If the mesh has no geometry, it is simply returned as it is.
  43788. * The `data` are either a numeric array either a Float32Array.
  43789. * No new underlying VertexBuffer object is created.
  43790. * 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.
  43791. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43792. *
  43793. * Possible `kind` values :
  43794. * - BABYLON.VertexBuffer.PositionKind
  43795. * - BABYLON.VertexBuffer.UVKind
  43796. * - BABYLON.VertexBuffer.UV2Kind
  43797. * - BABYLON.VertexBuffer.UV3Kind
  43798. * - BABYLON.VertexBuffer.UV4Kind
  43799. * - BABYLON.VertexBuffer.UV5Kind
  43800. * - BABYLON.VertexBuffer.UV6Kind
  43801. * - BABYLON.VertexBuffer.ColorKind
  43802. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43803. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43804. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43805. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43806. *
  43807. * Returns the Mesh.
  43808. */
  43809. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43810. if (this.sourceMesh) {
  43811. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43812. }
  43813. return this.sourceMesh;
  43814. };
  43815. /**
  43816. * Sets the mesh indices.
  43817. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43818. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43819. * This method creates a new index buffer each call.
  43820. * Returns the Mesh.
  43821. */
  43822. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43823. if (this.sourceMesh) {
  43824. this.sourceMesh.setIndices(indices, totalVertices);
  43825. }
  43826. return this.sourceMesh;
  43827. };
  43828. /**
  43829. * Boolean : True if the mesh owns the requested kind of data.
  43830. */
  43831. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43832. return this._sourceMesh.isVerticesDataPresent(kind);
  43833. };
  43834. /**
  43835. * Returns an array of indices (IndicesArray).
  43836. */
  43837. InstancedMesh.prototype.getIndices = function () {
  43838. return this._sourceMesh.getIndices();
  43839. };
  43840. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43841. get: function () {
  43842. return this._sourceMesh._positions;
  43843. },
  43844. enumerable: true,
  43845. configurable: true
  43846. });
  43847. /**
  43848. * Sets a new updated BoundingInfo to the mesh.
  43849. * Returns the mesh.
  43850. */
  43851. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43852. var meshBB = this._sourceMesh.getBoundingInfo();
  43853. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43854. this._updateBoundingInfo();
  43855. return this;
  43856. };
  43857. InstancedMesh.prototype._preActivate = function () {
  43858. if (this._currentLOD) {
  43859. this._currentLOD._preActivate();
  43860. }
  43861. return this;
  43862. };
  43863. InstancedMesh.prototype._activate = function (renderId) {
  43864. if (this._currentLOD) {
  43865. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43866. }
  43867. return this;
  43868. };
  43869. /**
  43870. * Returns the current associated LOD AbstractMesh.
  43871. */
  43872. InstancedMesh.prototype.getLOD = function (camera) {
  43873. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43874. if (this._currentLOD === this.sourceMesh) {
  43875. return this;
  43876. }
  43877. return this._currentLOD;
  43878. };
  43879. InstancedMesh.prototype._syncSubMeshes = function () {
  43880. this.releaseSubMeshes();
  43881. if (this._sourceMesh.subMeshes) {
  43882. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43883. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43884. }
  43885. }
  43886. return this;
  43887. };
  43888. InstancedMesh.prototype._generatePointsArray = function () {
  43889. return this._sourceMesh._generatePointsArray();
  43890. };
  43891. /**
  43892. * Creates a new InstancedMesh from the current mesh.
  43893. * - name (string) : the cloned mesh name
  43894. * - newParent (optional Node) : the optional Node to parent the clone to.
  43895. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43896. *
  43897. * Returns the clone.
  43898. */
  43899. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43900. var result = this._sourceMesh.createInstance(name);
  43901. // Deep copy
  43902. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43903. // Bounding info
  43904. this.refreshBoundingInfo();
  43905. // Parent
  43906. if (newParent) {
  43907. result.parent = newParent;
  43908. }
  43909. if (!doNotCloneChildren) {
  43910. // Children
  43911. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43912. var mesh = this.getScene().meshes[index];
  43913. if (mesh.parent === this) {
  43914. mesh.clone(mesh.name, result);
  43915. }
  43916. }
  43917. }
  43918. result.computeWorldMatrix(true);
  43919. return result;
  43920. };
  43921. /**
  43922. * Disposes the InstancedMesh.
  43923. * Returns nothing.
  43924. */
  43925. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43926. // Remove from mesh
  43927. var index = this._sourceMesh.instances.indexOf(this);
  43928. this._sourceMesh.instances.splice(index, 1);
  43929. _super.prototype.dispose.call(this, doNotRecurse);
  43930. };
  43931. return InstancedMesh;
  43932. }(BABYLON.AbstractMesh));
  43933. BABYLON.InstancedMesh = InstancedMesh;
  43934. })(BABYLON || (BABYLON = {}));
  43935. //# sourceMappingURL=babylon.instancedMesh.js.map
  43936. /// <reference path="babylon.mesh.ts" />
  43937. var BABYLON;
  43938. (function (BABYLON) {
  43939. var LinesMesh = (function (_super) {
  43940. __extends(LinesMesh, _super);
  43941. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43942. if (parent === void 0) { parent = null; }
  43943. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43944. _this.useVertexColor = useVertexColor;
  43945. _this.color = new BABYLON.Color3(1, 1, 1);
  43946. _this.alpha = 1;
  43947. if (source) {
  43948. _this.color = source.color.clone();
  43949. _this.alpha = source.alpha;
  43950. _this.useVertexColor = source.useVertexColor;
  43951. }
  43952. _this._intersectionThreshold = 0.1;
  43953. var options = {
  43954. attributes: [BABYLON.VertexBuffer.PositionKind],
  43955. uniforms: ["world", "viewProjection"],
  43956. needAlphaBlending: false,
  43957. };
  43958. if (!useVertexColor) {
  43959. options.uniforms.push("color");
  43960. options.needAlphaBlending = true;
  43961. }
  43962. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43963. return _this;
  43964. }
  43965. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43966. /**
  43967. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43968. * This margin is expressed in world space coordinates, so its value may vary.
  43969. * Default value is 0.1
  43970. * @returns the intersection Threshold value.
  43971. */
  43972. get: function () {
  43973. return this._intersectionThreshold;
  43974. },
  43975. /**
  43976. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43977. * This margin is expressed in world space coordinates, so its value may vary.
  43978. * @param value the new threshold to apply
  43979. */
  43980. set: function (value) {
  43981. if (this._intersectionThreshold === value) {
  43982. return;
  43983. }
  43984. this._intersectionThreshold = value;
  43985. if (this.geometry) {
  43986. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43987. }
  43988. },
  43989. enumerable: true,
  43990. configurable: true
  43991. });
  43992. /**
  43993. * Returns the string "LineMesh"
  43994. */
  43995. LinesMesh.prototype.getClassName = function () {
  43996. return "LinesMesh";
  43997. };
  43998. Object.defineProperty(LinesMesh.prototype, "material", {
  43999. get: function () {
  44000. return this._colorShader;
  44001. },
  44002. enumerable: true,
  44003. configurable: true
  44004. });
  44005. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  44006. get: function () {
  44007. return false;
  44008. },
  44009. enumerable: true,
  44010. configurable: true
  44011. });
  44012. LinesMesh.prototype.createInstance = function (name) {
  44013. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  44014. return null;
  44015. };
  44016. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  44017. // VBOs
  44018. this._geometry._bind(this._colorShader.getEffect());
  44019. // Color
  44020. if (!this.useVertexColor) {
  44021. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  44022. }
  44023. return this;
  44024. };
  44025. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  44026. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  44027. return this;
  44028. }
  44029. var engine = this.getScene().getEngine();
  44030. // Draw order
  44031. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  44032. return this;
  44033. };
  44034. LinesMesh.prototype.dispose = function (doNotRecurse) {
  44035. this._colorShader.dispose();
  44036. _super.prototype.dispose.call(this, doNotRecurse);
  44037. };
  44038. /**
  44039. * Returns a new LineMesh object cloned from the current one.
  44040. */
  44041. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44042. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  44043. };
  44044. return LinesMesh;
  44045. }(BABYLON.Mesh));
  44046. BABYLON.LinesMesh = LinesMesh;
  44047. })(BABYLON || (BABYLON = {}));
  44048. //# sourceMappingURL=babylon.linesMesh.js.map
  44049. var BABYLON;
  44050. (function (BABYLON) {
  44051. var StandardMaterialDefines = (function (_super) {
  44052. __extends(StandardMaterialDefines, _super);
  44053. function StandardMaterialDefines() {
  44054. var _this = _super.call(this) || this;
  44055. _this.MAINUV1 = false;
  44056. _this.MAINUV2 = false;
  44057. _this.DIFFUSE = false;
  44058. _this.DIFFUSEDIRECTUV = 0;
  44059. _this.AMBIENT = false;
  44060. _this.AMBIENTDIRECTUV = 0;
  44061. _this.OPACITY = false;
  44062. _this.OPACITYDIRECTUV = 0;
  44063. _this.OPACITYRGB = false;
  44064. _this.REFLECTION = false;
  44065. _this.EMISSIVE = false;
  44066. _this.EMISSIVEDIRECTUV = 0;
  44067. _this.SPECULAR = false;
  44068. _this.SPECULARDIRECTUV = 0;
  44069. _this.BUMP = false;
  44070. _this.BUMPDIRECTUV = 0;
  44071. _this.PARALLAX = false;
  44072. _this.PARALLAXOCCLUSION = false;
  44073. _this.SPECULAROVERALPHA = false;
  44074. _this.CLIPPLANE = false;
  44075. _this.ALPHATEST = false;
  44076. _this.ALPHAFROMDIFFUSE = false;
  44077. _this.POINTSIZE = false;
  44078. _this.FOG = false;
  44079. _this.SPECULARTERM = false;
  44080. _this.DIFFUSEFRESNEL = false;
  44081. _this.OPACITYFRESNEL = false;
  44082. _this.REFLECTIONFRESNEL = false;
  44083. _this.REFRACTIONFRESNEL = false;
  44084. _this.EMISSIVEFRESNEL = false;
  44085. _this.FRESNEL = false;
  44086. _this.NORMAL = false;
  44087. _this.UV1 = false;
  44088. _this.UV2 = false;
  44089. _this.VERTEXCOLOR = false;
  44090. _this.VERTEXALPHA = false;
  44091. _this.NUM_BONE_INFLUENCERS = 0;
  44092. _this.BonesPerMesh = 0;
  44093. _this.INSTANCES = false;
  44094. _this.GLOSSINESS = false;
  44095. _this.ROUGHNESS = false;
  44096. _this.EMISSIVEASILLUMINATION = false;
  44097. _this.LINKEMISSIVEWITHDIFFUSE = false;
  44098. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  44099. _this.LIGHTMAP = false;
  44100. _this.LIGHTMAPDIRECTUV = 0;
  44101. _this.USELIGHTMAPASSHADOWMAP = false;
  44102. _this.REFLECTIONMAP_3D = false;
  44103. _this.REFLECTIONMAP_SPHERICAL = false;
  44104. _this.REFLECTIONMAP_PLANAR = false;
  44105. _this.REFLECTIONMAP_CUBIC = false;
  44106. _this.REFLECTIONMAP_PROJECTION = false;
  44107. _this.REFLECTIONMAP_SKYBOX = false;
  44108. _this.REFLECTIONMAP_EXPLICIT = false;
  44109. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44110. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44111. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44112. _this.INVERTCUBICMAP = false;
  44113. _this.LOGARITHMICDEPTH = false;
  44114. _this.REFRACTION = false;
  44115. _this.REFRACTIONMAP_3D = false;
  44116. _this.REFLECTIONOVERALPHA = false;
  44117. _this.TWOSIDEDLIGHTING = false;
  44118. _this.SHADOWFLOAT = false;
  44119. _this.MORPHTARGETS = false;
  44120. _this.MORPHTARGETS_NORMAL = false;
  44121. _this.MORPHTARGETS_TANGENT = false;
  44122. _this.NUM_MORPH_INFLUENCERS = 0;
  44123. _this.USERIGHTHANDEDSYSTEM = false;
  44124. _this.IMAGEPROCESSING = false;
  44125. _this.VIGNETTE = false;
  44126. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44127. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44128. _this.TONEMAPPING = false;
  44129. _this.CONTRAST = false;
  44130. _this.COLORCURVES = false;
  44131. _this.COLORGRADING = false;
  44132. _this.SAMPLER3DGREENDEPTH = false;
  44133. _this.SAMPLER3DBGRMAP = false;
  44134. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44135. _this.EXPOSURE = false;
  44136. _this.rebuild();
  44137. return _this;
  44138. }
  44139. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  44140. var modes = [
  44141. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  44142. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  44143. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  44144. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  44145. ];
  44146. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  44147. var mode = modes_1[_i];
  44148. this[mode] = (mode === modeToEnable);
  44149. }
  44150. };
  44151. return StandardMaterialDefines;
  44152. }(BABYLON.MaterialDefines));
  44153. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  44154. var StandardMaterial = (function (_super) {
  44155. __extends(StandardMaterial, _super);
  44156. function StandardMaterial(name, scene) {
  44157. var _this = _super.call(this, name, scene) || this;
  44158. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44159. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  44160. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  44161. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44162. _this.specularPower = 64;
  44163. _this._useAlphaFromDiffuseTexture = false;
  44164. _this._useEmissiveAsIllumination = false;
  44165. _this._linkEmissiveWithDiffuse = false;
  44166. _this._useSpecularOverAlpha = false;
  44167. _this._useReflectionOverAlpha = false;
  44168. _this._disableLighting = false;
  44169. _this._useParallax = false;
  44170. _this._useParallaxOcclusion = false;
  44171. _this.parallaxScaleBias = 0.05;
  44172. _this._roughness = 0;
  44173. _this.indexOfRefraction = 0.98;
  44174. _this.invertRefractionY = true;
  44175. _this._useLightmapAsShadowmap = false;
  44176. _this._useReflectionFresnelFromSpecular = false;
  44177. _this._useGlossinessFromSpecularMapAlpha = false;
  44178. _this._maxSimultaneousLights = 4;
  44179. /**
  44180. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44181. */
  44182. _this._invertNormalMapX = false;
  44183. /**
  44184. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44185. */
  44186. _this._invertNormalMapY = false;
  44187. /**
  44188. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44189. */
  44190. _this._twoSidedLighting = false;
  44191. _this._renderTargets = new BABYLON.SmartArray(16);
  44192. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44193. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44194. // Setup the default processing configuration to the scene.
  44195. _this._attachImageProcessingConfiguration(null);
  44196. _this.getRenderTargetTextures = function () {
  44197. _this._renderTargets.reset();
  44198. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44199. _this._renderTargets.push(_this._reflectionTexture);
  44200. }
  44201. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44202. _this._renderTargets.push(_this._refractionTexture);
  44203. }
  44204. return _this._renderTargets;
  44205. };
  44206. return _this;
  44207. }
  44208. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  44209. /**
  44210. * Gets the image processing configuration used either in this material.
  44211. */
  44212. get: function () {
  44213. return this._imageProcessingConfiguration;
  44214. },
  44215. /**
  44216. * Sets the Default image processing configuration used either in the this material.
  44217. *
  44218. * If sets to null, the scene one is in use.
  44219. */
  44220. set: function (value) {
  44221. this._attachImageProcessingConfiguration(value);
  44222. // Ensure the effect will be rebuilt.
  44223. this._markAllSubMeshesAsTexturesDirty();
  44224. },
  44225. enumerable: true,
  44226. configurable: true
  44227. });
  44228. /**
  44229. * Attaches a new image processing configuration to the Standard Material.
  44230. * @param configuration
  44231. */
  44232. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44233. var _this = this;
  44234. if (configuration === this._imageProcessingConfiguration) {
  44235. return;
  44236. }
  44237. // Detaches observer.
  44238. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44239. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44240. }
  44241. // Pick the scene configuration if needed.
  44242. if (!configuration) {
  44243. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44244. }
  44245. else {
  44246. this._imageProcessingConfiguration = configuration;
  44247. }
  44248. // Attaches observer.
  44249. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44250. _this._markAllSubMeshesAsImageProcessingDirty();
  44251. });
  44252. };
  44253. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  44254. /**
  44255. * Gets wether the color curves effect is enabled.
  44256. */
  44257. get: function () {
  44258. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44259. },
  44260. /**
  44261. * Sets wether the color curves effect is enabled.
  44262. */
  44263. set: function (value) {
  44264. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44265. },
  44266. enumerable: true,
  44267. configurable: true
  44268. });
  44269. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  44270. /**
  44271. * Gets wether the color grading effect is enabled.
  44272. */
  44273. get: function () {
  44274. return this.imageProcessingConfiguration.colorGradingEnabled;
  44275. },
  44276. /**
  44277. * Gets wether the color grading effect is enabled.
  44278. */
  44279. set: function (value) {
  44280. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44281. },
  44282. enumerable: true,
  44283. configurable: true
  44284. });
  44285. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  44286. /**
  44287. * Gets wether tonemapping is enabled or not.
  44288. */
  44289. get: function () {
  44290. return this._imageProcessingConfiguration.toneMappingEnabled;
  44291. },
  44292. /**
  44293. * Sets wether tonemapping is enabled or not
  44294. */
  44295. set: function (value) {
  44296. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44297. },
  44298. enumerable: true,
  44299. configurable: true
  44300. });
  44301. ;
  44302. ;
  44303. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44304. /**
  44305. * The camera exposure used on this material.
  44306. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44307. * This corresponds to a photographic exposure.
  44308. */
  44309. get: function () {
  44310. return this._imageProcessingConfiguration.exposure;
  44311. },
  44312. /**
  44313. * The camera exposure used on this material.
  44314. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44315. * This corresponds to a photographic exposure.
  44316. */
  44317. set: function (value) {
  44318. this._imageProcessingConfiguration.exposure = value;
  44319. },
  44320. enumerable: true,
  44321. configurable: true
  44322. });
  44323. ;
  44324. ;
  44325. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44326. /**
  44327. * Gets The camera contrast used on this material.
  44328. */
  44329. get: function () {
  44330. return this._imageProcessingConfiguration.contrast;
  44331. },
  44332. /**
  44333. * Sets The camera contrast used on this material.
  44334. */
  44335. set: function (value) {
  44336. this._imageProcessingConfiguration.contrast = value;
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44342. /**
  44343. * Gets the Color Grading 2D Lookup Texture.
  44344. */
  44345. get: function () {
  44346. return this._imageProcessingConfiguration.colorGradingTexture;
  44347. },
  44348. /**
  44349. * Sets the Color Grading 2D Lookup Texture.
  44350. */
  44351. set: function (value) {
  44352. this._imageProcessingConfiguration.colorGradingTexture = value;
  44353. },
  44354. enumerable: true,
  44355. configurable: true
  44356. });
  44357. StandardMaterial.prototype.getClassName = function () {
  44358. return "StandardMaterial";
  44359. };
  44360. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44361. get: function () {
  44362. return this._useLogarithmicDepth;
  44363. },
  44364. set: function (value) {
  44365. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44366. this._markAllSubMeshesAsMiscDirty();
  44367. },
  44368. enumerable: true,
  44369. configurable: true
  44370. });
  44371. StandardMaterial.prototype.needAlphaBlending = function () {
  44372. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44373. };
  44374. StandardMaterial.prototype.needAlphaTesting = function () {
  44375. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44376. };
  44377. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44378. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44379. };
  44380. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44381. return this._diffuseTexture;
  44382. };
  44383. /**
  44384. * Child classes can use it to update shaders
  44385. */
  44386. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44387. if (this.isFrozen) {
  44388. if (this._wasPreviouslyReady && subMesh.effect) {
  44389. return true;
  44390. }
  44391. }
  44392. if (!subMesh._materialDefines) {
  44393. subMesh._materialDefines = new StandardMaterialDefines();
  44394. }
  44395. var scene = this.getScene();
  44396. var defines = subMesh._materialDefines;
  44397. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44398. if (defines._renderId === scene.getRenderId()) {
  44399. return true;
  44400. }
  44401. }
  44402. var engine = scene.getEngine();
  44403. // Lights
  44404. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44405. // Textures
  44406. if (defines._areTexturesDirty) {
  44407. defines._needUVs = false;
  44408. defines.MAINUV1 = false;
  44409. defines.MAINUV2 = false;
  44410. if (scene.texturesEnabled) {
  44411. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44412. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44413. return false;
  44414. }
  44415. else {
  44416. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44417. }
  44418. }
  44419. else {
  44420. defines.DIFFUSE = false;
  44421. }
  44422. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44423. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44424. return false;
  44425. }
  44426. else {
  44427. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44428. }
  44429. }
  44430. else {
  44431. defines.AMBIENT = false;
  44432. }
  44433. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44434. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44435. return false;
  44436. }
  44437. else {
  44438. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44439. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44440. }
  44441. }
  44442. else {
  44443. defines.OPACITY = false;
  44444. }
  44445. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44446. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44447. return false;
  44448. }
  44449. else {
  44450. defines._needNormals = true;
  44451. defines.REFLECTION = true;
  44452. defines.ROUGHNESS = (this._roughness > 0);
  44453. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44454. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44455. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44456. switch (this._reflectionTexture.coordinatesMode) {
  44457. case BABYLON.Texture.CUBIC_MODE:
  44458. case BABYLON.Texture.INVCUBIC_MODE:
  44459. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44460. break;
  44461. case BABYLON.Texture.EXPLICIT_MODE:
  44462. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44463. break;
  44464. case BABYLON.Texture.PLANAR_MODE:
  44465. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44466. break;
  44467. case BABYLON.Texture.PROJECTION_MODE:
  44468. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44469. break;
  44470. case BABYLON.Texture.SKYBOX_MODE:
  44471. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44472. break;
  44473. case BABYLON.Texture.SPHERICAL_MODE:
  44474. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44475. break;
  44476. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44477. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44478. break;
  44479. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44480. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44481. break;
  44482. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44483. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44484. break;
  44485. }
  44486. }
  44487. }
  44488. else {
  44489. defines.REFLECTION = false;
  44490. }
  44491. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44492. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44493. return false;
  44494. }
  44495. else {
  44496. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44497. }
  44498. }
  44499. else {
  44500. defines.EMISSIVE = false;
  44501. }
  44502. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44503. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44504. return false;
  44505. }
  44506. else {
  44507. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44508. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44509. }
  44510. }
  44511. else {
  44512. defines.LIGHTMAP = false;
  44513. }
  44514. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44515. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44516. return false;
  44517. }
  44518. else {
  44519. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44520. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44521. }
  44522. }
  44523. else {
  44524. defines.SPECULAR = false;
  44525. }
  44526. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44527. // Bump texure can not be not blocking.
  44528. if (!this._bumpTexture.isReady()) {
  44529. return false;
  44530. }
  44531. else {
  44532. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44533. defines.PARALLAX = this._useParallax;
  44534. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44535. }
  44536. }
  44537. else {
  44538. defines.BUMP = false;
  44539. }
  44540. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44541. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44542. return false;
  44543. }
  44544. else {
  44545. defines._needUVs = true;
  44546. defines.REFRACTION = true;
  44547. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44548. }
  44549. }
  44550. else {
  44551. defines.REFRACTION = false;
  44552. }
  44553. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44554. }
  44555. else {
  44556. defines.DIFFUSE = false;
  44557. defines.AMBIENT = false;
  44558. defines.OPACITY = false;
  44559. defines.REFLECTION = false;
  44560. defines.EMISSIVE = false;
  44561. defines.LIGHTMAP = false;
  44562. defines.BUMP = false;
  44563. defines.REFRACTION = false;
  44564. }
  44565. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44566. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44567. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44568. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44569. }
  44570. if (defines._areImageProcessingDirty) {
  44571. if (!this._imageProcessingConfiguration.isReady()) {
  44572. return false;
  44573. }
  44574. this._imageProcessingConfiguration.prepareDefines(defines);
  44575. }
  44576. if (defines._areFresnelDirty) {
  44577. if (StandardMaterial.FresnelEnabled) {
  44578. // Fresnel
  44579. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44580. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44581. this._reflectionFresnelParameters) {
  44582. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44583. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44584. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44585. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44586. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44587. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44588. defines._needNormals = true;
  44589. defines.FRESNEL = true;
  44590. }
  44591. }
  44592. else {
  44593. defines.FRESNEL = false;
  44594. }
  44595. }
  44596. // Misc.
  44597. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  44598. // Attribs
  44599. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44600. // Values that need to be evaluated on every frame
  44601. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44602. // Get correct effect
  44603. if (defines.isDirty) {
  44604. defines.markAsProcessed();
  44605. scene.resetCachedMaterial();
  44606. // Fallbacks
  44607. var fallbacks = new BABYLON.EffectFallbacks();
  44608. if (defines.REFLECTION) {
  44609. fallbacks.addFallback(0, "REFLECTION");
  44610. }
  44611. if (defines.SPECULAR) {
  44612. fallbacks.addFallback(0, "SPECULAR");
  44613. }
  44614. if (defines.BUMP) {
  44615. fallbacks.addFallback(0, "BUMP");
  44616. }
  44617. if (defines.PARALLAX) {
  44618. fallbacks.addFallback(1, "PARALLAX");
  44619. }
  44620. if (defines.PARALLAXOCCLUSION) {
  44621. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44622. }
  44623. if (defines.SPECULAROVERALPHA) {
  44624. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44625. }
  44626. if (defines.FOG) {
  44627. fallbacks.addFallback(1, "FOG");
  44628. }
  44629. if (defines.POINTSIZE) {
  44630. fallbacks.addFallback(0, "POINTSIZE");
  44631. }
  44632. if (defines.LOGARITHMICDEPTH) {
  44633. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44634. }
  44635. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44636. if (defines.SPECULARTERM) {
  44637. fallbacks.addFallback(0, "SPECULARTERM");
  44638. }
  44639. if (defines.DIFFUSEFRESNEL) {
  44640. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44641. }
  44642. if (defines.OPACITYFRESNEL) {
  44643. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44644. }
  44645. if (defines.REFLECTIONFRESNEL) {
  44646. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44647. }
  44648. if (defines.EMISSIVEFRESNEL) {
  44649. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44650. }
  44651. if (defines.FRESNEL) {
  44652. fallbacks.addFallback(4, "FRESNEL");
  44653. }
  44654. //Attributes
  44655. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44656. if (defines.NORMAL) {
  44657. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44658. }
  44659. if (defines.UV1) {
  44660. attribs.push(BABYLON.VertexBuffer.UVKind);
  44661. }
  44662. if (defines.UV2) {
  44663. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44664. }
  44665. if (defines.VERTEXCOLOR) {
  44666. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44667. }
  44668. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44669. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44670. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44671. var shaderName = "default";
  44672. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44673. "vFogInfos", "vFogColor", "pointSize",
  44674. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44675. "mBones",
  44676. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44677. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44678. "logarithmicDepthConstant", "vNormalReoderParams"
  44679. ];
  44680. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44681. var uniformBuffers = ["Material", "Scene"];
  44682. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44683. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44684. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44685. uniformsNames: uniforms,
  44686. uniformBuffersNames: uniformBuffers,
  44687. samplers: samplers,
  44688. defines: defines,
  44689. maxSimultaneousLights: this._maxSimultaneousLights
  44690. });
  44691. if (this.customShaderNameResolve) {
  44692. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44693. }
  44694. var join = defines.toString();
  44695. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  44696. attributes: attribs,
  44697. uniformsNames: uniforms,
  44698. uniformBuffersNames: uniformBuffers,
  44699. samplers: samplers,
  44700. defines: join,
  44701. fallbacks: fallbacks,
  44702. onCompiled: this.onCompiled,
  44703. onError: this.onError,
  44704. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44705. }, engine), defines);
  44706. this.buildUniformLayout();
  44707. }
  44708. if (!subMesh.effect.isReady()) {
  44709. return false;
  44710. }
  44711. defines._renderId = scene.getRenderId();
  44712. this._wasPreviouslyReady = true;
  44713. return true;
  44714. };
  44715. StandardMaterial.prototype.buildUniformLayout = function () {
  44716. // Order is important !
  44717. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44718. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44719. this._uniformBuffer.addUniform("opacityParts", 4);
  44720. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44721. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44722. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44723. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44724. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44725. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44726. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44727. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44728. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44729. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44730. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44731. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44732. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44733. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44734. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44735. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44736. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44737. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44738. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44739. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44740. this._uniformBuffer.addUniform("specularMatrix", 16);
  44741. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44742. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44743. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44744. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44745. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44746. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44747. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44748. this._uniformBuffer.addUniform("pointSize", 1);
  44749. this._uniformBuffer.create();
  44750. };
  44751. StandardMaterial.prototype.unbind = function () {
  44752. if (this._activeEffect) {
  44753. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44754. this._activeEffect.setTexture("reflection2DSampler", null);
  44755. }
  44756. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44757. this._activeEffect.setTexture("refraction2DSampler", null);
  44758. }
  44759. }
  44760. _super.prototype.unbind.call(this);
  44761. };
  44762. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44763. var scene = this.getScene();
  44764. var defines = subMesh._materialDefines;
  44765. if (!defines) {
  44766. return;
  44767. }
  44768. var effect = subMesh.effect;
  44769. this._activeEffect = effect;
  44770. // Matrices
  44771. this.bindOnlyWorldMatrix(world);
  44772. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44773. // Bones
  44774. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44775. if (mustRebind) {
  44776. this._uniformBuffer.bindToEffect(effect, "Material");
  44777. this.bindViewProjection(effect);
  44778. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44779. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44780. // Fresnel
  44781. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44782. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44783. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44784. }
  44785. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44786. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44787. }
  44788. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44789. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44790. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44791. }
  44792. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44793. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44794. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44795. }
  44796. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44797. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44798. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44799. }
  44800. }
  44801. // Textures
  44802. if (scene.texturesEnabled) {
  44803. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44804. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44805. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44806. }
  44807. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44808. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44809. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44810. }
  44811. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44812. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44813. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44814. }
  44815. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44816. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44817. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44818. }
  44819. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44820. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44821. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44822. }
  44823. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44824. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44825. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44826. }
  44827. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44828. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44829. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44830. }
  44831. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44832. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44833. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44834. if (scene._mirroredCameraPosition) {
  44835. 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);
  44836. }
  44837. else {
  44838. 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);
  44839. }
  44840. }
  44841. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44842. var depth = 1.0;
  44843. if (!this._refractionTexture.isCube) {
  44844. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44845. if (this._refractionTexture.depth) {
  44846. depth = this._refractionTexture.depth;
  44847. }
  44848. }
  44849. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44850. }
  44851. }
  44852. // Point size
  44853. if (this.pointsCloud) {
  44854. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44855. }
  44856. if (defines.SPECULARTERM) {
  44857. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44858. }
  44859. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44860. // Diffuse
  44861. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44862. }
  44863. // Textures
  44864. if (scene.texturesEnabled) {
  44865. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44866. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44867. }
  44868. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44869. effect.setTexture("ambientSampler", this._ambientTexture);
  44870. }
  44871. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44872. effect.setTexture("opacitySampler", this._opacityTexture);
  44873. }
  44874. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44875. if (this._reflectionTexture.isCube) {
  44876. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44877. }
  44878. else {
  44879. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44880. }
  44881. }
  44882. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44883. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44884. }
  44885. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44886. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44887. }
  44888. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44889. effect.setTexture("specularSampler", this._specularTexture);
  44890. }
  44891. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44892. effect.setTexture("bumpSampler", this._bumpTexture);
  44893. }
  44894. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44895. var depth = 1.0;
  44896. if (this._refractionTexture.isCube) {
  44897. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44898. }
  44899. else {
  44900. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44901. }
  44902. }
  44903. }
  44904. // Clip plane
  44905. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44906. // Colors
  44907. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44908. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44909. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44910. }
  44911. if (mustRebind || !this.isFrozen) {
  44912. // Lights
  44913. if (scene.lightsEnabled && !this._disableLighting) {
  44914. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44915. }
  44916. // View
  44917. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44918. this.bindView(effect);
  44919. }
  44920. // Fog
  44921. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44922. // Morph targets
  44923. if (defines.NUM_MORPH_INFLUENCERS) {
  44924. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44925. }
  44926. // Log. depth
  44927. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44928. // image processing
  44929. this._imageProcessingConfiguration.bind(this._activeEffect);
  44930. }
  44931. this._uniformBuffer.update();
  44932. this._afterBind(mesh, this._activeEffect);
  44933. };
  44934. StandardMaterial.prototype.getAnimatables = function () {
  44935. var results = [];
  44936. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44937. results.push(this._diffuseTexture);
  44938. }
  44939. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44940. results.push(this._ambientTexture);
  44941. }
  44942. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44943. results.push(this._opacityTexture);
  44944. }
  44945. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44946. results.push(this._reflectionTexture);
  44947. }
  44948. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44949. results.push(this._emissiveTexture);
  44950. }
  44951. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44952. results.push(this._specularTexture);
  44953. }
  44954. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44955. results.push(this._bumpTexture);
  44956. }
  44957. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44958. results.push(this._lightmapTexture);
  44959. }
  44960. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44961. results.push(this._refractionTexture);
  44962. }
  44963. return results;
  44964. };
  44965. StandardMaterial.prototype.getActiveTextures = function () {
  44966. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44967. if (this._diffuseTexture) {
  44968. activeTextures.push(this._diffuseTexture);
  44969. }
  44970. if (this._ambientTexture) {
  44971. activeTextures.push(this._ambientTexture);
  44972. }
  44973. if (this._opacityTexture) {
  44974. activeTextures.push(this._opacityTexture);
  44975. }
  44976. if (this._reflectionTexture) {
  44977. activeTextures.push(this._reflectionTexture);
  44978. }
  44979. if (this._emissiveTexture) {
  44980. activeTextures.push(this._emissiveTexture);
  44981. }
  44982. if (this._specularTexture) {
  44983. activeTextures.push(this._specularTexture);
  44984. }
  44985. if (this._bumpTexture) {
  44986. activeTextures.push(this._bumpTexture);
  44987. }
  44988. if (this._lightmapTexture) {
  44989. activeTextures.push(this._lightmapTexture);
  44990. }
  44991. if (this._refractionTexture) {
  44992. activeTextures.push(this._refractionTexture);
  44993. }
  44994. return activeTextures;
  44995. };
  44996. StandardMaterial.prototype.hasTexture = function (texture) {
  44997. if (_super.prototype.hasTexture.call(this, texture)) {
  44998. return true;
  44999. }
  45000. if (this._diffuseTexture === texture) {
  45001. return true;
  45002. }
  45003. if (this._ambientTexture === texture) {
  45004. return true;
  45005. }
  45006. if (this._opacityTexture === texture) {
  45007. return true;
  45008. }
  45009. if (this._reflectionTexture === texture) {
  45010. return true;
  45011. }
  45012. if (this._emissiveTexture === texture) {
  45013. return true;
  45014. }
  45015. if (this._specularTexture === texture) {
  45016. return true;
  45017. }
  45018. if (this._bumpTexture === texture) {
  45019. return true;
  45020. }
  45021. if (this._lightmapTexture === texture) {
  45022. return true;
  45023. }
  45024. if (this._refractionTexture === texture) {
  45025. return true;
  45026. }
  45027. return false;
  45028. };
  45029. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45030. if (forceDisposeTextures) {
  45031. if (this._diffuseTexture) {
  45032. this._diffuseTexture.dispose();
  45033. }
  45034. if (this._ambientTexture) {
  45035. this._ambientTexture.dispose();
  45036. }
  45037. if (this._opacityTexture) {
  45038. this._opacityTexture.dispose();
  45039. }
  45040. if (this._reflectionTexture) {
  45041. this._reflectionTexture.dispose();
  45042. }
  45043. if (this._emissiveTexture) {
  45044. this._emissiveTexture.dispose();
  45045. }
  45046. if (this._specularTexture) {
  45047. this._specularTexture.dispose();
  45048. }
  45049. if (this._bumpTexture) {
  45050. this._bumpTexture.dispose();
  45051. }
  45052. if (this._lightmapTexture) {
  45053. this._lightmapTexture.dispose();
  45054. }
  45055. if (this._refractionTexture) {
  45056. this._refractionTexture.dispose();
  45057. }
  45058. }
  45059. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45060. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45061. }
  45062. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45063. };
  45064. StandardMaterial.prototype.clone = function (name) {
  45065. var _this = this;
  45066. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  45067. result.name = name;
  45068. result.id = name;
  45069. return result;
  45070. };
  45071. StandardMaterial.prototype.serialize = function () {
  45072. return BABYLON.SerializationHelper.Serialize(this);
  45073. };
  45074. // Statics
  45075. StandardMaterial.Parse = function (source, scene, rootUrl) {
  45076. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  45077. };
  45078. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  45079. get: function () {
  45080. return StandardMaterial._DiffuseTextureEnabled;
  45081. },
  45082. set: function (value) {
  45083. if (StandardMaterial._DiffuseTextureEnabled === value) {
  45084. return;
  45085. }
  45086. StandardMaterial._DiffuseTextureEnabled = value;
  45087. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  45093. get: function () {
  45094. return StandardMaterial._AmbientTextureEnabled;
  45095. },
  45096. set: function (value) {
  45097. if (StandardMaterial._AmbientTextureEnabled === value) {
  45098. return;
  45099. }
  45100. StandardMaterial._AmbientTextureEnabled = value;
  45101. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45102. },
  45103. enumerable: true,
  45104. configurable: true
  45105. });
  45106. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  45107. get: function () {
  45108. return StandardMaterial._OpacityTextureEnabled;
  45109. },
  45110. set: function (value) {
  45111. if (StandardMaterial._OpacityTextureEnabled === value) {
  45112. return;
  45113. }
  45114. StandardMaterial._OpacityTextureEnabled = value;
  45115. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45116. },
  45117. enumerable: true,
  45118. configurable: true
  45119. });
  45120. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  45121. get: function () {
  45122. return StandardMaterial._ReflectionTextureEnabled;
  45123. },
  45124. set: function (value) {
  45125. if (StandardMaterial._ReflectionTextureEnabled === value) {
  45126. return;
  45127. }
  45128. StandardMaterial._ReflectionTextureEnabled = value;
  45129. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45130. },
  45131. enumerable: true,
  45132. configurable: true
  45133. });
  45134. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  45135. get: function () {
  45136. return StandardMaterial._EmissiveTextureEnabled;
  45137. },
  45138. set: function (value) {
  45139. if (StandardMaterial._EmissiveTextureEnabled === value) {
  45140. return;
  45141. }
  45142. StandardMaterial._EmissiveTextureEnabled = value;
  45143. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45144. },
  45145. enumerable: true,
  45146. configurable: true
  45147. });
  45148. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  45149. get: function () {
  45150. return StandardMaterial._SpecularTextureEnabled;
  45151. },
  45152. set: function (value) {
  45153. if (StandardMaterial._SpecularTextureEnabled === value) {
  45154. return;
  45155. }
  45156. StandardMaterial._SpecularTextureEnabled = value;
  45157. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45158. },
  45159. enumerable: true,
  45160. configurable: true
  45161. });
  45162. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  45163. get: function () {
  45164. return StandardMaterial._BumpTextureEnabled;
  45165. },
  45166. set: function (value) {
  45167. if (StandardMaterial._BumpTextureEnabled === value) {
  45168. return;
  45169. }
  45170. StandardMaterial._BumpTextureEnabled = value;
  45171. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45172. },
  45173. enumerable: true,
  45174. configurable: true
  45175. });
  45176. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45177. get: function () {
  45178. return StandardMaterial._LightmapTextureEnabled;
  45179. },
  45180. set: function (value) {
  45181. if (StandardMaterial._LightmapTextureEnabled === value) {
  45182. return;
  45183. }
  45184. StandardMaterial._LightmapTextureEnabled = value;
  45185. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45186. },
  45187. enumerable: true,
  45188. configurable: true
  45189. });
  45190. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45191. get: function () {
  45192. return StandardMaterial._RefractionTextureEnabled;
  45193. },
  45194. set: function (value) {
  45195. if (StandardMaterial._RefractionTextureEnabled === value) {
  45196. return;
  45197. }
  45198. StandardMaterial._RefractionTextureEnabled = value;
  45199. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45200. },
  45201. enumerable: true,
  45202. configurable: true
  45203. });
  45204. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45205. get: function () {
  45206. return StandardMaterial._ColorGradingTextureEnabled;
  45207. },
  45208. set: function (value) {
  45209. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45210. return;
  45211. }
  45212. StandardMaterial._ColorGradingTextureEnabled = value;
  45213. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45214. },
  45215. enumerable: true,
  45216. configurable: true
  45217. });
  45218. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45219. get: function () {
  45220. return StandardMaterial._FresnelEnabled;
  45221. },
  45222. set: function (value) {
  45223. if (StandardMaterial._FresnelEnabled === value) {
  45224. return;
  45225. }
  45226. StandardMaterial._FresnelEnabled = value;
  45227. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. // Flags used to enable or disable a type of texture for all Standard Materials
  45233. StandardMaterial._DiffuseTextureEnabled = true;
  45234. StandardMaterial._AmbientTextureEnabled = true;
  45235. StandardMaterial._OpacityTextureEnabled = true;
  45236. StandardMaterial._ReflectionTextureEnabled = true;
  45237. StandardMaterial._EmissiveTextureEnabled = true;
  45238. StandardMaterial._SpecularTextureEnabled = true;
  45239. StandardMaterial._BumpTextureEnabled = true;
  45240. StandardMaterial._LightmapTextureEnabled = true;
  45241. StandardMaterial._RefractionTextureEnabled = true;
  45242. StandardMaterial._ColorGradingTextureEnabled = true;
  45243. StandardMaterial._FresnelEnabled = true;
  45244. __decorate([
  45245. BABYLON.serializeAsTexture("diffuseTexture")
  45246. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45247. __decorate([
  45248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45249. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45250. __decorate([
  45251. BABYLON.serializeAsTexture("ambientTexture")
  45252. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45253. __decorate([
  45254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45255. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45256. __decorate([
  45257. BABYLON.serializeAsTexture("opacityTexture")
  45258. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45259. __decorate([
  45260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45261. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45262. __decorate([
  45263. BABYLON.serializeAsTexture("reflectionTexture")
  45264. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45265. __decorate([
  45266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45267. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45268. __decorate([
  45269. BABYLON.serializeAsTexture("emissiveTexture")
  45270. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45271. __decorate([
  45272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45273. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45274. __decorate([
  45275. BABYLON.serializeAsTexture("specularTexture")
  45276. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45277. __decorate([
  45278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45279. ], StandardMaterial.prototype, "specularTexture", void 0);
  45280. __decorate([
  45281. BABYLON.serializeAsTexture("bumpTexture")
  45282. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45283. __decorate([
  45284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45285. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45286. __decorate([
  45287. BABYLON.serializeAsTexture("lightmapTexture")
  45288. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45289. __decorate([
  45290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45291. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45292. __decorate([
  45293. BABYLON.serializeAsTexture("refractionTexture")
  45294. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45295. __decorate([
  45296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45297. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45298. __decorate([
  45299. BABYLON.serializeAsColor3("ambient")
  45300. ], StandardMaterial.prototype, "ambientColor", void 0);
  45301. __decorate([
  45302. BABYLON.serializeAsColor3("diffuse")
  45303. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45304. __decorate([
  45305. BABYLON.serializeAsColor3("specular")
  45306. ], StandardMaterial.prototype, "specularColor", void 0);
  45307. __decorate([
  45308. BABYLON.serializeAsColor3("emissive")
  45309. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45310. __decorate([
  45311. BABYLON.serialize()
  45312. ], StandardMaterial.prototype, "specularPower", void 0);
  45313. __decorate([
  45314. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45315. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45316. __decorate([
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45318. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45319. __decorate([
  45320. BABYLON.serialize("useEmissiveAsIllumination")
  45321. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45322. __decorate([
  45323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45324. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45325. __decorate([
  45326. BABYLON.serialize("linkEmissiveWithDiffuse")
  45327. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45328. __decorate([
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45331. __decorate([
  45332. BABYLON.serialize("useSpecularOverAlpha")
  45333. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45334. __decorate([
  45335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45336. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45337. __decorate([
  45338. BABYLON.serialize("useReflectionOverAlpha")
  45339. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45340. __decorate([
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45342. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45343. __decorate([
  45344. BABYLON.serialize("disableLighting")
  45345. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45346. __decorate([
  45347. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45348. ], StandardMaterial.prototype, "disableLighting", void 0);
  45349. __decorate([
  45350. BABYLON.serialize("useParallax")
  45351. ], StandardMaterial.prototype, "_useParallax", void 0);
  45352. __decorate([
  45353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45354. ], StandardMaterial.prototype, "useParallax", void 0);
  45355. __decorate([
  45356. BABYLON.serialize("useParallaxOcclusion")
  45357. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45358. __decorate([
  45359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45360. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45361. __decorate([
  45362. BABYLON.serialize()
  45363. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45364. __decorate([
  45365. BABYLON.serialize("roughness")
  45366. ], StandardMaterial.prototype, "_roughness", void 0);
  45367. __decorate([
  45368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45369. ], StandardMaterial.prototype, "roughness", void 0);
  45370. __decorate([
  45371. BABYLON.serialize()
  45372. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45373. __decorate([
  45374. BABYLON.serialize()
  45375. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45376. __decorate([
  45377. BABYLON.serialize("useLightmapAsShadowmap")
  45378. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45379. __decorate([
  45380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45381. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45382. __decorate([
  45383. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45384. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45385. __decorate([
  45386. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45387. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45388. __decorate([
  45389. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45390. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45391. __decorate([
  45392. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45393. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45394. __decorate([
  45395. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45396. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45397. __decorate([
  45398. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45399. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45400. __decorate([
  45401. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45402. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45403. __decorate([
  45404. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45405. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45406. __decorate([
  45407. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45408. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45409. __decorate([
  45410. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45411. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45412. __decorate([
  45413. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45414. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45415. __decorate([
  45416. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45417. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45418. __decorate([
  45419. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45420. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45421. __decorate([
  45422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45423. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45424. __decorate([
  45425. BABYLON.serialize("maxSimultaneousLights")
  45426. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45427. __decorate([
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45429. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45430. __decorate([
  45431. BABYLON.serialize("invertNormalMapX")
  45432. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45433. __decorate([
  45434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45435. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45436. __decorate([
  45437. BABYLON.serialize("invertNormalMapY")
  45438. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45439. __decorate([
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45441. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45442. __decorate([
  45443. BABYLON.serialize("twoSidedLighting")
  45444. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45445. __decorate([
  45446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45447. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45448. __decorate([
  45449. BABYLON.serialize()
  45450. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45451. return StandardMaterial;
  45452. }(BABYLON.PushMaterial));
  45453. BABYLON.StandardMaterial = StandardMaterial;
  45454. })(BABYLON || (BABYLON = {}));
  45455. //# sourceMappingURL=babylon.standardMaterial.js.map
  45456. var BABYLON;
  45457. (function (BABYLON) {
  45458. /**
  45459. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45460. * The underlying implementation relies on an associative array to ensure the best performances.
  45461. * The value can be anything including 'null' but except 'undefined'
  45462. */
  45463. var StringDictionary = (function () {
  45464. function StringDictionary() {
  45465. this._count = 0;
  45466. this._data = {};
  45467. }
  45468. /**
  45469. * This will clear this dictionary and copy the content from the 'source' one.
  45470. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45471. * @param source the dictionary to take the content from and copy to this dictionary
  45472. */
  45473. StringDictionary.prototype.copyFrom = function (source) {
  45474. var _this = this;
  45475. this.clear();
  45476. source.forEach(function (t, v) { return _this.add(t, v); });
  45477. };
  45478. /**
  45479. * Get a value based from its key
  45480. * @param key the given key to get the matching value from
  45481. * @return the value if found, otherwise undefined is returned
  45482. */
  45483. StringDictionary.prototype.get = function (key) {
  45484. var val = this._data[key];
  45485. if (val !== undefined) {
  45486. return val;
  45487. }
  45488. return undefined;
  45489. };
  45490. /**
  45491. * Get a value from its key or add it if it doesn't exist.
  45492. * This method will ensure you that a given key/data will be present in the dictionary.
  45493. * @param key the given key to get the matching value from
  45494. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45495. * The factory will only be invoked if there's no data for the given key.
  45496. * @return the value corresponding to the key.
  45497. */
  45498. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45499. var val = this.get(key);
  45500. if (val !== undefined) {
  45501. return val;
  45502. }
  45503. val = factory(key);
  45504. if (val) {
  45505. this.add(key, val);
  45506. }
  45507. return val;
  45508. };
  45509. /**
  45510. * Get a value from its key if present in the dictionary otherwise add it
  45511. * @param key the key to get the value from
  45512. * @param val if there's no such key/value pair in the dictionary add it with this value
  45513. * @return the value corresponding to the key
  45514. */
  45515. StringDictionary.prototype.getOrAdd = function (key, val) {
  45516. var curVal = this.get(key);
  45517. if (curVal !== undefined) {
  45518. return curVal;
  45519. }
  45520. this.add(key, val);
  45521. return val;
  45522. };
  45523. /**
  45524. * Check if there's a given key in the dictionary
  45525. * @param key the key to check for
  45526. * @return true if the key is present, false otherwise
  45527. */
  45528. StringDictionary.prototype.contains = function (key) {
  45529. return this._data[key] !== undefined;
  45530. };
  45531. /**
  45532. * Add a new key and its corresponding value
  45533. * @param key the key to add
  45534. * @param value the value corresponding to the key
  45535. * @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
  45536. */
  45537. StringDictionary.prototype.add = function (key, value) {
  45538. if (this._data[key] !== undefined) {
  45539. return false;
  45540. }
  45541. this._data[key] = value;
  45542. ++this._count;
  45543. return true;
  45544. };
  45545. StringDictionary.prototype.set = function (key, value) {
  45546. if (this._data[key] === undefined) {
  45547. return false;
  45548. }
  45549. this._data[key] = value;
  45550. return true;
  45551. };
  45552. /**
  45553. * Get the element of the given key and remove it from the dictionary
  45554. * @param key
  45555. */
  45556. StringDictionary.prototype.getAndRemove = function (key) {
  45557. var val = this.get(key);
  45558. if (val !== undefined) {
  45559. delete this._data[key];
  45560. --this._count;
  45561. return val;
  45562. }
  45563. return null;
  45564. };
  45565. /**
  45566. * Remove a key/value from the dictionary.
  45567. * @param key the key to remove
  45568. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45569. */
  45570. StringDictionary.prototype.remove = function (key) {
  45571. if (this.contains(key)) {
  45572. delete this._data[key];
  45573. --this._count;
  45574. return true;
  45575. }
  45576. return false;
  45577. };
  45578. /**
  45579. * Clear the whole content of the dictionary
  45580. */
  45581. StringDictionary.prototype.clear = function () {
  45582. this._data = {};
  45583. this._count = 0;
  45584. };
  45585. Object.defineProperty(StringDictionary.prototype, "count", {
  45586. get: function () {
  45587. return this._count;
  45588. },
  45589. enumerable: true,
  45590. configurable: true
  45591. });
  45592. /**
  45593. * Execute a callback on each key/val of the dictionary.
  45594. * Note that you can remove any element in this dictionary in the callback implementation
  45595. * @param callback the callback to execute on a given key/value pair
  45596. */
  45597. StringDictionary.prototype.forEach = function (callback) {
  45598. for (var cur in this._data) {
  45599. var val = this._data[cur];
  45600. callback(cur, val);
  45601. }
  45602. };
  45603. /**
  45604. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45605. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45606. * Note that you can remove any element in this dictionary in the callback implementation
  45607. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45608. */
  45609. StringDictionary.prototype.first = function (callback) {
  45610. for (var cur in this._data) {
  45611. var val = this._data[cur];
  45612. var res = callback(cur, val);
  45613. if (res) {
  45614. return res;
  45615. }
  45616. }
  45617. return null;
  45618. };
  45619. return StringDictionary;
  45620. }());
  45621. BABYLON.StringDictionary = StringDictionary;
  45622. })(BABYLON || (BABYLON = {}));
  45623. //# sourceMappingURL=babylon.stringDictionary.js.map
  45624. var BABYLON;
  45625. (function (BABYLON) {
  45626. var DynamicFloatArrayElementInfo = (function () {
  45627. function DynamicFloatArrayElementInfo() {
  45628. }
  45629. return DynamicFloatArrayElementInfo;
  45630. }());
  45631. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45632. /**
  45633. * 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.
  45634. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45635. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45636. * 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.
  45637. * 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.
  45638. * 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".
  45639. */
  45640. var DynamicFloatArray = (function () {
  45641. /**
  45642. * Construct an instance of the dynamic float array
  45643. * @param stride size of one element in float (i.e. not bytes!)
  45644. * @param initialElementCount the number of available entries at construction
  45645. */
  45646. function DynamicFloatArray(stride, initialElementCount) {
  45647. this.compareValueOffset = null;
  45648. this.sortingAscending = true;
  45649. this._stride = stride;
  45650. this.buffer = new Float32Array(stride * initialElementCount);
  45651. this._lastUsed = 0;
  45652. this._firstFree = 0;
  45653. this._allEntries = new Array(initialElementCount);
  45654. this._freeEntries = new Array(initialElementCount);
  45655. for (var i = 0; i < initialElementCount; i++) {
  45656. var element = new DynamicFloatArrayElementInfo();
  45657. element.offset = i * stride;
  45658. this._allEntries[i] = element;
  45659. this._freeEntries[initialElementCount - i - 1] = element;
  45660. }
  45661. }
  45662. /**
  45663. * Allocate an element in the array.
  45664. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45665. * Beware, this offset may change when you call pack()
  45666. */
  45667. DynamicFloatArray.prototype.allocElement = function () {
  45668. if (this._freeEntries.length === 0) {
  45669. this._growBuffer();
  45670. }
  45671. var el = this._freeEntries.pop();
  45672. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45673. if (el.offset === this._firstFree) {
  45674. if (this._freeEntries.length > 0) {
  45675. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45676. }
  45677. else {
  45678. this._firstFree += this._stride;
  45679. }
  45680. }
  45681. return el;
  45682. };
  45683. /**
  45684. * Free the element corresponding to the given element info
  45685. * @param elInfo the element that describe the allocated element
  45686. */
  45687. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45688. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45689. this._freeEntries.push(elInfo);
  45690. };
  45691. /**
  45692. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45693. * 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().
  45694. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45695. */
  45696. DynamicFloatArray.prototype.pack = function () {
  45697. // no free slot? no need to pack
  45698. if (this._freeEntries.length === 0) {
  45699. return this.buffer;
  45700. }
  45701. // If the buffer is already packed the last used will always be lower than the first free
  45702. // 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.
  45703. if (this._lastUsed < this._firstFree) {
  45704. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45705. return elementsBuffer_1;
  45706. }
  45707. var s = this._stride;
  45708. // 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
  45709. var lastFree = new DynamicFloatArrayElementInfo();
  45710. lastFree.offset = this.totalElementCount * s;
  45711. this._freeEntries.push(lastFree);
  45712. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45713. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45714. var firstFreeSlotOffset = sortedFree[0].offset;
  45715. var freeZoneSize = 1;
  45716. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45717. var prevOffset = sortedFree[0].offset;
  45718. for (var i = 1; i < sortedFree.length; i++) {
  45719. // 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
  45720. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45721. break;
  45722. }
  45723. var curFree = sortedFree[i];
  45724. var curOffset = curFree.offset;
  45725. // Compute the distance between this offset and the previous
  45726. var distance = curOffset - prevOffset;
  45727. // If the distance is the stride size, they are adjacent, it good, move to the next
  45728. if (distance === s) {
  45729. // Free zone is one element bigger
  45730. ++freeZoneSize;
  45731. // as we're about to iterate to the next, the cur becomes the previous...
  45732. prevOffset = curOffset;
  45733. continue;
  45734. }
  45735. // Distance is bigger, which means there's x element between the previous free and this one
  45736. var usedRange = (distance / s) - 1;
  45737. // Two cases the free zone is smaller than the data to move or bigger
  45738. // Copy what can fit in the free zone
  45739. var curMoveOffset = curOffset - s;
  45740. var copyCount = Math.min(freeZoneSize, usedRange);
  45741. for (var j = 0; j < copyCount; j++) {
  45742. var freeI = firstFreeSlotOffset / s;
  45743. var curI = curMoveOffset / s;
  45744. var moveEl = sortedAll[curI];
  45745. this._moveElement(moveEl, firstFreeSlotOffset);
  45746. var replacedEl = sortedAll[freeI];
  45747. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45748. replacedEl.offset = curMoveOffset;
  45749. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45750. sortedAll[freeI] = moveEl;
  45751. sortedAll[curI] = replacedEl;
  45752. curMoveOffset -= s;
  45753. firstFreeSlotOffset += s;
  45754. }
  45755. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45756. if (freeZoneSize <= usedRange) {
  45757. firstFreeSlotOffset = curMoveOffset + s;
  45758. freeZoneSize = 1 + copyCount;
  45759. }
  45760. else {
  45761. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45762. }
  45763. // as we're about to iterate to the next, the cur becomes the previous...
  45764. prevOffset = curOffset;
  45765. }
  45766. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45767. this._lastUsed = firstFreeSlotOffset - s;
  45768. this._firstFree = firstFreeSlotOffset;
  45769. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45770. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45771. this._allEntries = sortedAll;
  45772. return elementsBuffer;
  45773. };
  45774. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45775. for (var i = 0; i < this._stride; i++) {
  45776. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45777. }
  45778. element.offset = destOffset;
  45779. };
  45780. DynamicFloatArray.prototype._growBuffer = function () {
  45781. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45782. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45783. var newBuffer = new Float32Array(newElCount * this._stride);
  45784. newBuffer.set(this.buffer);
  45785. var curCount = this.totalElementCount;
  45786. var addedCount = newElCount - this.totalElementCount;
  45787. for (var i = 0; i < addedCount; i++) {
  45788. var element = new DynamicFloatArrayElementInfo();
  45789. element.offset = (curCount + i) * this.stride;
  45790. this._allEntries.push(element);
  45791. this._freeEntries[addedCount - i - 1] = element;
  45792. }
  45793. this._firstFree = curCount * this.stride;
  45794. this.buffer = newBuffer;
  45795. };
  45796. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45797. /**
  45798. * Get the total count of entries that can fit in the current buffer
  45799. * @returns the elements count
  45800. */
  45801. get: function () {
  45802. return this._allEntries.length;
  45803. },
  45804. enumerable: true,
  45805. configurable: true
  45806. });
  45807. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45808. /**
  45809. * Get the count of free entries that can still be allocated without resizing the buffer
  45810. * @returns the free elements count
  45811. */
  45812. get: function () {
  45813. return this._freeEntries.length;
  45814. },
  45815. enumerable: true,
  45816. configurable: true
  45817. });
  45818. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45819. /**
  45820. * Get the count of allocated elements
  45821. * @returns the allocated elements count
  45822. */
  45823. get: function () {
  45824. return this._allEntries.length - this._freeEntries.length;
  45825. },
  45826. enumerable: true,
  45827. configurable: true
  45828. });
  45829. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45830. /**
  45831. * Return the size of one element in float
  45832. * @returns the size in float
  45833. */
  45834. get: function () {
  45835. return this._stride;
  45836. },
  45837. enumerable: true,
  45838. configurable: true
  45839. });
  45840. DynamicFloatArray.prototype.sort = function () {
  45841. var _this = this;
  45842. if (!this.compareValueOffset) {
  45843. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45844. }
  45845. var count = this.usedElementCount;
  45846. // Do we have to (re)create the sort table?
  45847. if (!this._sortTable || this._sortTable.length < count) {
  45848. // 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...
  45849. var newCount = Math.min(this.totalElementCount, count * 2);
  45850. this._sortTable = new Array(newCount);
  45851. }
  45852. if (!this._sortedTable || this._sortedTable.length !== count) {
  45853. this._sortedTable = new Array(count);
  45854. }
  45855. // Because, you know...
  45856. this.pack();
  45857. //let stride = this.stride;
  45858. //for (let i = 0; i < count; i++) {
  45859. // let si = this._sortTable[i];
  45860. // if (!si) {
  45861. // si = new SortInfo();
  45862. // this._sortTable[i] = si;
  45863. // }
  45864. // si.entry = this._allEntries[i];
  45865. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45866. // si.swapedOffset = null;
  45867. // this._sortedTable[i] = si;
  45868. //}
  45869. var curOffset = 0;
  45870. var stride = this.stride;
  45871. for (var i = 0; i < count; i++, curOffset += stride) {
  45872. var si = this._sortTable[i];
  45873. if (!si) {
  45874. si = new SortInfo();
  45875. this._sortTable[i] = si;
  45876. }
  45877. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45878. si.offset = curOffset;
  45879. si.swapedOffset = null;
  45880. this._sortedTable[i] = si;
  45881. }
  45882. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45883. if (this.sortingAscending) {
  45884. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45885. }
  45886. else {
  45887. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45888. }
  45889. var swapElements = function (src, dst) {
  45890. for (var i = 0; i < stride; i++) {
  45891. var tps = _this.buffer[dst + i];
  45892. _this.buffer[dst + i] = _this.buffer[src + i];
  45893. _this.buffer[src + i] = tps;
  45894. }
  45895. };
  45896. // 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:
  45897. // 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),
  45898. // and I still want something with a good algorithm complexity.
  45899. // 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,
  45900. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  45901. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  45902. // 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
  45903. // until we find a SortInfo object without a swapedOffset which means we got the right location
  45904. // 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
  45905. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  45906. for (var i = 0; i < count; i++) {
  45907. // Get the element to move
  45908. var sourceSI = this._sortedTable[i];
  45909. var destSI = this._sortTable[i];
  45910. var sourceOff = sourceSI.offset;
  45911. // If the source changed location, find the new one
  45912. if (sourceSI.swapedOffset) {
  45913. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  45914. var curSI = sourceSI;
  45915. while (curSI.swapedOffset) {
  45916. curSI = this._sortTable[curSI.swapedOffset / stride];
  45917. }
  45918. // Finally get the right location
  45919. sourceOff = curSI.offset;
  45920. }
  45921. // Tag the element being replaced with its new location
  45922. destSI.swapedOffset = sourceOff;
  45923. // Swap elements (only if needed)
  45924. if (sourceOff !== destSI.offset) {
  45925. swapElements(sourceOff, destSI.offset);
  45926. }
  45927. // Update the offset in the corresponding DFAE
  45928. //sourceSI.entry.offset = destSI.entry.offset;
  45929. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  45930. }
  45931. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45932. return true;
  45933. };
  45934. return DynamicFloatArray;
  45935. }());
  45936. BABYLON.DynamicFloatArray = DynamicFloatArray;
  45937. var SortInfo = (function () {
  45938. function SortInfo() {
  45939. this.compareData = this.offset = this.swapedOffset = null;
  45940. }
  45941. return SortInfo;
  45942. }());
  45943. })(BABYLON || (BABYLON = {}));
  45944. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  45945. var BABYLON;
  45946. (function (BABYLON) {
  45947. var Condition = (function () {
  45948. function Condition(actionManager) {
  45949. this._actionManager = actionManager;
  45950. }
  45951. Condition.prototype.isValid = function () {
  45952. return true;
  45953. };
  45954. Condition.prototype._getProperty = function (propertyPath) {
  45955. return this._actionManager._getProperty(propertyPath);
  45956. };
  45957. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45958. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45959. };
  45960. Condition.prototype.serialize = function () {
  45961. };
  45962. Condition.prototype._serialize = function (serializedCondition) {
  45963. return {
  45964. type: 2,
  45965. children: [],
  45966. name: serializedCondition.name,
  45967. properties: serializedCondition.properties
  45968. };
  45969. };
  45970. return Condition;
  45971. }());
  45972. BABYLON.Condition = Condition;
  45973. var ValueCondition = (function (_super) {
  45974. __extends(ValueCondition, _super);
  45975. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45976. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45977. var _this = _super.call(this, actionManager) || this;
  45978. _this.propertyPath = propertyPath;
  45979. _this.value = value;
  45980. _this.operator = operator;
  45981. _this._target = target;
  45982. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45983. _this._property = _this._getProperty(_this.propertyPath);
  45984. return _this;
  45985. }
  45986. Object.defineProperty(ValueCondition, "IsEqual", {
  45987. get: function () {
  45988. return ValueCondition._IsEqual;
  45989. },
  45990. enumerable: true,
  45991. configurable: true
  45992. });
  45993. Object.defineProperty(ValueCondition, "IsDifferent", {
  45994. get: function () {
  45995. return ValueCondition._IsDifferent;
  45996. },
  45997. enumerable: true,
  45998. configurable: true
  45999. });
  46000. Object.defineProperty(ValueCondition, "IsGreater", {
  46001. get: function () {
  46002. return ValueCondition._IsGreater;
  46003. },
  46004. enumerable: true,
  46005. configurable: true
  46006. });
  46007. Object.defineProperty(ValueCondition, "IsLesser", {
  46008. get: function () {
  46009. return ValueCondition._IsLesser;
  46010. },
  46011. enumerable: true,
  46012. configurable: true
  46013. });
  46014. // Methods
  46015. ValueCondition.prototype.isValid = function () {
  46016. switch (this.operator) {
  46017. case ValueCondition.IsGreater:
  46018. return this._effectiveTarget[this._property] > this.value;
  46019. case ValueCondition.IsLesser:
  46020. return this._effectiveTarget[this._property] < this.value;
  46021. case ValueCondition.IsEqual:
  46022. case ValueCondition.IsDifferent:
  46023. var check;
  46024. if (this.value.equals) {
  46025. check = this.value.equals(this._effectiveTarget[this._property]);
  46026. }
  46027. else {
  46028. check = this.value === this._effectiveTarget[this._property];
  46029. }
  46030. return this.operator === ValueCondition.IsEqual ? check : !check;
  46031. }
  46032. return false;
  46033. };
  46034. ValueCondition.prototype.serialize = function () {
  46035. return this._serialize({
  46036. name: "ValueCondition",
  46037. properties: [
  46038. BABYLON.Action._GetTargetProperty(this._target),
  46039. { name: "propertyPath", value: this.propertyPath },
  46040. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46041. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  46042. ]
  46043. });
  46044. };
  46045. ValueCondition.GetOperatorName = function (operator) {
  46046. switch (operator) {
  46047. case ValueCondition._IsEqual: return "IsEqual";
  46048. case ValueCondition._IsDifferent: return "IsDifferent";
  46049. case ValueCondition._IsGreater: return "IsGreater";
  46050. case ValueCondition._IsLesser: return "IsLesser";
  46051. default: return "";
  46052. }
  46053. };
  46054. // Statics
  46055. ValueCondition._IsEqual = 0;
  46056. ValueCondition._IsDifferent = 1;
  46057. ValueCondition._IsGreater = 2;
  46058. ValueCondition._IsLesser = 3;
  46059. return ValueCondition;
  46060. }(Condition));
  46061. BABYLON.ValueCondition = ValueCondition;
  46062. var PredicateCondition = (function (_super) {
  46063. __extends(PredicateCondition, _super);
  46064. function PredicateCondition(actionManager, predicate) {
  46065. var _this = _super.call(this, actionManager) || this;
  46066. _this.predicate = predicate;
  46067. return _this;
  46068. }
  46069. PredicateCondition.prototype.isValid = function () {
  46070. return this.predicate();
  46071. };
  46072. return PredicateCondition;
  46073. }(Condition));
  46074. BABYLON.PredicateCondition = PredicateCondition;
  46075. var StateCondition = (function (_super) {
  46076. __extends(StateCondition, _super);
  46077. function StateCondition(actionManager, target, value) {
  46078. var _this = _super.call(this, actionManager) || this;
  46079. _this.value = value;
  46080. _this._target = target;
  46081. return _this;
  46082. }
  46083. // Methods
  46084. StateCondition.prototype.isValid = function () {
  46085. return this._target.state === this.value;
  46086. };
  46087. StateCondition.prototype.serialize = function () {
  46088. return this._serialize({
  46089. name: "StateCondition",
  46090. properties: [
  46091. BABYLON.Action._GetTargetProperty(this._target),
  46092. { name: "value", value: this.value }
  46093. ]
  46094. });
  46095. };
  46096. return StateCondition;
  46097. }(Condition));
  46098. BABYLON.StateCondition = StateCondition;
  46099. })(BABYLON || (BABYLON = {}));
  46100. //# sourceMappingURL=babylon.condition.js.map
  46101. var BABYLON;
  46102. (function (BABYLON) {
  46103. var Action = (function () {
  46104. function Action(triggerOptions, condition) {
  46105. this.triggerOptions = triggerOptions;
  46106. if (triggerOptions.parameter) {
  46107. this.trigger = triggerOptions.trigger;
  46108. this._triggerParameter = triggerOptions.parameter;
  46109. }
  46110. else {
  46111. this.trigger = triggerOptions;
  46112. }
  46113. this._nextActiveAction = this;
  46114. this._condition = condition;
  46115. }
  46116. // Methods
  46117. Action.prototype._prepare = function () {
  46118. };
  46119. Action.prototype.getTriggerParameter = function () {
  46120. return this._triggerParameter;
  46121. };
  46122. Action.prototype._executeCurrent = function (evt) {
  46123. if (this._nextActiveAction._condition) {
  46124. var condition = this._nextActiveAction._condition;
  46125. var currentRenderId = this._actionManager.getScene().getRenderId();
  46126. // We cache the current evaluation for the current frame
  46127. if (condition._evaluationId === currentRenderId) {
  46128. if (!condition._currentResult) {
  46129. return;
  46130. }
  46131. }
  46132. else {
  46133. condition._evaluationId = currentRenderId;
  46134. if (!condition.isValid()) {
  46135. condition._currentResult = false;
  46136. return;
  46137. }
  46138. condition._currentResult = true;
  46139. }
  46140. }
  46141. this._nextActiveAction.execute(evt);
  46142. this.skipToNextActiveAction();
  46143. };
  46144. Action.prototype.execute = function (evt) {
  46145. };
  46146. Action.prototype.skipToNextActiveAction = function () {
  46147. if (this._nextActiveAction._child) {
  46148. if (!this._nextActiveAction._child._actionManager) {
  46149. this._nextActiveAction._child._actionManager = this._actionManager;
  46150. }
  46151. this._nextActiveAction = this._nextActiveAction._child;
  46152. }
  46153. else {
  46154. this._nextActiveAction = this;
  46155. }
  46156. };
  46157. Action.prototype.then = function (action) {
  46158. this._child = action;
  46159. action._actionManager = this._actionManager;
  46160. action._prepare();
  46161. return action;
  46162. };
  46163. Action.prototype._getProperty = function (propertyPath) {
  46164. return this._actionManager._getProperty(propertyPath);
  46165. };
  46166. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  46167. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46168. };
  46169. Action.prototype.serialize = function (parent) {
  46170. };
  46171. // Called by BABYLON.Action objects in serialize(...). Internal use
  46172. Action.prototype._serialize = function (serializedAction, parent) {
  46173. var serializationObject = {
  46174. type: 1,
  46175. children: [],
  46176. name: serializedAction.name,
  46177. properties: serializedAction.properties || []
  46178. };
  46179. // Serialize child
  46180. if (this._child) {
  46181. this._child.serialize(serializationObject);
  46182. }
  46183. // Check if "this" has a condition
  46184. if (this._condition) {
  46185. var serializedCondition = this._condition.serialize();
  46186. serializedCondition.children.push(serializationObject);
  46187. if (parent) {
  46188. parent.children.push(serializedCondition);
  46189. }
  46190. return serializedCondition;
  46191. }
  46192. if (parent) {
  46193. parent.children.push(serializationObject);
  46194. }
  46195. return serializationObject;
  46196. };
  46197. Action._SerializeValueAsString = function (value) {
  46198. if (typeof value === "number") {
  46199. return value.toString();
  46200. }
  46201. if (typeof value === "boolean") {
  46202. return value ? "true" : "false";
  46203. }
  46204. if (value instanceof BABYLON.Vector2) {
  46205. return value.x + ", " + value.y;
  46206. }
  46207. if (value instanceof BABYLON.Vector3) {
  46208. return value.x + ", " + value.y + ", " + value.z;
  46209. }
  46210. if (value instanceof BABYLON.Color3) {
  46211. return value.r + ", " + value.g + ", " + value.b;
  46212. }
  46213. if (value instanceof BABYLON.Color4) {
  46214. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  46215. }
  46216. return value; // string
  46217. };
  46218. Action._GetTargetProperty = function (target) {
  46219. return {
  46220. name: "target",
  46221. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  46222. : target instanceof BABYLON.Light ? "LightProperties"
  46223. : target instanceof BABYLON.Camera ? "CameraProperties"
  46224. : "SceneProperties",
  46225. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  46226. };
  46227. };
  46228. return Action;
  46229. }());
  46230. BABYLON.Action = Action;
  46231. })(BABYLON || (BABYLON = {}));
  46232. //# sourceMappingURL=babylon.action.js.map
  46233. var BABYLON;
  46234. (function (BABYLON) {
  46235. /**
  46236. * ActionEvent is the event beint sent when an action is triggered.
  46237. */
  46238. var ActionEvent = (function () {
  46239. /**
  46240. * @param source The mesh or sprite that triggered the action.
  46241. * @param pointerX The X mouse cursor position at the time of the event
  46242. * @param pointerY The Y mouse cursor position at the time of the event
  46243. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  46244. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  46245. */
  46246. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  46247. this.source = source;
  46248. this.pointerX = pointerX;
  46249. this.pointerY = pointerY;
  46250. this.meshUnderPointer = meshUnderPointer;
  46251. this.sourceEvent = sourceEvent;
  46252. this.additionalData = additionalData;
  46253. }
  46254. /**
  46255. * Helper function to auto-create an ActionEvent from a source mesh.
  46256. * @param source The source mesh that triggered the event
  46257. * @param evt {Event} The original (browser) event
  46258. */
  46259. ActionEvent.CreateNew = function (source, evt, additionalData) {
  46260. var scene = source.getScene();
  46261. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46262. };
  46263. /**
  46264. * Helper function to auto-create an ActionEvent from a source mesh.
  46265. * @param source The source sprite that triggered the event
  46266. * @param scene Scene associated with the sprite
  46267. * @param evt {Event} The original (browser) event
  46268. */
  46269. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  46270. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46271. };
  46272. /**
  46273. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  46274. * @param scene the scene where the event occurred
  46275. * @param evt {Event} The original (browser) event
  46276. */
  46277. ActionEvent.CreateNewFromScene = function (scene, evt) {
  46278. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  46279. };
  46280. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  46281. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  46282. };
  46283. return ActionEvent;
  46284. }());
  46285. BABYLON.ActionEvent = ActionEvent;
  46286. /**
  46287. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  46288. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  46289. */
  46290. var ActionManager = (function () {
  46291. function ActionManager(scene) {
  46292. // Members
  46293. this.actions = new Array();
  46294. this.hoverCursor = '';
  46295. this._scene = scene;
  46296. scene._actionManagers.push(this);
  46297. }
  46298. Object.defineProperty(ActionManager, "NothingTrigger", {
  46299. get: function () {
  46300. return ActionManager._NothingTrigger;
  46301. },
  46302. enumerable: true,
  46303. configurable: true
  46304. });
  46305. Object.defineProperty(ActionManager, "OnPickTrigger", {
  46306. get: function () {
  46307. return ActionManager._OnPickTrigger;
  46308. },
  46309. enumerable: true,
  46310. configurable: true
  46311. });
  46312. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46313. get: function () {
  46314. return ActionManager._OnLeftPickTrigger;
  46315. },
  46316. enumerable: true,
  46317. configurable: true
  46318. });
  46319. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46320. get: function () {
  46321. return ActionManager._OnRightPickTrigger;
  46322. },
  46323. enumerable: true,
  46324. configurable: true
  46325. });
  46326. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46327. get: function () {
  46328. return ActionManager._OnCenterPickTrigger;
  46329. },
  46330. enumerable: true,
  46331. configurable: true
  46332. });
  46333. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46334. get: function () {
  46335. return ActionManager._OnPickDownTrigger;
  46336. },
  46337. enumerable: true,
  46338. configurable: true
  46339. });
  46340. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46341. get: function () {
  46342. return ActionManager._OnDoublePickTrigger;
  46343. },
  46344. enumerable: true,
  46345. configurable: true
  46346. });
  46347. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46348. get: function () {
  46349. return ActionManager._OnPickUpTrigger;
  46350. },
  46351. enumerable: true,
  46352. configurable: true
  46353. });
  46354. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46355. /// This trigger will only be raised if you also declared a OnPickDown
  46356. get: function () {
  46357. return ActionManager._OnPickOutTrigger;
  46358. },
  46359. enumerable: true,
  46360. configurable: true
  46361. });
  46362. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46363. get: function () {
  46364. return ActionManager._OnLongPressTrigger;
  46365. },
  46366. enumerable: true,
  46367. configurable: true
  46368. });
  46369. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46370. get: function () {
  46371. return ActionManager._OnPointerOverTrigger;
  46372. },
  46373. enumerable: true,
  46374. configurable: true
  46375. });
  46376. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46377. get: function () {
  46378. return ActionManager._OnPointerOutTrigger;
  46379. },
  46380. enumerable: true,
  46381. configurable: true
  46382. });
  46383. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46384. get: function () {
  46385. return ActionManager._OnEveryFrameTrigger;
  46386. },
  46387. enumerable: true,
  46388. configurable: true
  46389. });
  46390. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46391. get: function () {
  46392. return ActionManager._OnIntersectionEnterTrigger;
  46393. },
  46394. enumerable: true,
  46395. configurable: true
  46396. });
  46397. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46398. get: function () {
  46399. return ActionManager._OnIntersectionExitTrigger;
  46400. },
  46401. enumerable: true,
  46402. configurable: true
  46403. });
  46404. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46405. get: function () {
  46406. return ActionManager._OnKeyDownTrigger;
  46407. },
  46408. enumerable: true,
  46409. configurable: true
  46410. });
  46411. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46412. get: function () {
  46413. return ActionManager._OnKeyUpTrigger;
  46414. },
  46415. enumerable: true,
  46416. configurable: true
  46417. });
  46418. // Methods
  46419. ActionManager.prototype.dispose = function () {
  46420. var index = this._scene._actionManagers.indexOf(this);
  46421. for (var i = 0; i < this.actions.length; i++) {
  46422. var action = this.actions[i];
  46423. ActionManager.Triggers[action.trigger]--;
  46424. if (ActionManager.Triggers[action.trigger] === 0) {
  46425. delete ActionManager.Triggers[action.trigger];
  46426. }
  46427. }
  46428. if (index > -1) {
  46429. this._scene._actionManagers.splice(index, 1);
  46430. }
  46431. };
  46432. ActionManager.prototype.getScene = function () {
  46433. return this._scene;
  46434. };
  46435. /**
  46436. * Does this action manager handles actions of any of the given triggers
  46437. * @param {number[]} triggers - the triggers to be tested
  46438. * @return {boolean} whether one (or more) of the triggers is handeled
  46439. */
  46440. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46441. for (var index = 0; index < this.actions.length; index++) {
  46442. var action = this.actions[index];
  46443. if (triggers.indexOf(action.trigger) > -1) {
  46444. return true;
  46445. }
  46446. }
  46447. return false;
  46448. };
  46449. /**
  46450. * Does this action manager handles actions of a given trigger
  46451. * @param {number} trigger - the trigger to be tested
  46452. * @return {boolean} whether the trigger is handeled
  46453. */
  46454. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46455. for (var index = 0; index < this.actions.length; index++) {
  46456. var action = this.actions[index];
  46457. if (action.trigger === trigger) {
  46458. return true;
  46459. }
  46460. }
  46461. return false;
  46462. };
  46463. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46464. /**
  46465. * Does this action manager has pointer triggers
  46466. * @return {boolean} whether or not it has pointer triggers
  46467. */
  46468. get: function () {
  46469. for (var index = 0; index < this.actions.length; index++) {
  46470. var action = this.actions[index];
  46471. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46472. return true;
  46473. }
  46474. }
  46475. return false;
  46476. },
  46477. enumerable: true,
  46478. configurable: true
  46479. });
  46480. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46481. /**
  46482. * Does this action manager has pick triggers
  46483. * @return {boolean} whether or not it has pick triggers
  46484. */
  46485. get: function () {
  46486. for (var index = 0; index < this.actions.length; index++) {
  46487. var action = this.actions[index];
  46488. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46489. return true;
  46490. }
  46491. }
  46492. return false;
  46493. },
  46494. enumerable: true,
  46495. configurable: true
  46496. });
  46497. Object.defineProperty(ActionManager, "HasTriggers", {
  46498. /**
  46499. * Does exist one action manager with at least one trigger
  46500. * @return {boolean} whether or not it exists one action manager with one trigger
  46501. **/
  46502. get: function () {
  46503. for (var t in ActionManager.Triggers) {
  46504. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46505. return true;
  46506. }
  46507. }
  46508. return false;
  46509. },
  46510. enumerable: true,
  46511. configurable: true
  46512. });
  46513. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46514. /**
  46515. * Does exist one action manager with at least one pick trigger
  46516. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46517. **/
  46518. get: function () {
  46519. for (var t in ActionManager.Triggers) {
  46520. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46521. var t_int = parseInt(t);
  46522. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46523. return true;
  46524. }
  46525. }
  46526. }
  46527. return false;
  46528. },
  46529. enumerable: true,
  46530. configurable: true
  46531. });
  46532. /**
  46533. * Does exist one action manager that handles actions of a given trigger
  46534. * @param {number} trigger - the trigger to be tested
  46535. * @return {boolean} whether the trigger is handeled by at least one action manager
  46536. **/
  46537. ActionManager.HasSpecificTrigger = function (trigger) {
  46538. for (var t in ActionManager.Triggers) {
  46539. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46540. var t_int = parseInt(t);
  46541. if (t_int === trigger) {
  46542. return true;
  46543. }
  46544. }
  46545. }
  46546. return false;
  46547. };
  46548. /**
  46549. * Registers an action to this action manager
  46550. * @param {BABYLON.Action} action - the action to be registered
  46551. * @return {BABYLON.Action} the action amended (prepared) after registration
  46552. */
  46553. ActionManager.prototype.registerAction = function (action) {
  46554. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46555. if (this.getScene().actionManager !== this) {
  46556. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46557. return null;
  46558. }
  46559. }
  46560. this.actions.push(action);
  46561. if (ActionManager.Triggers[action.trigger]) {
  46562. ActionManager.Triggers[action.trigger]++;
  46563. }
  46564. else {
  46565. ActionManager.Triggers[action.trigger] = 1;
  46566. }
  46567. action._actionManager = this;
  46568. action._prepare();
  46569. return action;
  46570. };
  46571. /**
  46572. * Process a specific trigger
  46573. * @param {number} trigger - the trigger to process
  46574. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46575. */
  46576. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46577. for (var index = 0; index < this.actions.length; index++) {
  46578. var action = this.actions[index];
  46579. if (action.trigger === trigger) {
  46580. if (trigger === ActionManager.OnKeyUpTrigger
  46581. || trigger === ActionManager.OnKeyDownTrigger) {
  46582. var parameter = action.getTriggerParameter();
  46583. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46584. if (!parameter.toLowerCase) {
  46585. continue;
  46586. }
  46587. var lowerCase = parameter.toLowerCase();
  46588. if (lowerCase !== evt.sourceEvent.key) {
  46589. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46590. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46591. if (actualkey !== lowerCase) {
  46592. continue;
  46593. }
  46594. }
  46595. }
  46596. }
  46597. action._executeCurrent(evt);
  46598. }
  46599. }
  46600. };
  46601. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46602. var properties = propertyPath.split(".");
  46603. for (var index = 0; index < properties.length - 1; index++) {
  46604. target = target[properties[index]];
  46605. }
  46606. return target;
  46607. };
  46608. ActionManager.prototype._getProperty = function (propertyPath) {
  46609. var properties = propertyPath.split(".");
  46610. return properties[properties.length - 1];
  46611. };
  46612. ActionManager.prototype.serialize = function (name) {
  46613. var root = {
  46614. children: [],
  46615. name: name,
  46616. type: 3,
  46617. properties: [] // Empty for root but required
  46618. };
  46619. for (var i = 0; i < this.actions.length; i++) {
  46620. var triggerObject = {
  46621. type: 0,
  46622. children: [],
  46623. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46624. properties: []
  46625. };
  46626. var triggerOptions = this.actions[i].triggerOptions;
  46627. if (triggerOptions && typeof triggerOptions !== "number") {
  46628. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46629. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46630. }
  46631. else {
  46632. var parameter = {};
  46633. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46634. if (triggerOptions.parameter.mesh) {
  46635. parameter._meshId = triggerOptions.parameter.mesh.id;
  46636. }
  46637. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46638. }
  46639. }
  46640. // Serialize child action, recursively
  46641. this.actions[i].serialize(triggerObject);
  46642. // Add serialized trigger
  46643. root.children.push(triggerObject);
  46644. }
  46645. return root;
  46646. };
  46647. ActionManager.Parse = function (parsedActions, object, scene) {
  46648. var actionManager = new BABYLON.ActionManager(scene);
  46649. if (object === null)
  46650. scene.actionManager = actionManager;
  46651. else
  46652. object.actionManager = actionManager;
  46653. // instanciate a new object
  46654. var instanciate = function (name, params) {
  46655. var newInstance = Object.create(BABYLON[name].prototype);
  46656. newInstance.constructor.apply(newInstance, params);
  46657. return newInstance;
  46658. };
  46659. var parseParameter = function (name, value, target, propertyPath) {
  46660. if (propertyPath === null) {
  46661. // String, boolean or float
  46662. var floatValue = parseFloat(value);
  46663. if (value === "true" || value === "false")
  46664. return value === "true";
  46665. else
  46666. return isNaN(floatValue) ? value : floatValue;
  46667. }
  46668. var effectiveTarget = propertyPath.split(".");
  46669. var values = value.split(",");
  46670. // Get effective Target
  46671. for (var i = 0; i < effectiveTarget.length; i++) {
  46672. target = target[effectiveTarget[i]];
  46673. }
  46674. // Return appropriate value with its type
  46675. if (typeof (target) === "boolean")
  46676. return values[0] === "true";
  46677. if (typeof (target) === "string")
  46678. return values[0];
  46679. // Parameters with multiple values such as Vector3 etc.
  46680. var split = new Array();
  46681. for (var i = 0; i < values.length; i++)
  46682. split.push(parseFloat(values[i]));
  46683. if (target instanceof BABYLON.Vector3)
  46684. return BABYLON.Vector3.FromArray(split);
  46685. if (target instanceof BABYLON.Vector4)
  46686. return BABYLON.Vector4.FromArray(split);
  46687. if (target instanceof BABYLON.Color3)
  46688. return BABYLON.Color3.FromArray(split);
  46689. if (target instanceof BABYLON.Color4)
  46690. return BABYLON.Color4.FromArray(split);
  46691. return parseFloat(values[0]);
  46692. };
  46693. // traverse graph per trigger
  46694. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46695. if (combineArray === void 0) { combineArray = null; }
  46696. if (parsedAction.detached)
  46697. return;
  46698. var parameters = new Array();
  46699. var target = null;
  46700. var propertyPath = null;
  46701. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46702. // Parameters
  46703. if (parsedAction.type === 2)
  46704. parameters.push(actionManager);
  46705. else
  46706. parameters.push(trigger);
  46707. if (combine) {
  46708. var actions = new Array();
  46709. for (var j = 0; j < parsedAction.combine.length; j++) {
  46710. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46711. }
  46712. parameters.push(actions);
  46713. }
  46714. else {
  46715. for (var i = 0; i < parsedAction.properties.length; i++) {
  46716. var value = parsedAction.properties[i].value;
  46717. var name = parsedAction.properties[i].name;
  46718. var targetType = parsedAction.properties[i].targetType;
  46719. if (name === "target")
  46720. if (targetType !== null && targetType === "SceneProperties")
  46721. value = target = scene;
  46722. else
  46723. value = target = scene.getNodeByName(value);
  46724. else if (name === "parent")
  46725. value = scene.getNodeByName(value);
  46726. else if (name === "sound")
  46727. value = scene.getSoundByName(value);
  46728. else if (name !== "propertyPath") {
  46729. if (parsedAction.type === 2 && name === "operator")
  46730. value = BABYLON.ValueCondition[value];
  46731. else
  46732. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46733. }
  46734. else {
  46735. propertyPath = value;
  46736. }
  46737. parameters.push(value);
  46738. }
  46739. }
  46740. if (combineArray === null) {
  46741. parameters.push(condition);
  46742. }
  46743. else {
  46744. parameters.push(null);
  46745. }
  46746. // If interpolate value action
  46747. if (parsedAction.name === "InterpolateValueAction") {
  46748. var param = parameters[parameters.length - 2];
  46749. parameters[parameters.length - 1] = param;
  46750. parameters[parameters.length - 2] = condition;
  46751. }
  46752. // Action or condition(s) and not CombineAction
  46753. var newAction = instanciate(parsedAction.name, parameters);
  46754. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46755. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46756. if (action)
  46757. action.then(nothing);
  46758. else
  46759. actionManager.registerAction(nothing);
  46760. action = nothing;
  46761. }
  46762. if (combineArray === null) {
  46763. if (newAction instanceof BABYLON.Condition) {
  46764. condition = newAction;
  46765. newAction = action;
  46766. }
  46767. else {
  46768. condition = null;
  46769. if (action)
  46770. action.then(newAction);
  46771. else
  46772. actionManager.registerAction(newAction);
  46773. }
  46774. }
  46775. else {
  46776. combineArray.push(newAction);
  46777. }
  46778. for (var i = 0; i < parsedAction.children.length; i++)
  46779. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46780. };
  46781. // triggers
  46782. for (var i = 0; i < parsedActions.children.length; i++) {
  46783. var triggerParams;
  46784. var trigger = parsedActions.children[i];
  46785. if (trigger.properties.length > 0) {
  46786. var param = trigger.properties[0].value;
  46787. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46788. if (value._meshId) {
  46789. value.mesh = scene.getMeshByID(value._meshId);
  46790. }
  46791. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46792. }
  46793. else
  46794. triggerParams = BABYLON.ActionManager[trigger.name];
  46795. for (var j = 0; j < trigger.children.length; j++) {
  46796. if (!trigger.detached)
  46797. traverse(trigger.children[j], triggerParams, null, null);
  46798. }
  46799. }
  46800. };
  46801. ActionManager.GetTriggerName = function (trigger) {
  46802. switch (trigger) {
  46803. case 0: return "NothingTrigger";
  46804. case 1: return "OnPickTrigger";
  46805. case 2: return "OnLeftPickTrigger";
  46806. case 3: return "OnRightPickTrigger";
  46807. case 4: return "OnCenterPickTrigger";
  46808. case 5: return "OnPickDownTrigger";
  46809. case 6: return "OnPickUpTrigger";
  46810. case 7: return "OnLongPressTrigger";
  46811. case 8: return "OnPointerOverTrigger";
  46812. case 9: return "OnPointerOutTrigger";
  46813. case 10: return "OnEveryFrameTrigger";
  46814. case 11: return "OnIntersectionEnterTrigger";
  46815. case 12: return "OnIntersectionExitTrigger";
  46816. case 13: return "OnKeyDownTrigger";
  46817. case 14: return "OnKeyUpTrigger";
  46818. case 15: return "OnPickOutTrigger";
  46819. default: return "";
  46820. }
  46821. };
  46822. // Statics
  46823. ActionManager._NothingTrigger = 0;
  46824. ActionManager._OnPickTrigger = 1;
  46825. ActionManager._OnLeftPickTrigger = 2;
  46826. ActionManager._OnRightPickTrigger = 3;
  46827. ActionManager._OnCenterPickTrigger = 4;
  46828. ActionManager._OnPickDownTrigger = 5;
  46829. ActionManager._OnDoublePickTrigger = 6;
  46830. ActionManager._OnPickUpTrigger = 7;
  46831. ActionManager._OnLongPressTrigger = 8;
  46832. ActionManager._OnPointerOverTrigger = 9;
  46833. ActionManager._OnPointerOutTrigger = 10;
  46834. ActionManager._OnEveryFrameTrigger = 11;
  46835. ActionManager._OnIntersectionEnterTrigger = 12;
  46836. ActionManager._OnIntersectionExitTrigger = 13;
  46837. ActionManager._OnKeyDownTrigger = 14;
  46838. ActionManager._OnKeyUpTrigger = 15;
  46839. ActionManager._OnPickOutTrigger = 16;
  46840. ActionManager.Triggers = {};
  46841. return ActionManager;
  46842. }());
  46843. BABYLON.ActionManager = ActionManager;
  46844. })(BABYLON || (BABYLON = {}));
  46845. //# sourceMappingURL=babylon.actionManager.js.map
  46846. var BABYLON;
  46847. (function (BABYLON) {
  46848. var InterpolateValueAction = (function (_super) {
  46849. __extends(InterpolateValueAction, _super);
  46850. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46851. if (duration === void 0) { duration = 1000; }
  46852. var _this = _super.call(this, triggerOptions, condition) || this;
  46853. _this.propertyPath = propertyPath;
  46854. _this.value = value;
  46855. _this.duration = duration;
  46856. _this.stopOtherAnimations = stopOtherAnimations;
  46857. _this.onInterpolationDone = onInterpolationDone;
  46858. _this._target = _this._effectiveTarget = target;
  46859. return _this;
  46860. }
  46861. InterpolateValueAction.prototype._prepare = function () {
  46862. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46863. this._property = this._getProperty(this.propertyPath);
  46864. };
  46865. InterpolateValueAction.prototype.execute = function () {
  46866. var scene = this._actionManager.getScene();
  46867. var keys = [
  46868. {
  46869. frame: 0,
  46870. value: this._effectiveTarget[this._property]
  46871. }, {
  46872. frame: 100,
  46873. value: this.value
  46874. }
  46875. ];
  46876. var dataType;
  46877. if (typeof this.value === "number") {
  46878. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46879. }
  46880. else if (this.value instanceof BABYLON.Color3) {
  46881. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46882. }
  46883. else if (this.value instanceof BABYLON.Vector3) {
  46884. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46885. }
  46886. else if (this.value instanceof BABYLON.Matrix) {
  46887. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46888. }
  46889. else if (this.value instanceof BABYLON.Quaternion) {
  46890. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46891. }
  46892. else {
  46893. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46894. return;
  46895. }
  46896. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46897. animation.setKeys(keys);
  46898. if (this.stopOtherAnimations) {
  46899. scene.stopAnimation(this._effectiveTarget);
  46900. }
  46901. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  46902. };
  46903. InterpolateValueAction.prototype.serialize = function (parent) {
  46904. return _super.prototype._serialize.call(this, {
  46905. name: "InterpolateValueAction",
  46906. properties: [
  46907. BABYLON.Action._GetTargetProperty(this._target),
  46908. { name: "propertyPath", value: this.propertyPath },
  46909. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46910. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46911. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46912. ]
  46913. }, parent);
  46914. };
  46915. return InterpolateValueAction;
  46916. }(BABYLON.Action));
  46917. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46918. })(BABYLON || (BABYLON = {}));
  46919. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46920. var BABYLON;
  46921. (function (BABYLON) {
  46922. var SwitchBooleanAction = (function (_super) {
  46923. __extends(SwitchBooleanAction, _super);
  46924. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46925. var _this = _super.call(this, triggerOptions, condition) || this;
  46926. _this.propertyPath = propertyPath;
  46927. _this._target = _this._effectiveTarget = target;
  46928. return _this;
  46929. }
  46930. SwitchBooleanAction.prototype._prepare = function () {
  46931. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46932. this._property = this._getProperty(this.propertyPath);
  46933. };
  46934. SwitchBooleanAction.prototype.execute = function () {
  46935. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46936. };
  46937. SwitchBooleanAction.prototype.serialize = function (parent) {
  46938. return _super.prototype._serialize.call(this, {
  46939. name: "SwitchBooleanAction",
  46940. properties: [
  46941. BABYLON.Action._GetTargetProperty(this._target),
  46942. { name: "propertyPath", value: this.propertyPath }
  46943. ]
  46944. }, parent);
  46945. };
  46946. return SwitchBooleanAction;
  46947. }(BABYLON.Action));
  46948. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46949. var SetStateAction = (function (_super) {
  46950. __extends(SetStateAction, _super);
  46951. function SetStateAction(triggerOptions, target, value, condition) {
  46952. var _this = _super.call(this, triggerOptions, condition) || this;
  46953. _this.value = value;
  46954. _this._target = target;
  46955. return _this;
  46956. }
  46957. SetStateAction.prototype.execute = function () {
  46958. this._target.state = this.value;
  46959. };
  46960. SetStateAction.prototype.serialize = function (parent) {
  46961. return _super.prototype._serialize.call(this, {
  46962. name: "SetStateAction",
  46963. properties: [
  46964. BABYLON.Action._GetTargetProperty(this._target),
  46965. { name: "value", value: this.value }
  46966. ]
  46967. }, parent);
  46968. };
  46969. return SetStateAction;
  46970. }(BABYLON.Action));
  46971. BABYLON.SetStateAction = SetStateAction;
  46972. var SetValueAction = (function (_super) {
  46973. __extends(SetValueAction, _super);
  46974. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46975. var _this = _super.call(this, triggerOptions, condition) || this;
  46976. _this.propertyPath = propertyPath;
  46977. _this.value = value;
  46978. _this._target = _this._effectiveTarget = target;
  46979. return _this;
  46980. }
  46981. SetValueAction.prototype._prepare = function () {
  46982. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46983. this._property = this._getProperty(this.propertyPath);
  46984. };
  46985. SetValueAction.prototype.execute = function () {
  46986. this._effectiveTarget[this._property] = this.value;
  46987. if (this._target.markAsDirty) {
  46988. this._target.markAsDirty(this._property);
  46989. }
  46990. };
  46991. SetValueAction.prototype.serialize = function (parent) {
  46992. return _super.prototype._serialize.call(this, {
  46993. name: "SetValueAction",
  46994. properties: [
  46995. BABYLON.Action._GetTargetProperty(this._target),
  46996. { name: "propertyPath", value: this.propertyPath },
  46997. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46998. ]
  46999. }, parent);
  47000. };
  47001. return SetValueAction;
  47002. }(BABYLON.Action));
  47003. BABYLON.SetValueAction = SetValueAction;
  47004. var IncrementValueAction = (function (_super) {
  47005. __extends(IncrementValueAction, _super);
  47006. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  47007. var _this = _super.call(this, triggerOptions, condition) || this;
  47008. _this.propertyPath = propertyPath;
  47009. _this.value = value;
  47010. _this._target = _this._effectiveTarget = target;
  47011. return _this;
  47012. }
  47013. IncrementValueAction.prototype._prepare = function () {
  47014. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47015. this._property = this._getProperty(this.propertyPath);
  47016. if (typeof this._effectiveTarget[this._property] !== "number") {
  47017. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  47018. }
  47019. };
  47020. IncrementValueAction.prototype.execute = function () {
  47021. this._effectiveTarget[this._property] += this.value;
  47022. if (this._target.markAsDirty) {
  47023. this._target.markAsDirty(this._property);
  47024. }
  47025. };
  47026. IncrementValueAction.prototype.serialize = function (parent) {
  47027. return _super.prototype._serialize.call(this, {
  47028. name: "IncrementValueAction",
  47029. properties: [
  47030. BABYLON.Action._GetTargetProperty(this._target),
  47031. { name: "propertyPath", value: this.propertyPath },
  47032. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47033. ]
  47034. }, parent);
  47035. };
  47036. return IncrementValueAction;
  47037. }(BABYLON.Action));
  47038. BABYLON.IncrementValueAction = IncrementValueAction;
  47039. var PlayAnimationAction = (function (_super) {
  47040. __extends(PlayAnimationAction, _super);
  47041. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  47042. var _this = _super.call(this, triggerOptions, condition) || this;
  47043. _this.from = from;
  47044. _this.to = to;
  47045. _this.loop = loop;
  47046. _this._target = target;
  47047. return _this;
  47048. }
  47049. PlayAnimationAction.prototype._prepare = function () {
  47050. };
  47051. PlayAnimationAction.prototype.execute = function () {
  47052. var scene = this._actionManager.getScene();
  47053. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  47054. };
  47055. PlayAnimationAction.prototype.serialize = function (parent) {
  47056. return _super.prototype._serialize.call(this, {
  47057. name: "PlayAnimationAction",
  47058. properties: [
  47059. BABYLON.Action._GetTargetProperty(this._target),
  47060. { name: "from", value: String(this.from) },
  47061. { name: "to", value: String(this.to) },
  47062. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  47063. ]
  47064. }, parent);
  47065. };
  47066. return PlayAnimationAction;
  47067. }(BABYLON.Action));
  47068. BABYLON.PlayAnimationAction = PlayAnimationAction;
  47069. var StopAnimationAction = (function (_super) {
  47070. __extends(StopAnimationAction, _super);
  47071. function StopAnimationAction(triggerOptions, target, condition) {
  47072. var _this = _super.call(this, triggerOptions, condition) || this;
  47073. _this._target = target;
  47074. return _this;
  47075. }
  47076. StopAnimationAction.prototype._prepare = function () {
  47077. };
  47078. StopAnimationAction.prototype.execute = function () {
  47079. var scene = this._actionManager.getScene();
  47080. scene.stopAnimation(this._target);
  47081. };
  47082. StopAnimationAction.prototype.serialize = function (parent) {
  47083. return _super.prototype._serialize.call(this, {
  47084. name: "StopAnimationAction",
  47085. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  47086. }, parent);
  47087. };
  47088. return StopAnimationAction;
  47089. }(BABYLON.Action));
  47090. BABYLON.StopAnimationAction = StopAnimationAction;
  47091. var DoNothingAction = (function (_super) {
  47092. __extends(DoNothingAction, _super);
  47093. function DoNothingAction(triggerOptions, condition) {
  47094. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  47095. return _super.call(this, triggerOptions, condition) || this;
  47096. }
  47097. DoNothingAction.prototype.execute = function () {
  47098. };
  47099. DoNothingAction.prototype.serialize = function (parent) {
  47100. return _super.prototype._serialize.call(this, {
  47101. name: "DoNothingAction",
  47102. properties: []
  47103. }, parent);
  47104. };
  47105. return DoNothingAction;
  47106. }(BABYLON.Action));
  47107. BABYLON.DoNothingAction = DoNothingAction;
  47108. var CombineAction = (function (_super) {
  47109. __extends(CombineAction, _super);
  47110. function CombineAction(triggerOptions, children, condition) {
  47111. var _this = _super.call(this, triggerOptions, condition) || this;
  47112. _this.children = children;
  47113. return _this;
  47114. }
  47115. CombineAction.prototype._prepare = function () {
  47116. for (var index = 0; index < this.children.length; index++) {
  47117. this.children[index]._actionManager = this._actionManager;
  47118. this.children[index]._prepare();
  47119. }
  47120. };
  47121. CombineAction.prototype.execute = function (evt) {
  47122. for (var index = 0; index < this.children.length; index++) {
  47123. this.children[index].execute(evt);
  47124. }
  47125. };
  47126. CombineAction.prototype.serialize = function (parent) {
  47127. var serializationObject = _super.prototype._serialize.call(this, {
  47128. name: "CombineAction",
  47129. properties: [],
  47130. combine: []
  47131. }, parent);
  47132. for (var i = 0; i < this.children.length; i++) {
  47133. serializationObject.combine.push(this.children[i].serialize(null));
  47134. }
  47135. return serializationObject;
  47136. };
  47137. return CombineAction;
  47138. }(BABYLON.Action));
  47139. BABYLON.CombineAction = CombineAction;
  47140. var ExecuteCodeAction = (function (_super) {
  47141. __extends(ExecuteCodeAction, _super);
  47142. function ExecuteCodeAction(triggerOptions, func, condition) {
  47143. var _this = _super.call(this, triggerOptions, condition) || this;
  47144. _this.func = func;
  47145. return _this;
  47146. }
  47147. ExecuteCodeAction.prototype.execute = function (evt) {
  47148. this.func(evt);
  47149. };
  47150. return ExecuteCodeAction;
  47151. }(BABYLON.Action));
  47152. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  47153. var SetParentAction = (function (_super) {
  47154. __extends(SetParentAction, _super);
  47155. function SetParentAction(triggerOptions, target, parent, condition) {
  47156. var _this = _super.call(this, triggerOptions, condition) || this;
  47157. _this._target = target;
  47158. _this._parent = parent;
  47159. return _this;
  47160. }
  47161. SetParentAction.prototype._prepare = function () {
  47162. };
  47163. SetParentAction.prototype.execute = function () {
  47164. if (this._target.parent === this._parent) {
  47165. return;
  47166. }
  47167. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  47168. invertParentWorldMatrix.invert();
  47169. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  47170. this._target.parent = this._parent;
  47171. };
  47172. SetParentAction.prototype.serialize = function (parent) {
  47173. return _super.prototype._serialize.call(this, {
  47174. name: "SetParentAction",
  47175. properties: [
  47176. BABYLON.Action._GetTargetProperty(this._target),
  47177. BABYLON.Action._GetTargetProperty(this._parent),
  47178. ]
  47179. }, parent);
  47180. };
  47181. return SetParentAction;
  47182. }(BABYLON.Action));
  47183. BABYLON.SetParentAction = SetParentAction;
  47184. var PlaySoundAction = (function (_super) {
  47185. __extends(PlaySoundAction, _super);
  47186. function PlaySoundAction(triggerOptions, sound, condition) {
  47187. var _this = _super.call(this, triggerOptions, condition) || this;
  47188. _this._sound = sound;
  47189. return _this;
  47190. }
  47191. PlaySoundAction.prototype._prepare = function () {
  47192. };
  47193. PlaySoundAction.prototype.execute = function () {
  47194. if (this._sound !== undefined)
  47195. this._sound.play();
  47196. };
  47197. PlaySoundAction.prototype.serialize = function (parent) {
  47198. return _super.prototype._serialize.call(this, {
  47199. name: "PlaySoundAction",
  47200. properties: [{ name: "sound", value: this._sound.name }]
  47201. }, parent);
  47202. };
  47203. return PlaySoundAction;
  47204. }(BABYLON.Action));
  47205. BABYLON.PlaySoundAction = PlaySoundAction;
  47206. var StopSoundAction = (function (_super) {
  47207. __extends(StopSoundAction, _super);
  47208. function StopSoundAction(triggerOptions, sound, condition) {
  47209. var _this = _super.call(this, triggerOptions, condition) || this;
  47210. _this._sound = sound;
  47211. return _this;
  47212. }
  47213. StopSoundAction.prototype._prepare = function () {
  47214. };
  47215. StopSoundAction.prototype.execute = function () {
  47216. if (this._sound !== undefined)
  47217. this._sound.stop();
  47218. };
  47219. StopSoundAction.prototype.serialize = function (parent) {
  47220. return _super.prototype._serialize.call(this, {
  47221. name: "StopSoundAction",
  47222. properties: [{ name: "sound", value: this._sound.name }]
  47223. }, parent);
  47224. };
  47225. return StopSoundAction;
  47226. }(BABYLON.Action));
  47227. BABYLON.StopSoundAction = StopSoundAction;
  47228. })(BABYLON || (BABYLON = {}));
  47229. //# sourceMappingURL=babylon.directActions.js.map
  47230. var BABYLON;
  47231. (function (BABYLON) {
  47232. var Debug;
  47233. (function (Debug) {
  47234. /**
  47235. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  47236. */
  47237. var SkeletonViewer = (function () {
  47238. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  47239. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  47240. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  47241. this.skeleton = skeleton;
  47242. this.mesh = mesh;
  47243. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  47244. this.renderingGroupId = renderingGroupId;
  47245. this.color = BABYLON.Color3.White();
  47246. this._debugLines = [];
  47247. this._isEnabled = false;
  47248. this._scene = scene;
  47249. this.update();
  47250. this._renderFunction = this.update.bind(this);
  47251. }
  47252. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  47253. get: function () {
  47254. return this._isEnabled;
  47255. },
  47256. set: function (value) {
  47257. if (this._isEnabled === value) {
  47258. return;
  47259. }
  47260. this._isEnabled = value;
  47261. if (value) {
  47262. this._scene.registerBeforeRender(this._renderFunction);
  47263. }
  47264. else {
  47265. this._scene.unregisterBeforeRender(this._renderFunction);
  47266. }
  47267. },
  47268. enumerable: true,
  47269. configurable: true
  47270. });
  47271. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  47272. if (x === void 0) { x = 0; }
  47273. if (y === void 0) { y = 0; }
  47274. if (z === void 0) { z = 0; }
  47275. var tmat = BABYLON.Tmp.Matrix[0];
  47276. var parentBone = bone.getParent();
  47277. tmat.copyFrom(bone.getLocalMatrix());
  47278. if (x !== 0 || y !== 0 || z !== 0) {
  47279. var tmat2 = BABYLON.Tmp.Matrix[1];
  47280. BABYLON.Matrix.IdentityToRef(tmat2);
  47281. tmat2.m[12] = x;
  47282. tmat2.m[13] = y;
  47283. tmat2.m[14] = z;
  47284. tmat2.multiplyToRef(tmat, tmat);
  47285. }
  47286. if (parentBone) {
  47287. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  47288. }
  47289. tmat.multiplyToRef(meshMat, tmat);
  47290. position.x = tmat.m[12];
  47291. position.y = tmat.m[13];
  47292. position.z = tmat.m[14];
  47293. };
  47294. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  47295. var len = bones.length;
  47296. var meshPos = this.mesh.position;
  47297. for (var i = 0; i < len; i++) {
  47298. var bone = bones[i];
  47299. var points = this._debugLines[i];
  47300. if (!points) {
  47301. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47302. this._debugLines[i] = points;
  47303. }
  47304. this._getBonePosition(points[0], bone, meshMat);
  47305. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  47306. points[0].subtractInPlace(meshPos);
  47307. points[1].subtractInPlace(meshPos);
  47308. }
  47309. };
  47310. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  47311. var len = bones.length;
  47312. var boneNum = 0;
  47313. var meshPos = this.mesh.position;
  47314. for (var i = len - 1; i >= 0; i--) {
  47315. var childBone = bones[i];
  47316. var parentBone = childBone.getParent();
  47317. if (!parentBone) {
  47318. continue;
  47319. }
  47320. var points = this._debugLines[boneNum];
  47321. if (!points) {
  47322. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47323. this._debugLines[boneNum] = points;
  47324. }
  47325. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  47326. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  47327. points[0].subtractInPlace(meshPos);
  47328. points[1].subtractInPlace(meshPos);
  47329. boneNum++;
  47330. }
  47331. };
  47332. SkeletonViewer.prototype.update = function () {
  47333. if (this.autoUpdateBonesMatrices) {
  47334. this.skeleton.computeAbsoluteTransforms();
  47335. }
  47336. if (this.skeleton.bones[0].length === undefined) {
  47337. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47338. }
  47339. else {
  47340. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47341. }
  47342. if (!this._debugMesh) {
  47343. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  47344. this._debugMesh.renderingGroupId = this.renderingGroupId;
  47345. }
  47346. else {
  47347. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  47348. }
  47349. this._debugMesh.position.copyFrom(this.mesh.position);
  47350. this._debugMesh.color = this.color;
  47351. };
  47352. SkeletonViewer.prototype.dispose = function () {
  47353. if (this._debugMesh) {
  47354. this.isEnabled = false;
  47355. this._debugMesh.dispose();
  47356. this._debugMesh = null;
  47357. }
  47358. };
  47359. return SkeletonViewer;
  47360. }());
  47361. Debug.SkeletonViewer = SkeletonViewer;
  47362. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47363. })(BABYLON || (BABYLON = {}));
  47364. //# sourceMappingURL=babylon.skeletonViewer.js.map
  47365. var BABYLON;
  47366. (function (BABYLON) {
  47367. var Debug;
  47368. (function (Debug) {
  47369. var AxesViewer = (function () {
  47370. function AxesViewer(scene, scaleLines) {
  47371. if (scaleLines === void 0) { scaleLines = 1; }
  47372. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47373. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47374. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47375. this.scaleLines = 1;
  47376. this.scaleLines = scaleLines;
  47377. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  47378. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  47379. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  47380. this._xmesh.renderingGroupId = 2;
  47381. this._ymesh.renderingGroupId = 2;
  47382. this._zmesh.renderingGroupId = 2;
  47383. this._xmesh.material.checkReadyOnlyOnce = true;
  47384. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  47385. this._ymesh.material.checkReadyOnlyOnce = true;
  47386. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  47387. this._zmesh.material.checkReadyOnlyOnce = true;
  47388. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  47389. this.scene = scene;
  47390. }
  47391. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  47392. var scaleLines = this.scaleLines;
  47393. this._xmesh.position.copyFrom(position);
  47394. this._ymesh.position.copyFrom(position);
  47395. this._zmesh.position.copyFrom(position);
  47396. var point2 = this._xline[1];
  47397. point2.x = xaxis.x * scaleLines;
  47398. point2.y = xaxis.y * scaleLines;
  47399. point2.z = xaxis.z * scaleLines;
  47400. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  47401. point2 = this._yline[1];
  47402. point2.x = yaxis.x * scaleLines;
  47403. point2.y = yaxis.y * scaleLines;
  47404. point2.z = yaxis.z * scaleLines;
  47405. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  47406. point2 = this._zline[1];
  47407. point2.x = zaxis.x * scaleLines;
  47408. point2.y = zaxis.y * scaleLines;
  47409. point2.z = zaxis.z * scaleLines;
  47410. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  47411. };
  47412. AxesViewer.prototype.dispose = function () {
  47413. if (this._xmesh) {
  47414. this._xmesh.dispose();
  47415. this._ymesh.dispose();
  47416. this._zmesh.dispose();
  47417. this._xmesh = null;
  47418. this._ymesh = null;
  47419. this._zmesh = null;
  47420. this._xline = null;
  47421. this._yline = null;
  47422. this._zline = null;
  47423. this.scene = null;
  47424. }
  47425. };
  47426. return AxesViewer;
  47427. }());
  47428. Debug.AxesViewer = AxesViewer;
  47429. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47430. })(BABYLON || (BABYLON = {}));
  47431. //# sourceMappingURL=babylon.axesViewer.js.map
  47432. var BABYLON;
  47433. (function (BABYLON) {
  47434. var Debug;
  47435. (function (Debug) {
  47436. var BoneAxesViewer = (function (_super) {
  47437. __extends(BoneAxesViewer, _super);
  47438. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  47439. if (scaleLines === void 0) { scaleLines = 1; }
  47440. var _this = _super.call(this, scene, scaleLines) || this;
  47441. _this.pos = BABYLON.Vector3.Zero();
  47442. _this.xaxis = BABYLON.Vector3.Zero();
  47443. _this.yaxis = BABYLON.Vector3.Zero();
  47444. _this.zaxis = BABYLON.Vector3.Zero();
  47445. _this.mesh = mesh;
  47446. _this.bone = bone;
  47447. return _this;
  47448. }
  47449. BoneAxesViewer.prototype.update = function () {
  47450. var bone = this.bone;
  47451. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  47452. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  47453. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  47454. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  47455. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  47456. };
  47457. BoneAxesViewer.prototype.dispose = function () {
  47458. if (this.pos) {
  47459. this.pos = null;
  47460. this.xaxis = null;
  47461. this.yaxis = null;
  47462. this.zaxis = null;
  47463. this.mesh = null;
  47464. this.bone = null;
  47465. _super.prototype.dispose.call(this);
  47466. }
  47467. };
  47468. return BoneAxesViewer;
  47469. }(Debug.AxesViewer));
  47470. Debug.BoneAxesViewer = BoneAxesViewer;
  47471. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47472. })(BABYLON || (BABYLON = {}));
  47473. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  47474. var BABYLON;
  47475. (function (BABYLON) {
  47476. var RayHelper = (function () {
  47477. function RayHelper(ray) {
  47478. this.ray = ray;
  47479. }
  47480. RayHelper.CreateAndShow = function (ray, scene, color) {
  47481. var helper = new RayHelper(ray);
  47482. helper.show(scene, color);
  47483. return helper;
  47484. };
  47485. RayHelper.prototype.show = function (scene, color) {
  47486. if (!this._renderFunction) {
  47487. var ray = this.ray;
  47488. this._renderFunction = this._render.bind(this);
  47489. this._scene = scene;
  47490. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  47491. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  47492. this._scene.registerBeforeRender(this._renderFunction);
  47493. }
  47494. if (color) {
  47495. this._renderLine.color.copyFrom(color);
  47496. }
  47497. };
  47498. RayHelper.prototype.hide = function () {
  47499. if (this._renderFunction) {
  47500. this._scene.unregisterBeforeRender(this._renderFunction);
  47501. this._scene = null;
  47502. this._renderFunction = null;
  47503. this._renderLine.dispose();
  47504. this._renderLine = null;
  47505. this._renderPoints = null;
  47506. }
  47507. };
  47508. RayHelper.prototype._render = function () {
  47509. var ray = this.ray;
  47510. var point = this._renderPoints[1];
  47511. var len = Math.min(ray.length, 1000000);
  47512. point.copyFrom(ray.direction);
  47513. point.scaleInPlace(len);
  47514. point.addInPlace(ray.origin);
  47515. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  47516. };
  47517. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  47518. this._attachedToMesh = mesh;
  47519. var ray = this.ray;
  47520. if (!ray.direction) {
  47521. ray.direction = BABYLON.Vector3.Zero();
  47522. }
  47523. if (!ray.origin) {
  47524. ray.origin = BABYLON.Vector3.Zero();
  47525. }
  47526. if (length) {
  47527. ray.length = length;
  47528. }
  47529. if (!meshSpaceOrigin) {
  47530. meshSpaceOrigin = BABYLON.Vector3.Zero();
  47531. }
  47532. if (!meshSpaceDirection) {
  47533. // -1 so that this will work with Mesh.lookAt
  47534. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  47535. }
  47536. if (!this._meshSpaceDirection) {
  47537. this._meshSpaceDirection = meshSpaceDirection.clone();
  47538. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  47539. }
  47540. else {
  47541. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  47542. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  47543. }
  47544. if (!this._updateToMeshFunction) {
  47545. this._updateToMeshFunction = this._updateToMesh.bind(this);
  47546. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  47547. }
  47548. this._updateToMesh();
  47549. };
  47550. RayHelper.prototype.detachFromMesh = function () {
  47551. if (this._attachedToMesh) {
  47552. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  47553. this._attachedToMesh = null;
  47554. this._updateToMeshFunction = null;
  47555. }
  47556. };
  47557. RayHelper.prototype._updateToMesh = function () {
  47558. var ray = this.ray;
  47559. if (this._attachedToMesh._isDisposed) {
  47560. this.detachFromMesh();
  47561. return;
  47562. }
  47563. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  47564. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  47565. };
  47566. RayHelper.prototype.dispose = function () {
  47567. this.hide();
  47568. this.detachFromMesh();
  47569. this.ray = null;
  47570. };
  47571. return RayHelper;
  47572. }());
  47573. BABYLON.RayHelper = RayHelper;
  47574. })(BABYLON || (BABYLON = {}));
  47575. //# sourceMappingURL=babylon.rayHelper.js.map
  47576. var BABYLON;
  47577. (function (BABYLON) {
  47578. var DebugLayer = (function () {
  47579. function DebugLayer(scene) {
  47580. this._scene = scene;
  47581. }
  47582. /** Creates the inspector window. */
  47583. DebugLayer.prototype._createInspector = function (config) {
  47584. if (config === void 0) { config = {}; }
  47585. var popup = config.popup || false;
  47586. var initialTab = config.initialTab || 0;
  47587. var parentElement = config.parentElement || null;
  47588. if (!this._inspector) {
  47589. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  47590. } // else nothing to do,; instance is already existing
  47591. };
  47592. DebugLayer.prototype.isVisible = function () {
  47593. if (!this._inspector) {
  47594. return false;
  47595. }
  47596. return true;
  47597. };
  47598. DebugLayer.prototype.hide = function () {
  47599. if (this._inspector) {
  47600. try {
  47601. this._inspector.dispose();
  47602. }
  47603. catch (e) {
  47604. // If the inspector has been removed directly from the inspector tool
  47605. }
  47606. this._inspector = null;
  47607. }
  47608. };
  47609. DebugLayer.prototype.show = function (config) {
  47610. if (config === void 0) { config = {}; }
  47611. if (typeof INSPECTOR == 'undefined') {
  47612. // Load inspector and add it to the DOM
  47613. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  47614. }
  47615. else {
  47616. // Otherwise creates the inspector
  47617. this._createInspector(config);
  47618. }
  47619. };
  47620. // Get protocol used - http or https
  47621. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  47622. return DebugLayer;
  47623. }());
  47624. BABYLON.DebugLayer = DebugLayer;
  47625. })(BABYLON || (BABYLON = {}));
  47626. //# sourceMappingURL=babylon.debugLayer.js.map
  47627. var BABYLON;
  47628. (function (BABYLON) {
  47629. var Debug;
  47630. (function (Debug) {
  47631. var PhysicsViewer = (function () {
  47632. function PhysicsViewer(scene) {
  47633. this._impostors = [];
  47634. this._meshes = [];
  47635. this._numMeshes = 0;
  47636. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47637. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  47638. }
  47639. PhysicsViewer.prototype._updateDebugMeshes = function () {
  47640. var plugin = this._physicsEnginePlugin;
  47641. for (var i = 0; i < this._numMeshes; i++) {
  47642. if (this._impostors[i].isDisposed) {
  47643. this.hideImpostor(this._impostors[i--]);
  47644. }
  47645. else {
  47646. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  47647. }
  47648. }
  47649. };
  47650. PhysicsViewer.prototype.showImpostor = function (impostor) {
  47651. for (var i = 0; i < this._numMeshes; i++) {
  47652. if (this._impostors[i] == impostor) {
  47653. return;
  47654. }
  47655. }
  47656. var debugMesh = this._getDebugMesh(impostor, this._scene);
  47657. if (debugMesh) {
  47658. this._impostors[this._numMeshes] = impostor;
  47659. this._meshes[this._numMeshes] = debugMesh;
  47660. if (this._numMeshes === 0) {
  47661. this._renderFunction = this._updateDebugMeshes.bind(this);
  47662. this._scene.registerBeforeRender(this._renderFunction);
  47663. }
  47664. this._numMeshes++;
  47665. }
  47666. };
  47667. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  47668. var removed = false;
  47669. for (var i = 0; i < this._numMeshes; i++) {
  47670. if (this._impostors[i] == impostor) {
  47671. this._scene.removeMesh(this._meshes[i]);
  47672. this._meshes[i].dispose();
  47673. this._numMeshes--;
  47674. if (this._numMeshes > 0) {
  47675. this._meshes[i] = this._meshes[this._numMeshes];
  47676. this._impostors[i] = this._impostors[this._numMeshes];
  47677. this._meshes[this._numMeshes] = null;
  47678. this._impostors[this._numMeshes] = null;
  47679. }
  47680. else {
  47681. this._meshes[0] = null;
  47682. this._impostors[0] = null;
  47683. }
  47684. removed = true;
  47685. break;
  47686. }
  47687. }
  47688. if (removed && this._numMeshes === 0) {
  47689. this._scene.unregisterBeforeRender(this._renderFunction);
  47690. }
  47691. };
  47692. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  47693. if (!this._debugMaterial) {
  47694. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  47695. this._debugMaterial.wireframe = true;
  47696. }
  47697. return this._debugMaterial;
  47698. };
  47699. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  47700. if (!this._debugBoxMesh) {
  47701. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  47702. this._debugBoxMesh.renderingGroupId = 1;
  47703. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47704. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  47705. scene.removeMesh(this._debugBoxMesh);
  47706. }
  47707. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47708. };
  47709. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47710. if (!this._debugSphereMesh) {
  47711. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47712. this._debugSphereMesh.renderingGroupId = 1;
  47713. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47714. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47715. scene.removeMesh(this._debugSphereMesh);
  47716. }
  47717. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47718. };
  47719. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47720. var body = impostor.physicsBody;
  47721. var shape = body.shapes[0];
  47722. var mesh;
  47723. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47724. mesh = this._getDebugBoxMesh(scene);
  47725. impostor.getBoxSizeToRef(mesh.scaling);
  47726. }
  47727. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47728. mesh = this._getDebugSphereMesh(scene);
  47729. var radius = impostor.getRadius();
  47730. mesh.scaling.x = radius * 2;
  47731. mesh.scaling.y = radius * 2;
  47732. mesh.scaling.z = radius * 2;
  47733. }
  47734. return mesh;
  47735. };
  47736. PhysicsViewer.prototype.dispose = function () {
  47737. for (var i = 0; i < this._numMeshes; i++) {
  47738. this.hideImpostor(this._impostors[i]);
  47739. }
  47740. if (this._debugBoxMesh) {
  47741. this._debugBoxMesh.dispose();
  47742. }
  47743. if (this._debugSphereMesh) {
  47744. this._debugSphereMesh.dispose();
  47745. }
  47746. if (this._debugMaterial) {
  47747. this._debugMaterial.dispose();
  47748. }
  47749. this._impostors.length = 0;
  47750. this._scene = null;
  47751. this._physicsEnginePlugin = null;
  47752. };
  47753. return PhysicsViewer;
  47754. }());
  47755. Debug.PhysicsViewer = PhysicsViewer;
  47756. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47757. })(BABYLON || (BABYLON = {}));
  47758. //# sourceMappingURL=babylon.physicsViewer.js.map
  47759. var BABYLON;
  47760. (function (BABYLON) {
  47761. var BoundingBoxRenderer = (function () {
  47762. function BoundingBoxRenderer(scene) {
  47763. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47764. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47765. this.showBackLines = true;
  47766. this.renderList = new BABYLON.SmartArray(32);
  47767. this._vertexBuffers = {};
  47768. this._scene = scene;
  47769. }
  47770. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47771. if (this._colorShader) {
  47772. return;
  47773. }
  47774. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47775. attributes: [BABYLON.VertexBuffer.PositionKind],
  47776. uniforms: ["world", "viewProjection", "color"]
  47777. });
  47778. var engine = this._scene.getEngine();
  47779. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47780. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47781. this._createIndexBuffer();
  47782. };
  47783. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  47784. var engine = this._scene.getEngine();
  47785. 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]);
  47786. };
  47787. BoundingBoxRenderer.prototype._rebuild = function () {
  47788. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  47789. this._createIndexBuffer();
  47790. };
  47791. BoundingBoxRenderer.prototype.reset = function () {
  47792. this.renderList.reset();
  47793. };
  47794. BoundingBoxRenderer.prototype.render = function () {
  47795. if (this.renderList.length === 0) {
  47796. return;
  47797. }
  47798. this._prepareRessources();
  47799. if (!this._colorShader.isReady()) {
  47800. return;
  47801. }
  47802. var engine = this._scene.getEngine();
  47803. engine.setDepthWrite(false);
  47804. this._colorShader._preBind();
  47805. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47806. var boundingBox = this.renderList.data[boundingBoxIndex];
  47807. var min = boundingBox.minimum;
  47808. var max = boundingBox.maximum;
  47809. var diff = max.subtract(min);
  47810. var median = min.add(diff.scale(0.5));
  47811. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47812. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47813. .multiply(boundingBox.getWorldMatrix());
  47814. // VBOs
  47815. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47816. if (this.showBackLines) {
  47817. // Back
  47818. engine.setDepthFunctionToGreaterOrEqual();
  47819. this._scene.resetCachedMaterial();
  47820. this._colorShader.setColor4("color", this.backColor.toColor4());
  47821. this._colorShader.bind(worldMatrix);
  47822. // Draw order
  47823. engine.draw(false, 0, 24);
  47824. }
  47825. // Front
  47826. engine.setDepthFunctionToLess();
  47827. this._scene.resetCachedMaterial();
  47828. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47829. this._colorShader.bind(worldMatrix);
  47830. // Draw order
  47831. engine.draw(false, 0, 24);
  47832. }
  47833. this._colorShader.unbind();
  47834. engine.setDepthFunctionToLessOrEqual();
  47835. engine.setDepthWrite(true);
  47836. };
  47837. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  47838. this._prepareRessources();
  47839. if (!this._colorShader.isReady()) {
  47840. return;
  47841. }
  47842. var engine = this._scene.getEngine();
  47843. engine.setDepthWrite(false);
  47844. engine.setColorWrite(false);
  47845. this._colorShader._preBind();
  47846. var boundingBox = mesh._boundingInfo.boundingBox;
  47847. var min = boundingBox.minimum;
  47848. var max = boundingBox.maximum;
  47849. var diff = max.subtract(min);
  47850. var median = min.add(diff.scale(0.5));
  47851. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47852. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47853. .multiply(boundingBox.getWorldMatrix());
  47854. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47855. engine.setDepthFunctionToLess();
  47856. this._scene.resetCachedMaterial();
  47857. this._colorShader.bind(worldMatrix);
  47858. engine.draw(false, 0, 24);
  47859. this._colorShader.unbind();
  47860. engine.setDepthFunctionToLessOrEqual();
  47861. engine.setDepthWrite(true);
  47862. engine.setColorWrite(true);
  47863. };
  47864. BoundingBoxRenderer.prototype.dispose = function () {
  47865. if (!this._colorShader) {
  47866. return;
  47867. }
  47868. this.renderList.dispose();
  47869. this._colorShader.dispose();
  47870. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47871. if (buffer) {
  47872. buffer.dispose();
  47873. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47874. }
  47875. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47876. };
  47877. return BoundingBoxRenderer;
  47878. }());
  47879. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47880. })(BABYLON || (BABYLON = {}));
  47881. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47882. var BABYLON;
  47883. (function (BABYLON) {
  47884. var TextureTools = (function () {
  47885. function TextureTools() {
  47886. }
  47887. /**
  47888. * Uses the GPU to create a copy texture rescaled at a given size
  47889. * @param texture Texture to copy from
  47890. * @param width Desired width
  47891. * @param height Desired height
  47892. * @return Generated texture
  47893. */
  47894. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  47895. if (useBilinearMode === void 0) { useBilinearMode = true; }
  47896. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  47897. var scene = texture.getScene();
  47898. var engine = scene.getEngine();
  47899. rtt.wrapU = texture.wrapU;
  47900. rtt.wrapV = texture.wrapV;
  47901. rtt.uOffset = texture.uOffset;
  47902. rtt.vOffset = texture.vOffset;
  47903. rtt.uScale = texture.uScale;
  47904. rtt.vScale = texture.vScale;
  47905. rtt.uAng = texture.uAng;
  47906. rtt.vAng = texture.vAng;
  47907. rtt.wAng = texture.wAng;
  47908. rtt.coordinatesIndex = texture.coordinatesIndex;
  47909. rtt.level = texture.level;
  47910. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  47911. rtt._texture.isReady = false;
  47912. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47913. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47914. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47915. passPostProcess.getEffect().executeWhenCompiled(function () {
  47916. passPostProcess.onApply = function (effect) {
  47917. effect.setTexture("textureSampler", texture);
  47918. };
  47919. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  47920. engine.unBindFramebuffer(rtt.getInternalTexture());
  47921. rtt.disposeFramebufferObjects();
  47922. passPostProcess.dispose();
  47923. rtt._texture.isReady = true;
  47924. });
  47925. return rtt;
  47926. };
  47927. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  47928. if (!scene._environmentBRDFTexture) {
  47929. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47930. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47931. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47932. scene._environmentBRDFTexture = texture;
  47933. }
  47934. return scene._environmentBRDFTexture;
  47935. };
  47936. 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=";
  47937. return TextureTools;
  47938. }());
  47939. BABYLON.TextureTools = TextureTools;
  47940. })(BABYLON || (BABYLON = {}));
  47941. //# sourceMappingURL=babylon.textureTools.js.map
  47942. var BABYLON;
  47943. (function (BABYLON) {
  47944. var SphericalPolynomial = (function () {
  47945. function SphericalPolynomial() {
  47946. this.x = BABYLON.Vector3.Zero();
  47947. this.y = BABYLON.Vector3.Zero();
  47948. this.z = BABYLON.Vector3.Zero();
  47949. this.xx = BABYLON.Vector3.Zero();
  47950. this.yy = BABYLON.Vector3.Zero();
  47951. this.zz = BABYLON.Vector3.Zero();
  47952. this.xy = BABYLON.Vector3.Zero();
  47953. this.yz = BABYLON.Vector3.Zero();
  47954. this.zx = BABYLON.Vector3.Zero();
  47955. }
  47956. SphericalPolynomial.prototype.addAmbient = function (color) {
  47957. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47958. this.xx = this.xx.add(colorVector);
  47959. this.yy = this.yy.add(colorVector);
  47960. this.zz = this.zz.add(colorVector);
  47961. };
  47962. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  47963. var result = new SphericalPolynomial();
  47964. result.x = harmonics.L11.scale(1.02333);
  47965. result.y = harmonics.L1_1.scale(1.02333);
  47966. result.z = harmonics.L10.scale(1.02333);
  47967. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  47968. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  47969. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  47970. result.yz = harmonics.L2_1.scale(0.858086);
  47971. result.zx = harmonics.L21.scale(0.858086);
  47972. result.xy = harmonics.L2_2.scale(0.858086);
  47973. result.scale(1.0 / Math.PI);
  47974. return result;
  47975. };
  47976. SphericalPolynomial.prototype.scale = function (scale) {
  47977. this.x = this.x.scale(scale);
  47978. this.y = this.y.scale(scale);
  47979. this.z = this.z.scale(scale);
  47980. this.xx = this.xx.scale(scale);
  47981. this.yy = this.yy.scale(scale);
  47982. this.zz = this.zz.scale(scale);
  47983. this.yz = this.yz.scale(scale);
  47984. this.zx = this.zx.scale(scale);
  47985. this.xy = this.xy.scale(scale);
  47986. };
  47987. return SphericalPolynomial;
  47988. }());
  47989. BABYLON.SphericalPolynomial = SphericalPolynomial;
  47990. var SphericalHarmonics = (function () {
  47991. function SphericalHarmonics() {
  47992. this.L00 = BABYLON.Vector3.Zero();
  47993. this.L1_1 = BABYLON.Vector3.Zero();
  47994. this.L10 = BABYLON.Vector3.Zero();
  47995. this.L11 = BABYLON.Vector3.Zero();
  47996. this.L2_2 = BABYLON.Vector3.Zero();
  47997. this.L2_1 = BABYLON.Vector3.Zero();
  47998. this.L20 = BABYLON.Vector3.Zero();
  47999. this.L21 = BABYLON.Vector3.Zero();
  48000. this.L22 = BABYLON.Vector3.Zero();
  48001. }
  48002. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  48003. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  48004. var c = colorVector.scale(deltaSolidAngle);
  48005. this.L00 = this.L00.add(c.scale(0.282095));
  48006. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  48007. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  48008. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  48009. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  48010. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  48011. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  48012. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  48013. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  48014. };
  48015. SphericalHarmonics.prototype.scale = function (scale) {
  48016. this.L00 = this.L00.scale(scale);
  48017. this.L1_1 = this.L1_1.scale(scale);
  48018. this.L10 = this.L10.scale(scale);
  48019. this.L11 = this.L11.scale(scale);
  48020. this.L2_2 = this.L2_2.scale(scale);
  48021. this.L2_1 = this.L2_1.scale(scale);
  48022. this.L20 = this.L20.scale(scale);
  48023. this.L21 = this.L21.scale(scale);
  48024. this.L22 = this.L22.scale(scale);
  48025. };
  48026. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  48027. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  48028. //
  48029. // E_lm = A_l * L_lm
  48030. //
  48031. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  48032. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  48033. // the scaling factors are given in equation 9.
  48034. // Constant (Band 0)
  48035. this.L00 = this.L00.scale(3.141593);
  48036. // Linear (Band 1)
  48037. this.L1_1 = this.L1_1.scale(2.094395);
  48038. this.L10 = this.L10.scale(2.094395);
  48039. this.L11 = this.L11.scale(2.094395);
  48040. // Quadratic (Band 2)
  48041. this.L2_2 = this.L2_2.scale(0.785398);
  48042. this.L2_1 = this.L2_1.scale(0.785398);
  48043. this.L20 = this.L20.scale(0.785398);
  48044. this.L21 = this.L21.scale(0.785398);
  48045. this.L22 = this.L22.scale(0.785398);
  48046. };
  48047. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  48048. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  48049. // L = (1/pi) * E * rho
  48050. //
  48051. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  48052. this.scale(1.0 / Math.PI);
  48053. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  48054. // (The pixel shader must apply albedo after texture fetches, etc).
  48055. };
  48056. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  48057. var result = new SphericalHarmonics();
  48058. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  48059. result.L1_1 = polynomial.y.scale(0.977204);
  48060. result.L10 = polynomial.z.scale(0.977204);
  48061. result.L11 = polynomial.x.scale(0.977204);
  48062. result.L2_2 = polynomial.xy.scale(1.16538);
  48063. result.L2_1 = polynomial.yz.scale(1.16538);
  48064. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  48065. result.L21 = polynomial.zx.scale(1.16538);
  48066. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  48067. result.scale(Math.PI);
  48068. return result;
  48069. };
  48070. return SphericalHarmonics;
  48071. }());
  48072. BABYLON.SphericalHarmonics = SphericalHarmonics;
  48073. })(BABYLON || (BABYLON = {}));
  48074. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  48075. var BABYLON;
  48076. (function (BABYLON) {
  48077. var Internals;
  48078. (function (Internals) {
  48079. var FileFaceOrientation = (function () {
  48080. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48081. this.name = name;
  48082. this.worldAxisForNormal = worldAxisForNormal;
  48083. this.worldAxisForFileX = worldAxisForFileX;
  48084. this.worldAxisForFileY = worldAxisForFileY;
  48085. }
  48086. return FileFaceOrientation;
  48087. }());
  48088. ;
  48089. /**
  48090. * Helper class dealing with the extraction of spherical polynomial dataArray
  48091. * from a cube map.
  48092. */
  48093. var CubeMapToSphericalPolynomialTools = (function () {
  48094. function CubeMapToSphericalPolynomialTools() {
  48095. }
  48096. /**
  48097. * Converts a texture to the according Spherical Polynomial data.
  48098. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48099. *
  48100. * @param texture The texture to extract the information from.
  48101. * @return The Spherical Polynomial data.
  48102. */
  48103. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  48104. if (!texture.isCube) {
  48105. // Only supports cube Textures currently.
  48106. return null;
  48107. }
  48108. var size = texture.getSize().width;
  48109. var right = texture.readPixels(0);
  48110. var left = texture.readPixels(1);
  48111. var up;
  48112. var down;
  48113. if (texture.isRenderTarget) {
  48114. up = texture.readPixels(3);
  48115. down = texture.readPixels(2);
  48116. }
  48117. else {
  48118. up = texture.readPixels(2);
  48119. down = texture.readPixels(3);
  48120. }
  48121. var front = texture.readPixels(4);
  48122. var back = texture.readPixels(5);
  48123. var gammaSpace = texture.gammaSpace;
  48124. // Always read as RGBA.
  48125. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  48126. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  48127. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48128. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  48129. }
  48130. var cubeInfo = {
  48131. size: size,
  48132. right: right,
  48133. left: left,
  48134. up: up,
  48135. down: down,
  48136. front: front,
  48137. back: back,
  48138. format: format,
  48139. type: type,
  48140. gammaSpace: gammaSpace,
  48141. };
  48142. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  48143. };
  48144. /**
  48145. * Converts a cubemap to the according Spherical Polynomial data.
  48146. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48147. *
  48148. * @param cubeInfo The Cube map to extract the information from.
  48149. * @return The Spherical Polynomial data.
  48150. */
  48151. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48152. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48153. var totalSolidAngle = 0.0;
  48154. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48155. var du = 2.0 / cubeInfo.size;
  48156. var dv = du;
  48157. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48158. var minUV = du * 0.5 - 1.0;
  48159. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48160. var fileFace = this.FileFaces[faceIndex];
  48161. var dataArray = cubeInfo[fileFace.name];
  48162. var v = minUV;
  48163. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48164. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48165. // Because SP is still linear, so summation is fine in that basis.
  48166. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  48167. for (var y = 0; y < cubeInfo.size; y++) {
  48168. var u = minUV;
  48169. for (var x = 0; x < cubeInfo.size; x++) {
  48170. // World direction (not normalised)
  48171. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48172. worldDirection.normalize();
  48173. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48174. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  48175. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  48176. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  48177. // Handle Integer types.
  48178. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48179. r /= 255;
  48180. g /= 255;
  48181. b /= 255;
  48182. }
  48183. // Handle Gamma space textures.
  48184. if (cubeInfo.gammaSpace) {
  48185. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  48186. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  48187. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  48188. }
  48189. var color = new BABYLON.Color3(r, g, b);
  48190. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48191. totalSolidAngle += deltaSolidAngle;
  48192. u += du;
  48193. }
  48194. v += dv;
  48195. }
  48196. }
  48197. // Solid angle for entire sphere is 4*pi
  48198. var sphereSolidAngle = 4.0 * Math.PI;
  48199. // Adjust the solid angle to allow for how many faces we processed.
  48200. var facesProcessed = 6.0;
  48201. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  48202. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  48203. // This is needed because the numerical integration over the cube uses a
  48204. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  48205. // and also to compensate for accumulative error due to float precision in the summation.
  48206. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  48207. sphericalHarmonics.scale(correctionFactor);
  48208. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  48209. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  48210. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48211. };
  48212. CubeMapToSphericalPolynomialTools.FileFaces = [
  48213. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48214. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48215. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48216. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48217. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48218. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48219. ];
  48220. return CubeMapToSphericalPolynomialTools;
  48221. }());
  48222. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48223. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48224. })(BABYLON || (BABYLON = {}));
  48225. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  48226. var BABYLON;
  48227. (function (BABYLON) {
  48228. var Internals;
  48229. (function (Internals) {
  48230. /**
  48231. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48232. */
  48233. var PanoramaToCubeMapTools = (function () {
  48234. function PanoramaToCubeMapTools() {
  48235. }
  48236. /**
  48237. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48238. *
  48239. * @param float32Array The source data.
  48240. * @param inputWidth The width of the input panorama.
  48241. * @param inputhHeight The height of the input panorama.
  48242. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48243. * @return The cubemap data
  48244. */
  48245. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48246. if (!float32Array) {
  48247. throw "ConvertPanoramaToCubemap: input cannot be null";
  48248. }
  48249. if (float32Array.length != inputWidth * inputHeight * 3) {
  48250. throw "ConvertPanoramaToCubemap: input size is wrong";
  48251. }
  48252. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48253. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48254. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48255. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48256. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48257. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48258. return {
  48259. front: textureFront,
  48260. back: textureBack,
  48261. left: textureLeft,
  48262. right: textureRight,
  48263. up: textureUp,
  48264. down: textureDown,
  48265. size: size,
  48266. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  48267. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  48268. gammaSpace: false,
  48269. };
  48270. };
  48271. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48272. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48273. var textureArray = new Float32Array(buffer);
  48274. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48275. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48276. var dy = 1 / texSize;
  48277. var fy = 0;
  48278. for (var y = 0; y < texSize; y++) {
  48279. var xv1 = faceData[0];
  48280. var xv2 = faceData[2];
  48281. for (var x = 0; x < texSize; x++) {
  48282. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48283. v.normalize();
  48284. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48285. // 3 channels per pixels
  48286. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48287. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48288. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48289. xv1 = xv1.add(rotDX1);
  48290. xv2 = xv2.add(rotDX2);
  48291. }
  48292. fy += dy;
  48293. }
  48294. return textureArray;
  48295. };
  48296. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48297. var theta = Math.atan2(vDir.z, vDir.x);
  48298. var phi = Math.acos(vDir.y);
  48299. while (theta < -Math.PI)
  48300. theta += 2 * Math.PI;
  48301. while (theta > Math.PI)
  48302. theta -= 2 * Math.PI;
  48303. var dx = theta / Math.PI;
  48304. var dy = phi / Math.PI;
  48305. // recenter.
  48306. dx = dx * 0.5 + 0.5;
  48307. var px = Math.round(dx * inputWidth);
  48308. if (px < 0)
  48309. px = 0;
  48310. else if (px >= inputWidth)
  48311. px = inputWidth - 1;
  48312. var py = Math.round(dy * inputHeight);
  48313. if (py < 0)
  48314. py = 0;
  48315. else if (py >= inputHeight)
  48316. py = inputHeight - 1;
  48317. var inputY = (inputHeight - py - 1);
  48318. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48319. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48320. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48321. return {
  48322. r: r,
  48323. g: g,
  48324. b: b
  48325. };
  48326. };
  48327. PanoramaToCubeMapTools.FACE_FRONT = [
  48328. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48329. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48330. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48331. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48332. ];
  48333. PanoramaToCubeMapTools.FACE_BACK = [
  48334. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48335. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48336. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48337. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48338. ];
  48339. PanoramaToCubeMapTools.FACE_RIGHT = [
  48340. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48341. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48342. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48343. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48344. ];
  48345. PanoramaToCubeMapTools.FACE_LEFT = [
  48346. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48347. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48348. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48349. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48350. ];
  48351. PanoramaToCubeMapTools.FACE_DOWN = [
  48352. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48353. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48354. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48355. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48356. ];
  48357. PanoramaToCubeMapTools.FACE_UP = [
  48358. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48359. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48360. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48361. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48362. ];
  48363. return PanoramaToCubeMapTools;
  48364. }());
  48365. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48366. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48367. })(BABYLON || (BABYLON = {}));
  48368. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  48369. var BABYLON;
  48370. (function (BABYLON) {
  48371. var Internals;
  48372. (function (Internals) {
  48373. ;
  48374. /**
  48375. * This groups tools to convert HDR texture to native colors array.
  48376. */
  48377. var HDRTools = (function () {
  48378. function HDRTools() {
  48379. }
  48380. HDRTools.Ldexp = function (mantissa, exponent) {
  48381. if (exponent > 1023) {
  48382. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48383. }
  48384. if (exponent < -1074) {
  48385. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48386. }
  48387. return mantissa * Math.pow(2, exponent);
  48388. };
  48389. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48390. if (exponent > 0) {
  48391. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48392. float32array[index + 0] = red * exponent;
  48393. float32array[index + 1] = green * exponent;
  48394. float32array[index + 2] = blue * exponent;
  48395. }
  48396. else {
  48397. float32array[index + 0] = 0;
  48398. float32array[index + 1] = 0;
  48399. float32array[index + 2] = 0;
  48400. }
  48401. };
  48402. HDRTools.readStringLine = function (uint8array, startIndex) {
  48403. var line = "";
  48404. var character = "";
  48405. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48406. character = String.fromCharCode(uint8array[i]);
  48407. if (character == "\n") {
  48408. break;
  48409. }
  48410. line += character;
  48411. }
  48412. return line;
  48413. };
  48414. /**
  48415. * Reads header information from an RGBE texture stored in a native array.
  48416. * More information on this format are available here:
  48417. * https://en.wikipedia.org/wiki/RGBE_image_format
  48418. *
  48419. * @param uint8array The binary file stored in native array.
  48420. * @return The header information.
  48421. */
  48422. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48423. var height = 0;
  48424. var width = 0;
  48425. var line = this.readStringLine(uint8array, 0);
  48426. if (line[0] != '#' || line[1] != '?') {
  48427. throw "Bad HDR Format.";
  48428. }
  48429. var endOfHeader = false;
  48430. var findFormat = false;
  48431. var lineIndex = 0;
  48432. do {
  48433. lineIndex += (line.length + 1);
  48434. line = this.readStringLine(uint8array, lineIndex);
  48435. if (line == "FORMAT=32-bit_rle_rgbe") {
  48436. findFormat = true;
  48437. }
  48438. else if (line.length == 0) {
  48439. endOfHeader = true;
  48440. }
  48441. } while (!endOfHeader);
  48442. if (!findFormat) {
  48443. throw "HDR Bad header format, unsupported FORMAT";
  48444. }
  48445. lineIndex += (line.length + 1);
  48446. line = this.readStringLine(uint8array, lineIndex);
  48447. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48448. var match = sizeRegexp.exec(line);
  48449. // TODO. Support +Y and -X if needed.
  48450. if (match.length < 3) {
  48451. throw "HDR Bad header format, no size";
  48452. }
  48453. width = parseInt(match[2]);
  48454. height = parseInt(match[1]);
  48455. if (width < 8 || width > 0x7fff) {
  48456. throw "HDR Bad header format, unsupported size";
  48457. }
  48458. lineIndex += (line.length + 1);
  48459. return {
  48460. height: height,
  48461. width: width,
  48462. dataPosition: lineIndex
  48463. };
  48464. };
  48465. /**
  48466. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48467. * This RGBE texture needs to store the information as a panorama.
  48468. *
  48469. * More information on this format are available here:
  48470. * https://en.wikipedia.org/wiki/RGBE_image_format
  48471. *
  48472. * @param buffer The binary file stored in an array buffer.
  48473. * @param size The expected size of the extracted cubemap.
  48474. * @return The Cube Map information.
  48475. */
  48476. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48477. var uint8array = new Uint8Array(buffer);
  48478. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48479. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48480. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48481. return cubeMapData;
  48482. };
  48483. /**
  48484. * Returns the pixels data extracted from an RGBE texture.
  48485. * This pixels will be stored left to right up to down in the R G B order in one array.
  48486. *
  48487. * More information on this format are available here:
  48488. * https://en.wikipedia.org/wiki/RGBE_image_format
  48489. *
  48490. * @param uint8array The binary file stored in an array buffer.
  48491. * @param hdrInfo The header information of the file.
  48492. * @return The pixels data in RGB right to left up to down order.
  48493. */
  48494. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48495. // Keep for multi format supports.
  48496. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48497. };
  48498. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48499. var num_scanlines = hdrInfo.height;
  48500. var scanline_width = hdrInfo.width;
  48501. var a, b, c, d, count;
  48502. var dataIndex = hdrInfo.dataPosition;
  48503. var index = 0, endIndex = 0, i = 0;
  48504. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48505. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48506. // 3 channels of 4 bytes per pixel in float.
  48507. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48508. var resultArray = new Float32Array(resultBuffer);
  48509. // read in each successive scanline
  48510. while (num_scanlines > 0) {
  48511. a = uint8array[dataIndex++];
  48512. b = uint8array[dataIndex++];
  48513. c = uint8array[dataIndex++];
  48514. d = uint8array[dataIndex++];
  48515. if (a != 2 || b != 2 || (c & 0x80)) {
  48516. // this file is not run length encoded
  48517. throw "HDR Bad header format, not RLE";
  48518. }
  48519. if (((c << 8) | d) != scanline_width) {
  48520. throw "HDR Bad header format, wrong scan line width";
  48521. }
  48522. index = 0;
  48523. // read each of the four channels for the scanline into the buffer
  48524. for (i = 0; i < 4; i++) {
  48525. endIndex = (i + 1) * scanline_width;
  48526. while (index < endIndex) {
  48527. a = uint8array[dataIndex++];
  48528. b = uint8array[dataIndex++];
  48529. if (a > 128) {
  48530. // a run of the same value
  48531. count = a - 128;
  48532. if ((count == 0) || (count > endIndex - index)) {
  48533. throw "HDR Bad Format, bad scanline data (run)";
  48534. }
  48535. while (count-- > 0) {
  48536. scanLineArray[index++] = b;
  48537. }
  48538. }
  48539. else {
  48540. // a non-run
  48541. count = a;
  48542. if ((count == 0) || (count > endIndex - index)) {
  48543. throw "HDR Bad Format, bad scanline data (non-run)";
  48544. }
  48545. scanLineArray[index++] = b;
  48546. if (--count > 0) {
  48547. for (var j = 0; j < count; j++) {
  48548. scanLineArray[index++] = uint8array[dataIndex++];
  48549. }
  48550. }
  48551. }
  48552. }
  48553. }
  48554. // now convert data from buffer into floats
  48555. for (i = 0; i < scanline_width; i++) {
  48556. a = scanLineArray[i];
  48557. b = scanLineArray[i + scanline_width];
  48558. c = scanLineArray[i + 2 * scanline_width];
  48559. d = scanLineArray[i + 3 * scanline_width];
  48560. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48561. }
  48562. num_scanlines--;
  48563. }
  48564. return resultArray;
  48565. };
  48566. return HDRTools;
  48567. }());
  48568. Internals.HDRTools = HDRTools;
  48569. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48570. })(BABYLON || (BABYLON = {}));
  48571. //# sourceMappingURL=babylon.hdr.js.map
  48572. var BABYLON;
  48573. (function (BABYLON) {
  48574. /**
  48575. * This represents a texture coming from an HDR input.
  48576. *
  48577. * The only supported format is currently panorama picture stored in RGBE format.
  48578. * Example of such files can be found on HDRLib: http://hdrlib.com/
  48579. */
  48580. var HDRCubeTexture = (function (_super) {
  48581. __extends(HDRCubeTexture, _super);
  48582. /**
  48583. * Instantiates an HDRTexture from the following parameters.
  48584. *
  48585. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  48586. * @param scene The scene the texture will be used in
  48587. * @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.
  48588. * @param noMipmap Forces to not generate the mipmap if true
  48589. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  48590. * @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)
  48591. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  48592. */
  48593. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  48594. if (noMipmap === void 0) { noMipmap = false; }
  48595. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48596. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48597. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48598. if (onLoad === void 0) { onLoad = null; }
  48599. if (onError === void 0) { onError = null; }
  48600. var _this = _super.call(this, scene) || this;
  48601. _this._useInGammaSpace = false;
  48602. _this._generateHarmonics = true;
  48603. _this._isBABYLONPreprocessed = false;
  48604. _this._onLoad = null;
  48605. _this._onError = null;
  48606. /**
  48607. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  48608. */
  48609. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48610. /**
  48611. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  48612. * This is usefull at run time to apply the good shader.
  48613. */
  48614. _this.isPMREM = false;
  48615. _this._isBlocking = true;
  48616. if (!url) {
  48617. return _this;
  48618. }
  48619. _this.name = url;
  48620. _this.url = url;
  48621. _this.hasAlpha = false;
  48622. _this.isCube = true;
  48623. _this._textureMatrix = BABYLON.Matrix.Identity();
  48624. _this._onLoad = onLoad;
  48625. _this._onError = onError;
  48626. _this.gammaSpace = false;
  48627. if (size) {
  48628. _this._isBABYLONPreprocessed = false;
  48629. _this._noMipmap = noMipmap;
  48630. _this._size = size;
  48631. _this._useInGammaSpace = useInGammaSpace;
  48632. _this._usePMREMGenerator = usePMREMGenerator &&
  48633. scene.getEngine().getCaps().textureLOD &&
  48634. _this.getScene().getEngine().getCaps().textureFloat &&
  48635. !_this._useInGammaSpace;
  48636. }
  48637. else {
  48638. _this._isBABYLONPreprocessed = true;
  48639. _this._noMipmap = false;
  48640. _this._useInGammaSpace = false;
  48641. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  48642. _this.getScene().getEngine().getCaps().textureFloat &&
  48643. !_this._useInGammaSpace;
  48644. }
  48645. _this.isPMREM = _this._usePMREMGenerator;
  48646. _this._texture = _this._getFromCache(url, _this._noMipmap);
  48647. if (!_this._texture) {
  48648. if (!scene.useDelayedTextureLoading) {
  48649. _this.loadTexture();
  48650. }
  48651. else {
  48652. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48653. }
  48654. }
  48655. return _this;
  48656. }
  48657. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  48658. /**
  48659. * Gets wether or not the texture is blocking during loading.
  48660. */
  48661. get: function () {
  48662. return this._isBlocking;
  48663. },
  48664. /**
  48665. * Sets wether or not the texture is blocking during loading.
  48666. */
  48667. set: function (value) {
  48668. this._isBlocking = value;
  48669. },
  48670. enumerable: true,
  48671. configurable: true
  48672. });
  48673. /**
  48674. * Occurs when the file is a preprocessed .babylon.hdr file.
  48675. */
  48676. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  48677. var _this = this;
  48678. var mipLevels = 0;
  48679. var floatArrayView = null;
  48680. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  48681. var mips = [];
  48682. var startIndex = 30;
  48683. for (var level = 0; level < mipLevels; level++) {
  48684. mips.push([]);
  48685. // Fill each pixel of the mip level.
  48686. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  48687. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48688. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  48689. mips[level].push(faceData);
  48690. startIndex += faceSize;
  48691. }
  48692. }
  48693. return mips;
  48694. } : null;
  48695. var callback = function (buffer) {
  48696. // Create Native Array Views
  48697. var intArrayView = new Int32Array(buffer);
  48698. floatArrayView = new Float32Array(buffer);
  48699. // Fill header.
  48700. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  48701. _this._size = intArrayView[1]; // CubeMap max mip face size.
  48702. // Update Texture Information.
  48703. _this._texture.updateSize(_this._size, _this._size);
  48704. // Fill polynomial information.
  48705. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  48706. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  48707. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  48708. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  48709. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  48710. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  48711. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  48712. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  48713. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  48714. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  48715. _this.sphericalPolynomial = sphericalPolynomial;
  48716. // Fill pixel data.
  48717. mipLevels = intArrayView[29]; // Number of mip levels.
  48718. var startIndex = 30;
  48719. var data = [];
  48720. var faceSize = Math.pow(_this._size, 2) * 3;
  48721. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48722. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  48723. startIndex += faceSize;
  48724. }
  48725. var results = [];
  48726. var byteArray = null;
  48727. // Push each faces.
  48728. for (var k = 0; k < 6; k++) {
  48729. var dataFace = null;
  48730. // To be deprecated.
  48731. if (version === 1) {
  48732. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  48733. dataFace = data[j];
  48734. }
  48735. // If special cases.
  48736. if (!mipmapGenerator) {
  48737. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48738. // 3 channels of 1 bytes per pixel in bytes.
  48739. var byteBuffer = new ArrayBuffer(faceSize);
  48740. byteArray = new Uint8Array(byteBuffer);
  48741. }
  48742. for (var i = 0; i < _this._size * _this._size; i++) {
  48743. // Put in gamma space if requested.
  48744. if (_this._useInGammaSpace) {
  48745. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48746. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48747. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48748. }
  48749. // Convert to int texture for fallback.
  48750. if (byteArray) {
  48751. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48752. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48753. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48754. // May use luminance instead if the result is not accurate.
  48755. var max = Math.max(Math.max(r, g), b);
  48756. if (max > 255) {
  48757. var scale = 255 / max;
  48758. r *= scale;
  48759. g *= scale;
  48760. b *= scale;
  48761. }
  48762. byteArray[(i * 3) + 0] = r;
  48763. byteArray[(i * 3) + 1] = g;
  48764. byteArray[(i * 3) + 2] = b;
  48765. }
  48766. }
  48767. }
  48768. // Fill the array accordingly.
  48769. if (byteArray) {
  48770. results.push(byteArray);
  48771. }
  48772. else {
  48773. results.push(dataFace);
  48774. }
  48775. }
  48776. return results;
  48777. };
  48778. 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);
  48779. };
  48780. /**
  48781. * Occurs when the file is raw .hdr file.
  48782. */
  48783. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48784. var _this = this;
  48785. var callback = function (buffer) {
  48786. // Extract the raw linear data.
  48787. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48788. // Generate harmonics if needed.
  48789. if (_this._generateHarmonics) {
  48790. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48791. _this.sphericalPolynomial = sphericalPolynomial;
  48792. }
  48793. var results = [];
  48794. var byteArray = null;
  48795. // Push each faces.
  48796. for (var j = 0; j < 6; j++) {
  48797. // Create uintarray fallback.
  48798. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48799. // 3 channels of 1 bytes per pixel in bytes.
  48800. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48801. byteArray = new Uint8Array(byteBuffer);
  48802. }
  48803. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48804. // If special cases.
  48805. if (_this._useInGammaSpace || byteArray) {
  48806. for (var i = 0; i < _this._size * _this._size; i++) {
  48807. // Put in gamma space if requested.
  48808. if (_this._useInGammaSpace) {
  48809. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48810. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48811. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48812. }
  48813. // Convert to int texture for fallback.
  48814. if (byteArray) {
  48815. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48816. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48817. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48818. // May use luminance instead if the result is not accurate.
  48819. var max = Math.max(Math.max(r, g), b);
  48820. if (max > 255) {
  48821. var scale = 255 / max;
  48822. r *= scale;
  48823. g *= scale;
  48824. b *= scale;
  48825. }
  48826. byteArray[(i * 3) + 0] = r;
  48827. byteArray[(i * 3) + 1] = g;
  48828. byteArray[(i * 3) + 2] = b;
  48829. }
  48830. }
  48831. }
  48832. if (byteArray) {
  48833. results.push(byteArray);
  48834. }
  48835. else {
  48836. results.push(dataFace);
  48837. }
  48838. }
  48839. return results;
  48840. };
  48841. var mipmapGenerator = null;
  48842. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48843. // if (!this._noMipmap &&
  48844. // this._usePMREMGenerator) {
  48845. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48846. // // Custom setup of the generator matching with the PBR shader values.
  48847. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48848. // this._size,
  48849. // this._size,
  48850. // 0,
  48851. // 3,
  48852. // this.getScene().getEngine().getCaps().textureFloat,
  48853. // 2048,
  48854. // 0.25,
  48855. // false,
  48856. // true);
  48857. // return generator.filterCubeMap();
  48858. // };
  48859. // }
  48860. 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);
  48861. };
  48862. /**
  48863. * Starts the loading process of the texture.
  48864. */
  48865. HDRCubeTexture.prototype.loadTexture = function () {
  48866. if (this._isBABYLONPreprocessed) {
  48867. this.loadBabylonTexture();
  48868. }
  48869. else {
  48870. this.loadHDRTexture();
  48871. }
  48872. };
  48873. HDRCubeTexture.prototype.clone = function () {
  48874. var size = this._isBABYLONPreprocessed ? null : this._size;
  48875. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48876. // Base texture
  48877. newTexture.level = this.level;
  48878. newTexture.wrapU = this.wrapU;
  48879. newTexture.wrapV = this.wrapV;
  48880. newTexture.coordinatesIndex = this.coordinatesIndex;
  48881. newTexture.coordinatesMode = this.coordinatesMode;
  48882. return newTexture;
  48883. };
  48884. // Methods
  48885. HDRCubeTexture.prototype.delayLoad = function () {
  48886. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48887. return;
  48888. }
  48889. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48890. this._texture = this._getFromCache(this.url, this._noMipmap);
  48891. if (!this._texture) {
  48892. this.loadTexture();
  48893. }
  48894. };
  48895. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  48896. return this._textureMatrix;
  48897. };
  48898. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  48899. this._textureMatrix = value;
  48900. };
  48901. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  48902. var texture = null;
  48903. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  48904. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  48905. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  48906. texture.name = parsedTexture.name;
  48907. texture.hasAlpha = parsedTexture.hasAlpha;
  48908. texture.level = parsedTexture.level;
  48909. texture.coordinatesMode = parsedTexture.coordinatesMode;
  48910. texture.isBlocking = parsedTexture.isBlocking;
  48911. }
  48912. return texture;
  48913. };
  48914. HDRCubeTexture.prototype.serialize = function () {
  48915. if (!this.name) {
  48916. return null;
  48917. }
  48918. var serializationObject = {};
  48919. serializationObject.name = this.name;
  48920. serializationObject.hasAlpha = this.hasAlpha;
  48921. serializationObject.isCube = true;
  48922. serializationObject.level = this.level;
  48923. serializationObject.size = this._size;
  48924. serializationObject.coordinatesMode = this.coordinatesMode;
  48925. serializationObject.useInGammaSpace = this._useInGammaSpace;
  48926. serializationObject.generateHarmonics = this._generateHarmonics;
  48927. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  48928. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  48929. serializationObject.customType = "BABYLON.HDRCubeTexture";
  48930. serializationObject.noMipmap = this._noMipmap;
  48931. serializationObject.isBlocking = this._isBlocking;
  48932. return serializationObject;
  48933. };
  48934. /**
  48935. * Saves as a file the data contained in the texture in a binary format.
  48936. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48937. * as the spherical used in the lighting.
  48938. * @param url The HDR file url.
  48939. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48940. * @param onError Method called if any error happens during download.
  48941. * @return The packed binary data.
  48942. */
  48943. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  48944. if (onError === void 0) { onError = null; }
  48945. var callback = function (buffer) {
  48946. var data = new Blob([buffer], { type: 'application/octet-stream' });
  48947. // Returns a URL you can use as a href.
  48948. var objUrl = window.URL.createObjectURL(data);
  48949. // Simulates a link to it and click to dowload.
  48950. var a = document.createElement("a");
  48951. document.body.appendChild(a);
  48952. a.style.display = "none";
  48953. a.href = objUrl;
  48954. a.download = "envmap.babylon.hdr";
  48955. a.click();
  48956. };
  48957. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  48958. };
  48959. /**
  48960. * Serializes the data contained in the texture in a binary format.
  48961. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48962. * as the spherical used in the lighting.
  48963. * @param url The HDR file url.
  48964. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48965. * @param onError Method called if any error happens during download.
  48966. * @return The packed binary data.
  48967. */
  48968. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  48969. if (onError === void 0) { onError = null; }
  48970. // Needs the url tho create the texture.
  48971. if (!url) {
  48972. return null;
  48973. }
  48974. // Check Power of two size.
  48975. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  48976. return null;
  48977. }
  48978. // Coming Back in 3.1.
  48979. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  48980. return null;
  48981. };
  48982. HDRCubeTexture._facesMapping = [
  48983. "right",
  48984. "left",
  48985. "up",
  48986. "down",
  48987. "front",
  48988. "back"
  48989. ];
  48990. return HDRCubeTexture;
  48991. }(BABYLON.BaseTexture));
  48992. BABYLON.HDRCubeTexture = HDRCubeTexture;
  48993. })(BABYLON || (BABYLON = {}));
  48994. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  48995. var BABYLON;
  48996. (function (BABYLON) {
  48997. var DefaultLoadingScreen = (function () {
  48998. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48999. if (_loadingText === void 0) { _loadingText = ""; }
  49000. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  49001. var _this = this;
  49002. this._renderingCanvas = _renderingCanvas;
  49003. this._loadingText = _loadingText;
  49004. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  49005. // Resize
  49006. this._resizeLoadingUI = function () {
  49007. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  49008. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  49009. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  49010. _this._loadingDiv.style.left = canvasRect.left + "px";
  49011. _this._loadingDiv.style.top = canvasRect.top + "px";
  49012. _this._loadingDiv.style.width = canvasRect.width + "px";
  49013. _this._loadingDiv.style.height = canvasRect.height + "px";
  49014. };
  49015. }
  49016. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  49017. if (this._loadingDiv) {
  49018. // Do not add a loading screen if there is already one
  49019. return;
  49020. }
  49021. this._loadingDiv = document.createElement("div");
  49022. this._loadingDiv.id = "babylonjsLoadingDiv";
  49023. this._loadingDiv.style.opacity = "0";
  49024. this._loadingDiv.style.transition = "opacity 1.5s ease";
  49025. // Loading text
  49026. this._loadingTextDiv = document.createElement("div");
  49027. this._loadingTextDiv.style.position = "absolute";
  49028. this._loadingTextDiv.style.left = "0";
  49029. this._loadingTextDiv.style.top = "50%";
  49030. this._loadingTextDiv.style.marginTop = "80px";
  49031. this._loadingTextDiv.style.width = "100%";
  49032. this._loadingTextDiv.style.height = "20px";
  49033. this._loadingTextDiv.style.fontFamily = "Arial";
  49034. this._loadingTextDiv.style.fontSize = "14px";
  49035. this._loadingTextDiv.style.color = "white";
  49036. this._loadingTextDiv.style.textAlign = "center";
  49037. this._loadingTextDiv.innerHTML = "Loading";
  49038. this._loadingDiv.appendChild(this._loadingTextDiv);
  49039. //set the predefined text
  49040. this._loadingTextDiv.innerHTML = this._loadingText;
  49041. // Generating keyframes
  49042. var style = document.createElement('style');
  49043. style.type = 'text/css';
  49044. 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 }";
  49045. style.innerHTML = keyFrames;
  49046. document.getElementsByTagName('head')[0].appendChild(style);
  49047. // Loading img
  49048. var imgBack = new Image();
  49049. 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";
  49050. imgBack.style.position = "absolute";
  49051. imgBack.style.left = "50%";
  49052. imgBack.style.top = "50%";
  49053. imgBack.style.marginLeft = "-60px";
  49054. imgBack.style.marginTop = "-60px";
  49055. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  49056. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  49057. imgBack.style.transformOrigin = "50% 50%";
  49058. imgBack.style.webkitTransformOrigin = "50% 50%";
  49059. this._loadingDiv.appendChild(imgBack);
  49060. this._resizeLoadingUI();
  49061. window.addEventListener("resize", this._resizeLoadingUI);
  49062. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49063. document.body.appendChild(this._loadingDiv);
  49064. this._loadingDiv.style.opacity = "1";
  49065. };
  49066. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  49067. var _this = this;
  49068. if (!this._loadingDiv) {
  49069. return;
  49070. }
  49071. var onTransitionEnd = function () {
  49072. if (!_this._loadingDiv) {
  49073. return;
  49074. }
  49075. document.body.removeChild(_this._loadingDiv);
  49076. window.removeEventListener("resize", _this._resizeLoadingUI);
  49077. _this._loadingDiv = null;
  49078. };
  49079. this._loadingDiv.style.opacity = "0";
  49080. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  49081. };
  49082. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  49083. set: function (text) {
  49084. this._loadingText = text;
  49085. if (this._loadingTextDiv) {
  49086. this._loadingTextDiv.innerHTML = this._loadingText;
  49087. }
  49088. },
  49089. enumerable: true,
  49090. configurable: true
  49091. });
  49092. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  49093. get: function () {
  49094. return this._loadingDivBackgroundColor;
  49095. },
  49096. set: function (color) {
  49097. this._loadingDivBackgroundColor = color;
  49098. if (!this._loadingDiv) {
  49099. return;
  49100. }
  49101. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49102. },
  49103. enumerable: true,
  49104. configurable: true
  49105. });
  49106. return DefaultLoadingScreen;
  49107. }());
  49108. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  49109. })(BABYLON || (BABYLON = {}));
  49110. //# sourceMappingURL=babylon.loadingScreen.js.map
  49111. var BABYLON;
  49112. (function (BABYLON) {
  49113. var SceneLoader = (function () {
  49114. function SceneLoader() {
  49115. }
  49116. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  49117. get: function () {
  49118. return 0;
  49119. },
  49120. enumerable: true,
  49121. configurable: true
  49122. });
  49123. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  49124. get: function () {
  49125. return 1;
  49126. },
  49127. enumerable: true,
  49128. configurable: true
  49129. });
  49130. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  49131. get: function () {
  49132. return 2;
  49133. },
  49134. enumerable: true,
  49135. configurable: true
  49136. });
  49137. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  49138. get: function () {
  49139. return 3;
  49140. },
  49141. enumerable: true,
  49142. configurable: true
  49143. });
  49144. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  49145. get: function () {
  49146. return SceneLoader._ForceFullSceneLoadingForIncremental;
  49147. },
  49148. set: function (value) {
  49149. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  49150. },
  49151. enumerable: true,
  49152. configurable: true
  49153. });
  49154. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  49155. get: function () {
  49156. return SceneLoader._ShowLoadingScreen;
  49157. },
  49158. set: function (value) {
  49159. SceneLoader._ShowLoadingScreen = value;
  49160. },
  49161. enumerable: true,
  49162. configurable: true
  49163. });
  49164. Object.defineProperty(SceneLoader, "loggingLevel", {
  49165. get: function () {
  49166. return SceneLoader._loggingLevel;
  49167. },
  49168. set: function (value) {
  49169. SceneLoader._loggingLevel = value;
  49170. },
  49171. enumerable: true,
  49172. configurable: true
  49173. });
  49174. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  49175. get: function () {
  49176. return SceneLoader._CleanBoneMatrixWeights;
  49177. },
  49178. set: function (value) {
  49179. SceneLoader._CleanBoneMatrixWeights = value;
  49180. },
  49181. enumerable: true,
  49182. configurable: true
  49183. });
  49184. SceneLoader._getDefaultPlugin = function () {
  49185. return SceneLoader._registeredPlugins[".babylon"];
  49186. };
  49187. SceneLoader._getPluginForExtension = function (extension) {
  49188. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  49189. if (registeredPlugin) {
  49190. return registeredPlugin;
  49191. }
  49192. return SceneLoader._getDefaultPlugin();
  49193. };
  49194. SceneLoader._getPluginForDirectLoad = function (data) {
  49195. for (var extension in SceneLoader._registeredPlugins) {
  49196. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  49197. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  49198. return SceneLoader._registeredPlugins[extension];
  49199. }
  49200. }
  49201. return SceneLoader._getDefaultPlugin();
  49202. };
  49203. SceneLoader._getPluginForFilename = function (sceneFilename) {
  49204. if (sceneFilename.name) {
  49205. sceneFilename = sceneFilename.name;
  49206. }
  49207. var dotPosition = sceneFilename.lastIndexOf(".");
  49208. var queryStringPosition = sceneFilename.indexOf("?");
  49209. if (queryStringPosition === -1) {
  49210. queryStringPosition = sceneFilename.length;
  49211. }
  49212. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  49213. return SceneLoader._getPluginForExtension(extension);
  49214. };
  49215. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  49216. SceneLoader._getDirectLoad = function (sceneFilename) {
  49217. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  49218. return sceneFilename.substr(5);
  49219. }
  49220. return null;
  49221. };
  49222. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49223. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  49224. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  49225. var plugin = registeredPlugin.plugin;
  49226. var useArrayBuffer = registeredPlugin.isBinary;
  49227. var database;
  49228. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  49229. var dataCallback = function (data) {
  49230. if (scene.isDisposed) {
  49231. onError("Scene has been disposed");
  49232. return;
  49233. }
  49234. scene.database = database;
  49235. try {
  49236. onSuccess(plugin, data);
  49237. }
  49238. catch (e) {
  49239. onError(null, e);
  49240. }
  49241. };
  49242. var manifestChecked = function (success) {
  49243. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  49244. onError(request.status + " " + request.statusText);
  49245. });
  49246. };
  49247. if (directLoad) {
  49248. dataCallback(directLoad);
  49249. return;
  49250. }
  49251. if (rootUrl.indexOf("file:") === -1) {
  49252. if (scene.getEngine().enableOfflineSupport) {
  49253. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  49254. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  49255. }
  49256. else {
  49257. manifestChecked(true);
  49258. }
  49259. }
  49260. else {
  49261. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  49262. }
  49263. };
  49264. // Public functions
  49265. SceneLoader.GetPluginForExtension = function (extension) {
  49266. return SceneLoader._getPluginForExtension(extension).plugin;
  49267. };
  49268. SceneLoader.RegisterPlugin = function (plugin) {
  49269. if (typeof plugin.extensions === "string") {
  49270. var extension = plugin.extensions;
  49271. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49272. plugin: plugin,
  49273. isBinary: false
  49274. };
  49275. }
  49276. else {
  49277. var extensions = plugin.extensions;
  49278. Object.keys(extensions).forEach(function (extension) {
  49279. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49280. plugin: plugin,
  49281. isBinary: extensions[extension].isBinary
  49282. };
  49283. });
  49284. }
  49285. };
  49286. /**
  49287. * Import meshes into a scene
  49288. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  49289. * @param rootUrl a string that defines the root url for scene and resources
  49290. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49291. * @param scene the instance of BABYLON.Scene to append to
  49292. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  49293. * @param onProgress a callback with a progress event for each file being loaded
  49294. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49295. */
  49296. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49297. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49298. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49299. return;
  49300. }
  49301. var loadingToken = {};
  49302. scene._addPendingData(loadingToken);
  49303. var errorHandler = function (message, exception) {
  49304. if (onError) {
  49305. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49306. }
  49307. scene._removePendingData(loadingToken);
  49308. };
  49309. var progressHandler = function (event) {
  49310. if (onProgress) {
  49311. onProgress(event);
  49312. }
  49313. };
  49314. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49315. if (plugin.importMesh) {
  49316. var syncedPlugin = plugin;
  49317. var meshes = [];
  49318. var particleSystems = [];
  49319. var skeletons = [];
  49320. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  49321. return;
  49322. }
  49323. if (onSuccess) {
  49324. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49325. onSuccess(meshes, particleSystems, skeletons);
  49326. scene._removePendingData(loadingToken);
  49327. }
  49328. }
  49329. else {
  49330. var asyncedPlugin = plugin;
  49331. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  49332. if (onSuccess) {
  49333. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49334. onSuccess(meshes, particleSystems, skeletons);
  49335. scene._removePendingData(loadingToken);
  49336. }
  49337. }, progressHandler, errorHandler);
  49338. }
  49339. }, progressHandler, errorHandler);
  49340. };
  49341. /**
  49342. * Load a scene
  49343. * @param rootUrl a string that defines the root url for scene and resources
  49344. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49345. * @param engine is the instance of BABYLON.Engine to use to create the scene
  49346. * @param onSuccess a callback with the scene when import succeeds
  49347. * @param onProgress a callback with a progress event for each file being loaded
  49348. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49349. */
  49350. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  49351. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  49352. };
  49353. /**
  49354. * Append a scene
  49355. * @param rootUrl a string that defines the root url for scene and resources
  49356. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49357. * @param scene is the instance of BABYLON.Scene to append to
  49358. * @param onSuccess a callback with the scene when import succeeds
  49359. * @param onProgress a callback with a progress event for each file being loaded
  49360. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49361. */
  49362. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49363. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49364. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49365. return;
  49366. }
  49367. if (SceneLoader.ShowLoadingScreen) {
  49368. scene.getEngine().displayLoadingUI();
  49369. }
  49370. var loadingToken = {};
  49371. scene._addPendingData(loadingToken);
  49372. var errorHandler = function (message, exception) {
  49373. if (onError) {
  49374. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49375. }
  49376. scene._removePendingData(loadingToken);
  49377. scene.getEngine().hideLoadingUI();
  49378. };
  49379. var progressHandler = function (event) {
  49380. if (onProgress) {
  49381. onProgress(event);
  49382. }
  49383. };
  49384. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49385. if (plugin.load) {
  49386. var syncedPlugin = plugin;
  49387. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  49388. return;
  49389. }
  49390. if (onSuccess) {
  49391. onSuccess(scene);
  49392. }
  49393. scene.loadingPluginName = plugin.name;
  49394. scene._removePendingData(loadingToken);
  49395. }
  49396. else {
  49397. var asyncedPlugin = plugin;
  49398. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49399. if (onSuccess) {
  49400. onSuccess(scene);
  49401. }
  49402. scene.loadingPluginName = plugin.name;
  49403. scene._removePendingData(loadingToken);
  49404. }, progressHandler, errorHandler);
  49405. }
  49406. if (SceneLoader.ShowLoadingScreen) {
  49407. scene.executeWhenReady(function () {
  49408. scene.getEngine().hideLoadingUI();
  49409. });
  49410. }
  49411. }, progressHandler, errorHandler);
  49412. };
  49413. // Flags
  49414. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49415. SceneLoader._ShowLoadingScreen = true;
  49416. SceneLoader._CleanBoneMatrixWeights = false;
  49417. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49418. // Members
  49419. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49420. SceneLoader._registeredPlugins = {};
  49421. return SceneLoader;
  49422. }());
  49423. BABYLON.SceneLoader = SceneLoader;
  49424. ;
  49425. })(BABYLON || (BABYLON = {}));
  49426. //# sourceMappingURL=babylon.sceneLoader.js.map
  49427. var BABYLON;
  49428. (function (BABYLON) {
  49429. var Internals;
  49430. (function (Internals) {
  49431. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49432. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49433. var parsedMaterial = parsedData.materials[index];
  49434. if (parsedMaterial.id === id) {
  49435. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49436. }
  49437. }
  49438. return null;
  49439. };
  49440. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49441. for (var i in names) {
  49442. if (mesh.name === names[i]) {
  49443. hierarchyIds.push(mesh.id);
  49444. return true;
  49445. }
  49446. }
  49447. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49448. hierarchyIds.push(mesh.id);
  49449. return true;
  49450. }
  49451. return false;
  49452. };
  49453. var logOperation = function (operation, producer) {
  49454. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49455. };
  49456. BABYLON.SceneLoader.RegisterPlugin({
  49457. name: "babylon.js",
  49458. extensions: ".babylon",
  49459. canDirectLoad: function (data) {
  49460. if (data.indexOf("babylon") !== -1) {
  49461. return true;
  49462. }
  49463. return false;
  49464. },
  49465. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  49466. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49467. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49468. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49469. // and avoid problems with multiple concurrent .babylon loads.
  49470. var log = "importMesh has failed JSON parse";
  49471. try {
  49472. var parsedData = JSON.parse(data);
  49473. log = "";
  49474. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49475. if (!meshesNames) {
  49476. meshesNames = null;
  49477. }
  49478. else if (!Array.isArray(meshesNames)) {
  49479. meshesNames = [meshesNames];
  49480. }
  49481. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49482. var loadedSkeletonsIds = [];
  49483. var loadedMaterialsIds = [];
  49484. var hierarchyIds = [];
  49485. var index;
  49486. var cache;
  49487. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49488. var parsedMesh = parsedData.meshes[index];
  49489. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49490. if (meshesNames !== null) {
  49491. // Remove found mesh name from list.
  49492. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49493. }
  49494. //Geometry?
  49495. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49496. //does the file contain geometries?
  49497. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49498. //find the correct geometry and add it to the scene
  49499. var found = false;
  49500. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49501. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49502. return;
  49503. }
  49504. else {
  49505. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49506. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49507. switch (geometryType) {
  49508. case "boxes":
  49509. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49510. break;
  49511. case "spheres":
  49512. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49513. break;
  49514. case "cylinders":
  49515. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49516. break;
  49517. case "toruses":
  49518. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49519. break;
  49520. case "grounds":
  49521. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49522. break;
  49523. case "planes":
  49524. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49525. break;
  49526. case "torusKnots":
  49527. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49528. break;
  49529. case "vertexData":
  49530. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49531. break;
  49532. }
  49533. found = true;
  49534. }
  49535. });
  49536. }
  49537. });
  49538. if (found === false) {
  49539. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49540. }
  49541. }
  49542. }
  49543. // Material ?
  49544. if (parsedMesh.materialId) {
  49545. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49546. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49547. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49548. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49549. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49550. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49551. var subMatId = parsedMultiMaterial.materials[matIndex];
  49552. loadedMaterialsIds.push(subMatId);
  49553. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49554. log += "\n\tMaterial " + mat.toString(fullDetails);
  49555. }
  49556. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49557. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49558. materialFound = true;
  49559. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49560. break;
  49561. }
  49562. }
  49563. }
  49564. if (materialFound === false) {
  49565. loadedMaterialsIds.push(parsedMesh.materialId);
  49566. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49567. if (!mat) {
  49568. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49569. }
  49570. else {
  49571. log += "\n\tMaterial " + mat.toString(fullDetails);
  49572. }
  49573. }
  49574. }
  49575. // Skeleton ?
  49576. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49577. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49578. if (skeletonAlreadyLoaded === false) {
  49579. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49580. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49581. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49582. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49583. skeletons.push(skeleton);
  49584. loadedSkeletonsIds.push(parsedSkeleton.id);
  49585. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49586. }
  49587. }
  49588. }
  49589. }
  49590. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49591. meshes.push(mesh);
  49592. log += "\n\tMesh " + mesh.toString(fullDetails);
  49593. }
  49594. }
  49595. // Connecting parents
  49596. var currentMesh;
  49597. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49598. currentMesh = scene.meshes[index];
  49599. if (currentMesh._waitingParentId) {
  49600. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49601. currentMesh._waitingParentId = undefined;
  49602. }
  49603. }
  49604. // freeze and compute world matrix application
  49605. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49606. currentMesh = scene.meshes[index];
  49607. if (currentMesh._waitingFreezeWorldMatrix) {
  49608. currentMesh.freezeWorldMatrix();
  49609. currentMesh._waitingFreezeWorldMatrix = undefined;
  49610. }
  49611. else {
  49612. currentMesh.computeWorldMatrix(true);
  49613. }
  49614. }
  49615. }
  49616. // Particles
  49617. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49618. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49619. var parsedParticleSystem = parsedData.particleSystems[index];
  49620. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49621. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49622. }
  49623. }
  49624. }
  49625. return true;
  49626. }
  49627. catch (err) {
  49628. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  49629. log = null;
  49630. throw err;
  49631. }
  49632. finally {
  49633. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49634. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49635. }
  49636. }
  49637. },
  49638. load: function (scene, data, rootUrl) {
  49639. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49640. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49641. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49642. // and avoid problems with multiple concurrent .babylon loads.
  49643. var log = "importScene has failed JSON parse";
  49644. try {
  49645. var parsedData = JSON.parse(data);
  49646. log = "";
  49647. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49648. // Scene
  49649. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49650. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49651. }
  49652. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49653. scene.autoClear = parsedData.autoClear;
  49654. }
  49655. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49656. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49657. }
  49658. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49659. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49660. }
  49661. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49662. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49663. }
  49664. // Fog
  49665. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49666. scene.fogMode = parsedData.fogMode;
  49667. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49668. scene.fogStart = parsedData.fogStart;
  49669. scene.fogEnd = parsedData.fogEnd;
  49670. scene.fogDensity = parsedData.fogDensity;
  49671. log += "\tFog mode for scene: ";
  49672. switch (scene.fogMode) {
  49673. // getters not compiling, so using hardcoded
  49674. case 1:
  49675. log += "exp\n";
  49676. break;
  49677. case 2:
  49678. log += "exp2\n";
  49679. break;
  49680. case 3:
  49681. log += "linear\n";
  49682. break;
  49683. }
  49684. }
  49685. //Physics
  49686. if (parsedData.physicsEnabled) {
  49687. var physicsPlugin;
  49688. if (parsedData.physicsEngine === "cannon") {
  49689. physicsPlugin = new BABYLON.CannonJSPlugin();
  49690. }
  49691. else if (parsedData.physicsEngine === "oimo") {
  49692. physicsPlugin = new BABYLON.OimoJSPlugin();
  49693. }
  49694. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49695. //else - default engine, which is currently oimo
  49696. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49697. scene.enablePhysics(physicsGravity, physicsPlugin);
  49698. }
  49699. // Metadata
  49700. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49701. scene.metadata = parsedData.metadata;
  49702. }
  49703. //collisions, if defined. otherwise, default is true
  49704. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49705. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49706. }
  49707. scene.workerCollisions = !!parsedData.workerCollisions;
  49708. var index;
  49709. var cache;
  49710. // Lights
  49711. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49712. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49713. var parsedLight = parsedData.lights[index];
  49714. var light = BABYLON.Light.Parse(parsedLight, scene);
  49715. log += (index === 0 ? "\n\tLights:" : "");
  49716. log += "\n\t\t" + light.toString(fullDetails);
  49717. }
  49718. }
  49719. // Animations
  49720. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49721. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49722. var parsedAnimation = parsedData.animations[index];
  49723. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49724. scene.animations.push(animation);
  49725. log += (index === 0 ? "\n\tAnimations:" : "");
  49726. log += "\n\t\t" + animation.toString(fullDetails);
  49727. }
  49728. }
  49729. if (parsedData.autoAnimate) {
  49730. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49731. }
  49732. // Materials
  49733. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49734. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49735. var parsedMaterial = parsedData.materials[index];
  49736. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49737. log += (index === 0 ? "\n\tMaterials:" : "");
  49738. log += "\n\t\t" + mat.toString(fullDetails);
  49739. }
  49740. }
  49741. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49742. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49743. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49744. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49745. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49746. log += "\n\t\t" + mmat.toString(fullDetails);
  49747. }
  49748. }
  49749. // Morph targets
  49750. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49751. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49752. var managerData = _a[_i];
  49753. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49754. }
  49755. }
  49756. // Skeletons
  49757. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49758. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49759. var parsedSkeleton = parsedData.skeletons[index];
  49760. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49761. log += (index === 0 ? "\n\tSkeletons:" : "");
  49762. log += "\n\t\t" + skeleton.toString(fullDetails);
  49763. }
  49764. }
  49765. // Geometries
  49766. var geometries = parsedData.geometries;
  49767. if (geometries !== undefined && geometries !== null) {
  49768. // Boxes
  49769. var boxes = geometries.boxes;
  49770. if (boxes !== undefined && boxes !== null) {
  49771. for (index = 0, cache = boxes.length; index < cache; index++) {
  49772. var parsedBox = boxes[index];
  49773. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49774. }
  49775. }
  49776. // Spheres
  49777. var spheres = geometries.spheres;
  49778. if (spheres !== undefined && spheres !== null) {
  49779. for (index = 0, cache = spheres.length; index < cache; index++) {
  49780. var parsedSphere = spheres[index];
  49781. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49782. }
  49783. }
  49784. // Cylinders
  49785. var cylinders = geometries.cylinders;
  49786. if (cylinders !== undefined && cylinders !== null) {
  49787. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49788. var parsedCylinder = cylinders[index];
  49789. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49790. }
  49791. }
  49792. // Toruses
  49793. var toruses = geometries.toruses;
  49794. if (toruses !== undefined && toruses !== null) {
  49795. for (index = 0, cache = toruses.length; index < cache; index++) {
  49796. var parsedTorus = toruses[index];
  49797. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49798. }
  49799. }
  49800. // Grounds
  49801. var grounds = geometries.grounds;
  49802. if (grounds !== undefined && grounds !== null) {
  49803. for (index = 0, cache = grounds.length; index < cache; index++) {
  49804. var parsedGround = grounds[index];
  49805. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49806. }
  49807. }
  49808. // Planes
  49809. var planes = geometries.planes;
  49810. if (planes !== undefined && planes !== null) {
  49811. for (index = 0, cache = planes.length; index < cache; index++) {
  49812. var parsedPlane = planes[index];
  49813. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49814. }
  49815. }
  49816. // TorusKnots
  49817. var torusKnots = geometries.torusKnots;
  49818. if (torusKnots !== undefined && torusKnots !== null) {
  49819. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49820. var parsedTorusKnot = torusKnots[index];
  49821. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49822. }
  49823. }
  49824. // VertexData
  49825. var vertexData = geometries.vertexData;
  49826. if (vertexData !== undefined && vertexData !== null) {
  49827. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49828. var parsedVertexData = vertexData[index];
  49829. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49830. }
  49831. }
  49832. }
  49833. // Meshes
  49834. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49835. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49836. var parsedMesh = parsedData.meshes[index];
  49837. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49838. log += (index === 0 ? "\n\tMeshes:" : "");
  49839. log += "\n\t\t" + mesh.toString(fullDetails);
  49840. }
  49841. }
  49842. // Cameras
  49843. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49844. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49845. var parsedCamera = parsedData.cameras[index];
  49846. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49847. log += (index === 0 ? "\n\tCameras:" : "");
  49848. log += "\n\t\t" + camera.toString(fullDetails);
  49849. }
  49850. }
  49851. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49852. scene.setActiveCameraByID(parsedData.activeCameraID);
  49853. }
  49854. // Browsing all the graph to connect the dots
  49855. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49856. var camera = scene.cameras[index];
  49857. if (camera._waitingParentId) {
  49858. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49859. camera._waitingParentId = undefined;
  49860. }
  49861. }
  49862. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49863. var light = scene.lights[index];
  49864. if (light._waitingParentId) {
  49865. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49866. light._waitingParentId = undefined;
  49867. }
  49868. }
  49869. // Sounds
  49870. var loadedSounds = [];
  49871. var loadedSound;
  49872. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49873. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49874. var parsedSound = parsedData.sounds[index];
  49875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49876. if (!parsedSound.url)
  49877. parsedSound.url = parsedSound.name;
  49878. if (!loadedSounds[parsedSound.url]) {
  49879. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49880. loadedSounds[parsedSound.url] = loadedSound;
  49881. }
  49882. else {
  49883. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49884. }
  49885. }
  49886. else {
  49887. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49888. }
  49889. }
  49890. }
  49891. loadedSounds = [];
  49892. // Connect parents & children and parse actions
  49893. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49894. var mesh = scene.meshes[index];
  49895. if (mesh._waitingParentId) {
  49896. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49897. mesh._waitingParentId = undefined;
  49898. }
  49899. if (mesh._waitingActions) {
  49900. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49901. mesh._waitingActions = undefined;
  49902. }
  49903. }
  49904. // freeze world matrix application
  49905. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49906. var currentMesh = scene.meshes[index];
  49907. if (currentMesh._waitingFreezeWorldMatrix) {
  49908. currentMesh.freezeWorldMatrix();
  49909. currentMesh._waitingFreezeWorldMatrix = undefined;
  49910. }
  49911. else {
  49912. currentMesh.computeWorldMatrix(true);
  49913. }
  49914. }
  49915. // Particles Systems
  49916. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49917. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49918. var parsedParticleSystem = parsedData.particleSystems[index];
  49919. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49920. }
  49921. }
  49922. // Lens flares
  49923. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49924. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49925. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49926. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49927. }
  49928. }
  49929. // Shadows
  49930. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49931. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49932. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49933. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49934. }
  49935. }
  49936. // Lights exclusions / inclusions
  49937. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49938. var light = scene.lights[index];
  49939. // Excluded check
  49940. if (light._excludedMeshesIds.length > 0) {
  49941. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49942. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49943. if (excludedMesh) {
  49944. light.excludedMeshes.push(excludedMesh);
  49945. }
  49946. }
  49947. light._excludedMeshesIds = [];
  49948. }
  49949. // Included check
  49950. if (light._includedOnlyMeshesIds.length > 0) {
  49951. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49952. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49953. if (includedOnlyMesh) {
  49954. light.includedOnlyMeshes.push(includedOnlyMesh);
  49955. }
  49956. }
  49957. light._includedOnlyMeshesIds = [];
  49958. }
  49959. }
  49960. // Actions (scene)
  49961. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49962. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49963. }
  49964. // Finish
  49965. return true;
  49966. }
  49967. catch (err) {
  49968. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49969. log = null;
  49970. throw err;
  49971. }
  49972. finally {
  49973. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49974. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49975. }
  49976. }
  49977. }
  49978. });
  49979. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49980. })(BABYLON || (BABYLON = {}));
  49981. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49982. var BABYLON;
  49983. (function (BABYLON) {
  49984. var FilesInput = (function () {
  49985. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49986. this._engine = engine;
  49987. this._currentScene = scene;
  49988. this._sceneLoadedCallback = sceneLoadedCallback;
  49989. this._progressCallback = progressCallback;
  49990. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49991. this._textureLoadingCallback = textureLoadingCallback;
  49992. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49993. this._onReloadCallback = onReloadCallback;
  49994. }
  49995. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49996. var _this = this;
  49997. if (elementToMonitor) {
  49998. this._elementToMonitor = elementToMonitor;
  49999. this._dragEnterHandler = function (e) { _this.drag(e); };
  50000. this._dragOverHandler = function (e) { _this.drag(e); };
  50001. this._dropHandler = function (e) { _this.drop(e); };
  50002. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  50003. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  50004. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  50005. }
  50006. };
  50007. FilesInput.prototype.dispose = function () {
  50008. if (!this._elementToMonitor) {
  50009. return;
  50010. }
  50011. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  50012. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  50013. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  50014. };
  50015. FilesInput.prototype.renderFunction = function () {
  50016. if (this._additionalRenderLoopLogicCallback) {
  50017. this._additionalRenderLoopLogicCallback();
  50018. }
  50019. if (this._currentScene) {
  50020. if (this._textureLoadingCallback) {
  50021. var remaining = this._currentScene.getWaitingItemsCount();
  50022. if (remaining > 0) {
  50023. this._textureLoadingCallback(remaining);
  50024. }
  50025. }
  50026. this._currentScene.render();
  50027. }
  50028. };
  50029. FilesInput.prototype.drag = function (e) {
  50030. e.stopPropagation();
  50031. e.preventDefault();
  50032. };
  50033. FilesInput.prototype.drop = function (eventDrop) {
  50034. eventDrop.stopPropagation();
  50035. eventDrop.preventDefault();
  50036. this.loadFiles(eventDrop);
  50037. };
  50038. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  50039. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  50040. reader.readEntries(function (fileEntries) {
  50041. var remaining = fileEntries.length;
  50042. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  50043. var fileEntry = fileEntries_1[_i];
  50044. if (fileEntry.isFile) {
  50045. fileEntry.file(function (file) {
  50046. file.correctName = relativePath + file.name;
  50047. files.push(file);
  50048. remaining--;
  50049. if (remaining === 0) {
  50050. callback();
  50051. }
  50052. });
  50053. }
  50054. else {
  50055. remaining--;
  50056. if (remaining === 0) {
  50057. callback();
  50058. }
  50059. }
  50060. }
  50061. });
  50062. };
  50063. FilesInput.prototype._processFiles = function (files) {
  50064. for (var i = 0; i < files.length; i++) {
  50065. var name = files[i].correctName.toLowerCase();
  50066. var extension = name.split('.').pop();
  50067. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  50068. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  50069. this._sceneFileToLoad = files[i];
  50070. }
  50071. else {
  50072. FilesInput.FilesToLoad[name] = files[i];
  50073. }
  50074. }
  50075. if (this._onReloadCallback) {
  50076. this._onReloadCallback(this._sceneFileToLoad);
  50077. }
  50078. else {
  50079. this.reload();
  50080. }
  50081. };
  50082. FilesInput.prototype.loadFiles = function (event) {
  50083. var _this = this;
  50084. if (this._startingProcessingFilesCallback)
  50085. this._startingProcessingFilesCallback();
  50086. // Handling data transfer via drag'n'drop
  50087. if (event && event.dataTransfer && event.dataTransfer.files) {
  50088. this._filesToLoad = event.dataTransfer.files;
  50089. }
  50090. // Handling files from input files
  50091. if (event && event.target && event.target.files) {
  50092. this._filesToLoad = event.target.files;
  50093. }
  50094. if (this._filesToLoad && this._filesToLoad.length > 0) {
  50095. var files_1 = [];
  50096. var folders = [];
  50097. var items = event.dataTransfer ? event.dataTransfer.items : null;
  50098. for (var i = 0; i < this._filesToLoad.length; i++) {
  50099. var fileToLoad = this._filesToLoad[i];
  50100. var name_1 = fileToLoad.name.toLowerCase();
  50101. var type = fileToLoad.type;
  50102. var entry = void 0;
  50103. fileToLoad.correctName = name_1;
  50104. if (items) {
  50105. var item = items[i];
  50106. if (item.getAsEntry) {
  50107. entry = item.getAsEntry();
  50108. }
  50109. else if (item.webkitGetAsEntry) {
  50110. entry = item.webkitGetAsEntry();
  50111. }
  50112. }
  50113. if (!entry) {
  50114. files_1.push(fileToLoad);
  50115. }
  50116. else {
  50117. if (entry.isDirectory) {
  50118. folders.push(entry);
  50119. }
  50120. else {
  50121. files_1.push(fileToLoad);
  50122. }
  50123. }
  50124. }
  50125. if (folders.length === 0) {
  50126. this._processFiles(files_1);
  50127. }
  50128. else {
  50129. var remaining = folders.length;
  50130. // Extract folder content
  50131. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  50132. var folder = folders_1[_i];
  50133. this._handleFolderDrop(folder, files_1, function () {
  50134. remaining--;
  50135. if (remaining === 0) {
  50136. _this._processFiles(files_1);
  50137. }
  50138. });
  50139. }
  50140. }
  50141. }
  50142. };
  50143. FilesInput.prototype.reload = function () {
  50144. var _this = this;
  50145. // If a ".babylon" file has been provided
  50146. if (this._sceneFileToLoad) {
  50147. if (this._currentScene) {
  50148. if (BABYLON.Tools.errorsCount > 0) {
  50149. BABYLON.Tools.ClearLogCache();
  50150. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  50151. }
  50152. this._engine.stopRenderLoop();
  50153. this._currentScene.dispose();
  50154. }
  50155. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  50156. _this._currentScene = newScene;
  50157. if (_this._sceneLoadedCallback) {
  50158. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  50159. }
  50160. // Wait for textures and shaders to be ready
  50161. _this._currentScene.executeWhenReady(function () {
  50162. _this._engine.runRenderLoop(function () {
  50163. _this.renderFunction();
  50164. });
  50165. });
  50166. }, function (progress) {
  50167. if (_this._progressCallback) {
  50168. _this._progressCallback(progress);
  50169. }
  50170. });
  50171. }
  50172. else {
  50173. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  50174. }
  50175. };
  50176. FilesInput.FilesToLoad = new Array();
  50177. return FilesInput;
  50178. }());
  50179. BABYLON.FilesInput = FilesInput;
  50180. })(BABYLON || (BABYLON = {}));
  50181. //# sourceMappingURL=babylon.filesInput.js.map
  50182. var BABYLON;
  50183. (function (BABYLON) {
  50184. var FramingBehavior = (function () {
  50185. function FramingBehavior() {
  50186. this._mode = FramingBehavior.FitFrustumSidesMode;
  50187. this._radiusScale = 1.0;
  50188. this._positionScale = 0.5;
  50189. this._defaultElevation = 0.3;
  50190. this._elevationReturnTime = 1500;
  50191. this._elevationReturnWaitTime = 1000;
  50192. this._zoomStopsAnimation = false;
  50193. this._framingTime = 1500;
  50194. this._isPointerDown = false;
  50195. this._lastFrameTime = null;
  50196. this._lastInteractionTime = -Infinity;
  50197. // Framing control
  50198. this._animatables = new Array();
  50199. this._betaIsAnimating = false;
  50200. this._lastFrameRadius = 0;
  50201. }
  50202. Object.defineProperty(FramingBehavior.prototype, "name", {
  50203. get: function () {
  50204. return "Framing";
  50205. },
  50206. enumerable: true,
  50207. configurable: true
  50208. });
  50209. Object.defineProperty(FramingBehavior.prototype, "mode", {
  50210. /**
  50211. * Gets current mode used by the behavior.
  50212. */
  50213. get: function () {
  50214. return this._mode;
  50215. },
  50216. /**
  50217. * Sets the current mode used by the behavior
  50218. */
  50219. set: function (mode) {
  50220. this._mode = mode;
  50221. },
  50222. enumerable: true,
  50223. configurable: true
  50224. });
  50225. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  50226. /**
  50227. * Gets the scale applied to the radius
  50228. */
  50229. get: function () {
  50230. return this._radiusScale;
  50231. },
  50232. /**
  50233. * Sets the scale applied to the radius (1 by default)
  50234. */
  50235. set: function (radius) {
  50236. this._radiusScale = radius;
  50237. },
  50238. enumerable: true,
  50239. configurable: true
  50240. });
  50241. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  50242. /**
  50243. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50244. */
  50245. get: function () {
  50246. return this._positionScale;
  50247. },
  50248. /**
  50249. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50250. */
  50251. set: function (scale) {
  50252. this._positionScale = scale;
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  50258. /**
  50259. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50260. * behaviour is triggered, in radians.
  50261. */
  50262. get: function () {
  50263. return this._defaultElevation;
  50264. },
  50265. /**
  50266. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50267. * behaviour is triggered, in radians.
  50268. */
  50269. set: function (elevation) {
  50270. this._defaultElevation = elevation;
  50271. },
  50272. enumerable: true,
  50273. configurable: true
  50274. });
  50275. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  50276. /**
  50277. * Gets the time (in milliseconds) taken to return to the default beta position.
  50278. * Negative value indicates camera should not return to default.
  50279. */
  50280. get: function () {
  50281. return this._elevationReturnTime;
  50282. },
  50283. /**
  50284. * Sets the time (in milliseconds) taken to return to the default beta position.
  50285. * Negative value indicates camera should not return to default.
  50286. */
  50287. set: function (speed) {
  50288. this._elevationReturnTime = speed;
  50289. },
  50290. enumerable: true,
  50291. configurable: true
  50292. });
  50293. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  50294. /**
  50295. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50296. */
  50297. get: function () {
  50298. return this._elevationReturnWaitTime;
  50299. },
  50300. /**
  50301. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50302. */
  50303. set: function (time) {
  50304. this._elevationReturnWaitTime = time;
  50305. },
  50306. enumerable: true,
  50307. configurable: true
  50308. });
  50309. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  50310. /**
  50311. * Gets the flag that indicates if user zooming should stop animation.
  50312. */
  50313. get: function () {
  50314. return this._zoomStopsAnimation;
  50315. },
  50316. /**
  50317. * Sets the flag that indicates if user zooming should stop animation.
  50318. */
  50319. set: function (flag) {
  50320. this._zoomStopsAnimation = flag;
  50321. },
  50322. enumerable: true,
  50323. configurable: true
  50324. });
  50325. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  50326. /**
  50327. * Gets the transition time when framing the mesh, in milliseconds
  50328. */
  50329. get: function () {
  50330. return this._framingTime;
  50331. },
  50332. /**
  50333. * Sets the transition time when framing the mesh, in milliseconds
  50334. */
  50335. set: function (time) {
  50336. this._framingTime = time;
  50337. },
  50338. enumerable: true,
  50339. configurable: true
  50340. });
  50341. FramingBehavior.prototype.attach = function (camera) {
  50342. var _this = this;
  50343. this._attachedCamera = camera;
  50344. var scene = this._attachedCamera.getScene();
  50345. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  50346. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50347. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50348. _this._isPointerDown = true;
  50349. return;
  50350. }
  50351. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50352. _this._isPointerDown = false;
  50353. }
  50354. });
  50355. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50356. if (mesh) {
  50357. _this.zoomOnMesh(mesh);
  50358. }
  50359. });
  50360. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50361. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50362. _this._applyUserInteraction();
  50363. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  50364. // back to the default position after a given timeout
  50365. _this._maintainCameraAboveGround();
  50366. });
  50367. };
  50368. FramingBehavior.prototype.detach = function () {
  50369. var scene = this._attachedCamera.getScene();
  50370. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50371. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50372. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50373. this._attachedCamera = null;
  50374. };
  50375. /**
  50376. * Targets the given mesh and updates zoom level accordingly.
  50377. * @param mesh The mesh to target.
  50378. * @param radius Optional. If a cached radius position already exists, overrides default.
  50379. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50380. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50381. */
  50382. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  50383. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50384. mesh.computeWorldMatrix(true);
  50385. var boundingBox = mesh.getBoundingInfo().boundingBox;
  50386. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  50387. };
  50388. /**
  50389. * Targets the given mesh and updates zoom level accordingly.
  50390. * @param mesh The mesh to target.
  50391. * @param radius Optional. If a cached radius position already exists, overrides default.
  50392. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50393. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50394. */
  50395. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  50396. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50397. var zoomTarget;
  50398. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  50399. var bottom = minimumWorld.y;
  50400. var top = maximumWorld.y;
  50401. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  50402. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  50403. if (focusOnOriginXZ) {
  50404. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  50405. }
  50406. else {
  50407. var centerWorld = minimumWorld.add(radiusWorld);
  50408. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  50409. }
  50410. if (!this._vectorTransition) {
  50411. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  50412. }
  50413. this._betaIsAnimating = true;
  50414. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  50415. // sets the radius and lower radius bounds
  50416. // Small delta ensures camera is not always at lower zoom limit.
  50417. var delta = 0.1;
  50418. var radius = 0;
  50419. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  50420. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50421. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  50422. radius = position;
  50423. }
  50424. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50425. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50426. if (this._attachedCamera.lowerRadiusLimit === null) {
  50427. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  50428. }
  50429. }
  50430. // transition to new radius
  50431. if (!this._radiusTransition) {
  50432. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50433. }
  50434. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  50435. };
  50436. /**
  50437. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  50438. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  50439. * frustum width.
  50440. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  50441. * to fully enclose the mesh in the viewing frustum.
  50442. */
  50443. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  50444. var size = maximumWorld.subtract(minimumWorld);
  50445. var boxVectorGlobalDiagonal = size.length();
  50446. var frustumSlope = this._getFrustumSlope();
  50447. // Formula for setting distance
  50448. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  50449. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  50450. // Horizon distance
  50451. var radius = radiusWithoutFraming * this._radiusScale;
  50452. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  50453. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  50454. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  50455. var camera = this._attachedCamera;
  50456. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50457. // Don't exceed the requested limit
  50458. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  50459. }
  50460. // Don't exceed the upper radius limit
  50461. if (camera.upperRadiusLimit) {
  50462. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  50463. }
  50464. return distance;
  50465. };
  50466. /**
  50467. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  50468. * is automatically returned to its default position (expected to be above ground plane).
  50469. */
  50470. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  50471. var _this = this;
  50472. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  50473. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  50474. var limitBeta = Math.PI * 0.5;
  50475. // Bring the camera back up if below the ground plane
  50476. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  50477. this._betaIsAnimating = true;
  50478. //Transition to new position
  50479. this.stopAllAnimations();
  50480. if (!this._betaTransition) {
  50481. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50482. }
  50483. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  50484. _this._clearAnimationLocks();
  50485. _this.stopAllAnimations();
  50486. }));
  50487. }
  50488. };
  50489. /**
  50490. * Returns the frustum slope based on the canvas ratio and camera FOV
  50491. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  50492. */
  50493. FramingBehavior.prototype._getFrustumSlope = function () {
  50494. // Calculate the viewport ratio
  50495. // Aspect Ratio is Height/Width.
  50496. var camera = this._attachedCamera;
  50497. var engine = camera.getScene().getEngine();
  50498. var aspectRatio = engine.getAspectRatio(camera);
  50499. // Camera FOV is the vertical field of view (top-bottom) in radians.
  50500. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  50501. var frustumSlopeY = Math.tan(camera.fov / 2);
  50502. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  50503. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  50504. // along the forward vector.
  50505. var frustumSlopeX = frustumSlopeY * aspectRatio;
  50506. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  50507. };
  50508. /**
  50509. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  50510. */
  50511. FramingBehavior.prototype._clearAnimationLocks = function () {
  50512. this._betaIsAnimating = false;
  50513. };
  50514. /**
  50515. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50516. */
  50517. FramingBehavior.prototype._applyUserInteraction = function () {
  50518. if (this.isUserIsMoving) {
  50519. this._lastInteractionTime = BABYLON.Tools.Now;
  50520. this.stopAllAnimations();
  50521. this._clearAnimationLocks();
  50522. }
  50523. };
  50524. /**
  50525. * Stops and removes all animations that have been applied to the camera
  50526. */
  50527. FramingBehavior.prototype.stopAllAnimations = function () {
  50528. this._attachedCamera.animations = [];
  50529. while (this._animatables.length) {
  50530. if (this._animatables[0]) {
  50531. this._animatables[0].onAnimationEnd = null;
  50532. this._animatables[0].stop();
  50533. }
  50534. this._animatables.shift();
  50535. }
  50536. };
  50537. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  50538. /**
  50539. * Gets a value indicating if the user is moving the camera
  50540. */
  50541. get: function () {
  50542. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50543. this._attachedCamera.inertialBetaOffset !== 0 ||
  50544. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50545. this._attachedCamera.inertialPanningX !== 0 ||
  50546. this._attachedCamera.inertialPanningY !== 0 ||
  50547. this._isPointerDown;
  50548. },
  50549. enumerable: true,
  50550. configurable: true
  50551. });
  50552. /**
  50553. * The easing function used by animations
  50554. */
  50555. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  50556. /**
  50557. * The easing mode used by animations
  50558. */
  50559. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  50560. // Statics
  50561. /**
  50562. * The camera can move all the way towards the mesh.
  50563. */
  50564. FramingBehavior.IgnoreBoundsSizeMode = 0;
  50565. /**
  50566. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  50567. */
  50568. FramingBehavior.FitFrustumSidesMode = 1;
  50569. return FramingBehavior;
  50570. }());
  50571. BABYLON.FramingBehavior = FramingBehavior;
  50572. })(BABYLON || (BABYLON = {}));
  50573. //# sourceMappingURL=babylon.framingBehavior.js.map
  50574. var BABYLON;
  50575. (function (BABYLON) {
  50576. /**
  50577. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  50578. */
  50579. var BouncingBehavior = (function () {
  50580. function BouncingBehavior() {
  50581. /**
  50582. * The duration of the animation, in milliseconds
  50583. */
  50584. this.transitionDuration = 450;
  50585. /**
  50586. * Length of the distance animated by the transition when lower radius is reached
  50587. */
  50588. this.lowerRadiusTransitionRange = 2;
  50589. /**
  50590. * Length of the distance animated by the transition when upper radius is reached
  50591. */
  50592. this.upperRadiusTransitionRange = -2;
  50593. this._autoTransitionRange = false;
  50594. // Animations
  50595. this._radiusIsAnimating = false;
  50596. this._radiusBounceTransition = null;
  50597. this._animatables = new Array();
  50598. }
  50599. Object.defineProperty(BouncingBehavior.prototype, "name", {
  50600. get: function () {
  50601. return "Bouncing";
  50602. },
  50603. enumerable: true,
  50604. configurable: true
  50605. });
  50606. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  50607. /**
  50608. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50609. */
  50610. get: function () {
  50611. return this._autoTransitionRange;
  50612. },
  50613. /**
  50614. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50615. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  50616. */
  50617. set: function (value) {
  50618. var _this = this;
  50619. if (this._autoTransitionRange === value) {
  50620. return;
  50621. }
  50622. this._autoTransitionRange = value;
  50623. var camera = this._attachedCamera;
  50624. if (value) {
  50625. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50626. if (!mesh) {
  50627. return;
  50628. }
  50629. mesh.computeWorldMatrix(true);
  50630. var diagonal = mesh.getBoundingInfo().diagonalLength;
  50631. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  50632. _this.upperRadiusTransitionRange = diagonal * 0.05;
  50633. });
  50634. }
  50635. else if (this._onMeshTargetChangedObserver) {
  50636. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50637. }
  50638. },
  50639. enumerable: true,
  50640. configurable: true
  50641. });
  50642. BouncingBehavior.prototype.attach = function (camera) {
  50643. var _this = this;
  50644. this._attachedCamera = camera;
  50645. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50646. // Add the bounce animation to the lower radius limit
  50647. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  50648. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  50649. }
  50650. // Add the bounce animation to the upper radius limit
  50651. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  50652. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  50653. }
  50654. });
  50655. };
  50656. BouncingBehavior.prototype.detach = function () {
  50657. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50658. if (this._onMeshTargetChangedObserver) {
  50659. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50660. }
  50661. this._attachedCamera = null;
  50662. };
  50663. /**
  50664. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  50665. * @param radiusLimit The limit to check against.
  50666. * @return Bool to indicate if at limit.
  50667. */
  50668. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  50669. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  50670. return true;
  50671. }
  50672. return false;
  50673. };
  50674. /**
  50675. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  50676. * @param radiusDelta The delta by which to animate to. Can be negative.
  50677. */
  50678. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  50679. var _this = this;
  50680. if (!this._radiusBounceTransition) {
  50681. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  50682. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  50683. }
  50684. // Prevent zoom until bounce has completed
  50685. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  50686. this._attachedCamera.wheelPrecision = Infinity;
  50687. this._attachedCamera.inertialRadiusOffset = 0;
  50688. // Animate to the radius limit
  50689. this.stopAllAnimations();
  50690. this._radiusIsAnimating = true;
  50691. 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(); }));
  50692. };
  50693. /**
  50694. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  50695. */
  50696. BouncingBehavior.prototype._clearAnimationLocks = function () {
  50697. this._radiusIsAnimating = false;
  50698. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  50699. };
  50700. /**
  50701. * Stops and removes all animations that have been applied to the camera
  50702. */
  50703. BouncingBehavior.prototype.stopAllAnimations = function () {
  50704. this._attachedCamera.animations = [];
  50705. while (this._animatables.length) {
  50706. this._animatables[0].onAnimationEnd = null;
  50707. this._animatables[0].stop();
  50708. this._animatables.shift();
  50709. }
  50710. };
  50711. /**
  50712. * The easing function used by animations
  50713. */
  50714. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  50715. /**
  50716. * The easing mode used by animations
  50717. */
  50718. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  50719. return BouncingBehavior;
  50720. }());
  50721. BABYLON.BouncingBehavior = BouncingBehavior;
  50722. })(BABYLON || (BABYLON = {}));
  50723. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  50724. var BABYLON;
  50725. (function (BABYLON) {
  50726. var AutoRotationBehavior = (function () {
  50727. function AutoRotationBehavior() {
  50728. this._zoomStopsAnimation = false;
  50729. this._idleRotationSpeed = 0.05;
  50730. this._idleRotationWaitTime = 2000;
  50731. this._idleRotationSpinupTime = 2000;
  50732. this._isPointerDown = false;
  50733. this._lastFrameTime = null;
  50734. this._lastInteractionTime = -Infinity;
  50735. this._cameraRotationSpeed = 0;
  50736. this._lastFrameRadius = 0;
  50737. }
  50738. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  50739. get: function () {
  50740. return "AutoRotation";
  50741. },
  50742. enumerable: true,
  50743. configurable: true
  50744. });
  50745. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  50746. /**
  50747. * Gets the flag that indicates if user zooming should stop animation.
  50748. */
  50749. get: function () {
  50750. return this._zoomStopsAnimation;
  50751. },
  50752. /**
  50753. * Sets the flag that indicates if user zooming should stop animation.
  50754. */
  50755. set: function (flag) {
  50756. this._zoomStopsAnimation = flag;
  50757. },
  50758. enumerable: true,
  50759. configurable: true
  50760. });
  50761. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  50762. /**
  50763. * Gets the default speed at which the camera rotates around the model.
  50764. */
  50765. get: function () {
  50766. return this._idleRotationSpeed;
  50767. },
  50768. /**
  50769. * Sets the default speed at which the camera rotates around the model.
  50770. */
  50771. set: function (speed) {
  50772. this._idleRotationSpeed = speed;
  50773. },
  50774. enumerable: true,
  50775. configurable: true
  50776. });
  50777. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50778. /**
  50779. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50780. */
  50781. get: function () {
  50782. return this._idleRotationWaitTime;
  50783. },
  50784. /**
  50785. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50786. */
  50787. set: function (time) {
  50788. this._idleRotationWaitTime = time;
  50789. },
  50790. enumerable: true,
  50791. configurable: true
  50792. });
  50793. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50794. /**
  50795. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50796. */
  50797. get: function () {
  50798. return this._idleRotationSpinupTime;
  50799. },
  50800. /**
  50801. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50802. */
  50803. set: function (time) {
  50804. this._idleRotationSpinupTime = time;
  50805. },
  50806. enumerable: true,
  50807. configurable: true
  50808. });
  50809. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  50810. /**
  50811. * Gets a value indicating if the camera is currently rotating because of this behavior
  50812. */
  50813. get: function () {
  50814. return Math.abs(this._cameraRotationSpeed) > 0;
  50815. },
  50816. enumerable: true,
  50817. configurable: true
  50818. });
  50819. AutoRotationBehavior.prototype.attach = function (camera) {
  50820. var _this = this;
  50821. this._attachedCamera = camera;
  50822. var scene = this._attachedCamera.getScene();
  50823. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50824. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50825. _this._isPointerDown = true;
  50826. return;
  50827. }
  50828. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50829. _this._isPointerDown = false;
  50830. }
  50831. });
  50832. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50833. var now = BABYLON.Tools.Now;
  50834. var dt = 0;
  50835. if (_this._lastFrameTime != null) {
  50836. dt = now - _this._lastFrameTime;
  50837. }
  50838. _this._lastFrameTime = now;
  50839. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50840. _this._applyUserInteraction();
  50841. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50842. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50843. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50844. // Step camera rotation by rotation speed
  50845. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  50846. });
  50847. };
  50848. AutoRotationBehavior.prototype.detach = function () {
  50849. var scene = this._attachedCamera.getScene();
  50850. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50851. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50852. this._attachedCamera = null;
  50853. };
  50854. /**
  50855. * Returns true if user is scrolling.
  50856. * @return true if user is scrolling.
  50857. */
  50858. AutoRotationBehavior.prototype._userIsZooming = function () {
  50859. return this._attachedCamera.inertialRadiusOffset !== 0;
  50860. };
  50861. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50862. var zoomHasHitLimit = false;
  50863. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50864. zoomHasHitLimit = true;
  50865. }
  50866. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50867. this._lastFrameRadius = this._attachedCamera.radius;
  50868. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50869. };
  50870. /**
  50871. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50872. */
  50873. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50874. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50875. this._lastInteractionTime = BABYLON.Tools.Now;
  50876. }
  50877. };
  50878. // Tools
  50879. AutoRotationBehavior.prototype._userIsMoving = function () {
  50880. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50881. this._attachedCamera.inertialBetaOffset !== 0 ||
  50882. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50883. this._attachedCamera.inertialPanningX !== 0 ||
  50884. this._attachedCamera.inertialPanningY !== 0 ||
  50885. this._isPointerDown;
  50886. };
  50887. return AutoRotationBehavior;
  50888. }());
  50889. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  50890. })(BABYLON || (BABYLON = {}));
  50891. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  50892. var BABYLON;
  50893. (function (BABYLON) {
  50894. var MorphTarget = (function () {
  50895. function MorphTarget(name, influence) {
  50896. if (influence === void 0) { influence = 0; }
  50897. this.name = name;
  50898. this.animations = new Array();
  50899. this.onInfluenceChanged = new BABYLON.Observable();
  50900. this.influence = influence;
  50901. }
  50902. Object.defineProperty(MorphTarget.prototype, "influence", {
  50903. get: function () {
  50904. return this._influence;
  50905. },
  50906. set: function (influence) {
  50907. if (this._influence === influence) {
  50908. return;
  50909. }
  50910. var previous = this._influence;
  50911. this._influence = influence;
  50912. if (this.onInfluenceChanged.hasObservers) {
  50913. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  50914. }
  50915. },
  50916. enumerable: true,
  50917. configurable: true
  50918. });
  50919. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  50920. get: function () {
  50921. return this._normals !== undefined;
  50922. },
  50923. enumerable: true,
  50924. configurable: true
  50925. });
  50926. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  50927. get: function () {
  50928. return this._tangents !== undefined;
  50929. },
  50930. enumerable: true,
  50931. configurable: true
  50932. });
  50933. MorphTarget.prototype.setPositions = function (data) {
  50934. this._positions = new Float32Array(data);
  50935. };
  50936. MorphTarget.prototype.getPositions = function () {
  50937. return this._positions;
  50938. };
  50939. MorphTarget.prototype.setNormals = function (data) {
  50940. this._normals = new Float32Array(data);
  50941. };
  50942. MorphTarget.prototype.getNormals = function () {
  50943. return this._normals;
  50944. };
  50945. MorphTarget.prototype.setTangents = function (data) {
  50946. this._tangents = new Float32Array(data);
  50947. };
  50948. MorphTarget.prototype.getTangents = function () {
  50949. return this._tangents;
  50950. };
  50951. /**
  50952. * Serializes the current target into a Serialization object.
  50953. * Returns the serialized object.
  50954. */
  50955. MorphTarget.prototype.serialize = function () {
  50956. var serializationObject = {};
  50957. serializationObject.name = this.name;
  50958. serializationObject.influence = this.influence;
  50959. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  50960. if (this.hasNormals) {
  50961. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  50962. }
  50963. if (this.hasTangents) {
  50964. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  50965. }
  50966. return serializationObject;
  50967. };
  50968. // Statics
  50969. MorphTarget.Parse = function (serializationObject) {
  50970. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  50971. result.setPositions(serializationObject.positions);
  50972. if (serializationObject.normals) {
  50973. result.setNormals(serializationObject.normals);
  50974. }
  50975. if (serializationObject.tangents) {
  50976. result.setTangents(serializationObject.tangents);
  50977. }
  50978. return result;
  50979. };
  50980. MorphTarget.FromMesh = function (mesh, name, influence) {
  50981. if (!name) {
  50982. name = mesh.name;
  50983. }
  50984. var result = new MorphTarget(name, influence);
  50985. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  50986. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50987. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  50988. }
  50989. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  50990. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  50991. }
  50992. return result;
  50993. };
  50994. return MorphTarget;
  50995. }());
  50996. BABYLON.MorphTarget = MorphTarget;
  50997. })(BABYLON || (BABYLON = {}));
  50998. //# sourceMappingURL=babylon.morphTarget.js.map
  50999. var BABYLON;
  51000. (function (BABYLON) {
  51001. var MorphTargetManager = (function () {
  51002. function MorphTargetManager(scene) {
  51003. this._targets = new Array();
  51004. this._targetObservable = new Array();
  51005. this._activeTargets = new BABYLON.SmartArray(16);
  51006. this._supportsNormals = false;
  51007. this._supportsTangents = false;
  51008. this._vertexCount = 0;
  51009. this._uniqueId = 0;
  51010. this._tempInfluences = new Array();
  51011. if (!scene) {
  51012. scene = BABYLON.Engine.LastCreatedScene;
  51013. }
  51014. this._scene = scene;
  51015. this._scene.morphTargetManagers.push(this);
  51016. this._uniqueId = scene.getUniqueId();
  51017. }
  51018. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  51019. get: function () {
  51020. return this._uniqueId;
  51021. },
  51022. enumerable: true,
  51023. configurable: true
  51024. });
  51025. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  51026. get: function () {
  51027. return this._vertexCount;
  51028. },
  51029. enumerable: true,
  51030. configurable: true
  51031. });
  51032. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  51033. get: function () {
  51034. return this._supportsNormals;
  51035. },
  51036. enumerable: true,
  51037. configurable: true
  51038. });
  51039. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  51040. get: function () {
  51041. return this._supportsTangents;
  51042. },
  51043. enumerable: true,
  51044. configurable: true
  51045. });
  51046. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  51047. get: function () {
  51048. return this._targets.length;
  51049. },
  51050. enumerable: true,
  51051. configurable: true
  51052. });
  51053. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  51054. get: function () {
  51055. return this._activeTargets.length;
  51056. },
  51057. enumerable: true,
  51058. configurable: true
  51059. });
  51060. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  51061. get: function () {
  51062. return this._influences;
  51063. },
  51064. enumerable: true,
  51065. configurable: true
  51066. });
  51067. MorphTargetManager.prototype.getActiveTarget = function (index) {
  51068. return this._activeTargets.data[index];
  51069. };
  51070. MorphTargetManager.prototype.getTarget = function (index) {
  51071. return this._targets[index];
  51072. };
  51073. MorphTargetManager.prototype.addTarget = function (target) {
  51074. var _this = this;
  51075. if (this._vertexCount) {
  51076. if (this._vertexCount !== target.getPositions().length / 3) {
  51077. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  51078. return;
  51079. }
  51080. }
  51081. this._targets.push(target);
  51082. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  51083. _this._syncActiveTargets(needUpdate);
  51084. }));
  51085. this._syncActiveTargets(true);
  51086. };
  51087. MorphTargetManager.prototype.removeTarget = function (target) {
  51088. var index = this._targets.indexOf(target);
  51089. if (index >= 0) {
  51090. this._targets.splice(index, 1);
  51091. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  51092. this._vertexCount = 0;
  51093. this._syncActiveTargets(true);
  51094. }
  51095. };
  51096. /**
  51097. * Serializes the current manager into a Serialization object.
  51098. * Returns the serialized object.
  51099. */
  51100. MorphTargetManager.prototype.serialize = function () {
  51101. var serializationObject = {};
  51102. serializationObject.id = this.uniqueId;
  51103. serializationObject.targets = [];
  51104. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51105. var target = _a[_i];
  51106. serializationObject.targets.push(target.serialize());
  51107. }
  51108. return serializationObject;
  51109. };
  51110. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  51111. this._syncActiveTargets(needUpdate);
  51112. };
  51113. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  51114. var influenceCount = 0;
  51115. this._activeTargets.reset();
  51116. this._supportsNormals = true;
  51117. this._supportsTangents = true;
  51118. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51119. var target = _a[_i];
  51120. if (target.influence > 0) {
  51121. this._activeTargets.push(target);
  51122. this._tempInfluences[influenceCount++] = target.influence;
  51123. this._supportsNormals = this._supportsNormals && target.hasNormals;
  51124. this._supportsTangents = this._supportsTangents && target.hasTangents;
  51125. if (this._vertexCount === 0) {
  51126. this._vertexCount = target.getPositions().length / 3;
  51127. }
  51128. }
  51129. }
  51130. if (!this._influences || this._influences.length !== influenceCount) {
  51131. this._influences = new Float32Array(influenceCount);
  51132. }
  51133. for (var index = 0; index < influenceCount; index++) {
  51134. this._influences[index] = this._tempInfluences[index];
  51135. }
  51136. if (needUpdate) {
  51137. // Flag meshes as dirty to resync with the active targets
  51138. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  51139. var mesh = _c[_b];
  51140. if (mesh.morphTargetManager === this) {
  51141. mesh._syncGeometryWithMorphTargetManager();
  51142. }
  51143. }
  51144. }
  51145. };
  51146. // Statics
  51147. MorphTargetManager.Parse = function (serializationObject, scene) {
  51148. var result = new MorphTargetManager(scene);
  51149. result._uniqueId = serializationObject.id;
  51150. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  51151. var targetData = _a[_i];
  51152. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  51153. }
  51154. return result;
  51155. };
  51156. return MorphTargetManager;
  51157. }());
  51158. BABYLON.MorphTargetManager = MorphTargetManager;
  51159. })(BABYLON || (BABYLON = {}));
  51160. //# sourceMappingURL=babylon.morphTargetManager.js.map
  51161. 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}"};
  51162. 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};"};
  51163. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51164. var BABYLON;
  51165. (function (BABYLON) {
  51166. var GridMaterialDefines = (function (_super) {
  51167. __extends(GridMaterialDefines, _super);
  51168. function GridMaterialDefines() {
  51169. var _this = _super.call(this) || this;
  51170. _this.TRANSPARENT = false;
  51171. _this.FOG = false;
  51172. _this.PREMULTIPLYALPHA = false;
  51173. _this.rebuild();
  51174. return _this;
  51175. }
  51176. return GridMaterialDefines;
  51177. }(BABYLON.MaterialDefines));
  51178. /**
  51179. * The grid materials allows you to wrap any shape with a grid.
  51180. * Colors are customizable.
  51181. */
  51182. var GridMaterial = (function (_super) {
  51183. __extends(GridMaterial, _super);
  51184. /**
  51185. * constructor
  51186. * @param name The name given to the material in order to identify it afterwards.
  51187. * @param scene The scene the material is used in.
  51188. */
  51189. function GridMaterial(name, scene) {
  51190. var _this = _super.call(this, name, scene) || this;
  51191. /**
  51192. * Main color of the grid (e.g. between lines)
  51193. */
  51194. _this.mainColor = BABYLON.Color3.Black();
  51195. /**
  51196. * Color of the grid lines.
  51197. */
  51198. _this.lineColor = BABYLON.Color3.Teal();
  51199. /**
  51200. * The scale of the grid compared to unit.
  51201. */
  51202. _this.gridRatio = 1.0;
  51203. /**
  51204. * The frequency of thicker lines.
  51205. */
  51206. _this.majorUnitFrequency = 10;
  51207. /**
  51208. * The visibility of minor units in the grid.
  51209. */
  51210. _this.minorUnitVisibility = 0.33;
  51211. /**
  51212. * The grid opacity outside of the lines.
  51213. */
  51214. _this.opacity = 1.0;
  51215. /**
  51216. * Determine RBG output is premultiplied by alpha value.
  51217. */
  51218. _this.preMultiplyAlpha = false;
  51219. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  51220. return _this;
  51221. }
  51222. /**
  51223. * Returns wehter or not the grid requires alpha blending.
  51224. */
  51225. GridMaterial.prototype.needAlphaBlending = function () {
  51226. return this.opacity < 1.0;
  51227. };
  51228. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  51229. if (this.isFrozen) {
  51230. if (this._wasPreviouslyReady && subMesh.effect) {
  51231. return true;
  51232. }
  51233. }
  51234. if (!subMesh._materialDefines) {
  51235. subMesh._materialDefines = new GridMaterialDefines();
  51236. }
  51237. var defines = subMesh._materialDefines;
  51238. var scene = this.getScene();
  51239. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  51240. if (this._renderId === scene.getRenderId()) {
  51241. return true;
  51242. }
  51243. }
  51244. var engine = scene.getEngine();
  51245. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  51246. defines.TRANSPARENT = !defines.TRANSPARENT;
  51247. defines.markAsUnprocessed();
  51248. }
  51249. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  51250. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  51251. defines.markAsUnprocessed();
  51252. }
  51253. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  51254. // Get correct effect
  51255. if (defines.isDirty) {
  51256. defines.markAsProcessed();
  51257. scene.resetCachedMaterial();
  51258. // Attributes
  51259. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51260. // Defines
  51261. var join = defines.toString();
  51262. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  51263. }
  51264. if (!subMesh.effect.isReady()) {
  51265. return false;
  51266. }
  51267. this._renderId = scene.getRenderId();
  51268. this._wasPreviouslyReady = true;
  51269. return true;
  51270. };
  51271. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  51272. var scene = this.getScene();
  51273. var defines = subMesh._materialDefines;
  51274. if (!defines) {
  51275. return;
  51276. }
  51277. var effect = subMesh.effect;
  51278. this._activeEffect = effect;
  51279. // Matrices
  51280. this.bindOnlyWorldMatrix(world);
  51281. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  51282. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  51283. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  51284. // Uniforms
  51285. if (this._mustRebind(scene, effect)) {
  51286. this._activeEffect.setColor3("mainColor", this.mainColor);
  51287. this._activeEffect.setColor3("lineColor", this.lineColor);
  51288. this._gridControl.x = this.gridRatio;
  51289. this._gridControl.y = Math.round(this.majorUnitFrequency);
  51290. this._gridControl.z = this.minorUnitVisibility;
  51291. this._gridControl.w = this.opacity;
  51292. this._activeEffect.setVector4("gridControl", this._gridControl);
  51293. }
  51294. // Fog
  51295. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  51296. this._afterBind(mesh, this._activeEffect);
  51297. };
  51298. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  51299. _super.prototype.dispose.call(this, forceDisposeEffect);
  51300. };
  51301. GridMaterial.prototype.clone = function (name) {
  51302. var _this = this;
  51303. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  51304. };
  51305. GridMaterial.prototype.serialize = function () {
  51306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51307. serializationObject.customType = "BABYLON.GridMaterial";
  51308. return serializationObject;
  51309. };
  51310. GridMaterial.prototype.getClassName = function () {
  51311. return "GridMaterial";
  51312. };
  51313. GridMaterial.Parse = function (source, scene, rootUrl) {
  51314. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  51315. };
  51316. __decorate([
  51317. BABYLON.serializeAsColor3()
  51318. ], GridMaterial.prototype, "mainColor", void 0);
  51319. __decorate([
  51320. BABYLON.serializeAsColor3()
  51321. ], GridMaterial.prototype, "lineColor", void 0);
  51322. __decorate([
  51323. BABYLON.serialize()
  51324. ], GridMaterial.prototype, "gridRatio", void 0);
  51325. __decorate([
  51326. BABYLON.serialize()
  51327. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  51328. __decorate([
  51329. BABYLON.serialize()
  51330. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  51331. __decorate([
  51332. BABYLON.serialize()
  51333. ], GridMaterial.prototype, "opacity", void 0);
  51334. __decorate([
  51335. BABYLON.serialize()
  51336. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  51337. return GridMaterial;
  51338. }(BABYLON.PushMaterial));
  51339. BABYLON.GridMaterial = GridMaterial;
  51340. })(BABYLON || (BABYLON = {}));
  51341. //# sourceMappingURL=babylon.gridmaterial.js.map
  51342. 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}";
  51343. 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}";
  51344. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51345. var BABYLON;
  51346. (function (BABYLON) {
  51347. var GLTFLoaderCoordinateSystemMode;
  51348. (function (GLTFLoaderCoordinateSystemMode) {
  51349. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  51350. // 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.
  51351. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  51352. // The glTF right-handed data is not transformed in any form and is loaded directly.
  51353. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  51354. // Sets the useRightHandedSystem flag on the scene.
  51355. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  51356. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  51357. var GLTFFileLoader = (function () {
  51358. function GLTFFileLoader() {
  51359. // V2 options
  51360. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51361. this.name = "gltf";
  51362. this.extensions = {
  51363. ".gltf": { isBinary: false },
  51364. ".glb": { isBinary: true }
  51365. };
  51366. }
  51367. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  51368. var loaderData = GLTFFileLoader._parse(data, onError);
  51369. if (!loaderData) {
  51370. return;
  51371. }
  51372. var loader = this._getLoader(loaderData, onError);
  51373. if (!loader) {
  51374. return;
  51375. }
  51376. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51377. };
  51378. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  51379. var loaderData = GLTFFileLoader._parse(data, onError);
  51380. if (!loaderData) {
  51381. return;
  51382. }
  51383. var loader = this._getLoader(loaderData, onError);
  51384. if (!loader) {
  51385. return;
  51386. }
  51387. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51388. };
  51389. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  51390. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  51391. };
  51392. GLTFFileLoader._parse = function (data, onError) {
  51393. if (data instanceof ArrayBuffer) {
  51394. return GLTFFileLoader._parseBinary(data, onError);
  51395. }
  51396. try {
  51397. return {
  51398. json: JSON.parse(data),
  51399. bin: null
  51400. };
  51401. }
  51402. catch (e) {
  51403. onError(e.message);
  51404. return null;
  51405. }
  51406. };
  51407. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  51408. var loaderVersion = { major: 2, minor: 0 };
  51409. var asset = loaderData.json.asset || {};
  51410. var version = GLTFFileLoader._parseVersion(asset.version);
  51411. if (!version) {
  51412. onError("Invalid version: " + asset.version);
  51413. return null;
  51414. }
  51415. if (asset.minVersion !== undefined) {
  51416. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  51417. if (!minVersion) {
  51418. onError("Invalid minimum version: " + asset.minVersion);
  51419. return null;
  51420. }
  51421. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  51422. onError("Incompatible minimum version: " + asset.minVersion);
  51423. return null;
  51424. }
  51425. }
  51426. var createLoaders = {
  51427. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  51428. 2: GLTFFileLoader.CreateGLTFLoaderV2
  51429. };
  51430. var createLoader = createLoaders[version.major];
  51431. if (!createLoader) {
  51432. onError("Unsupported version: " + asset.version);
  51433. return null;
  51434. }
  51435. return createLoader(this);
  51436. };
  51437. GLTFFileLoader._parseBinary = function (data, onError) {
  51438. var Binary = {
  51439. Magic: 0x46546C67
  51440. };
  51441. var binaryReader = new BinaryReader(data);
  51442. var magic = binaryReader.readUint32();
  51443. if (magic !== Binary.Magic) {
  51444. onError("Unexpected magic: " + magic);
  51445. return null;
  51446. }
  51447. var version = binaryReader.readUint32();
  51448. switch (version) {
  51449. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  51450. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  51451. }
  51452. onError("Unsupported version: " + version);
  51453. return null;
  51454. };
  51455. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  51456. var ContentFormat = {
  51457. JSON: 0
  51458. };
  51459. var length = binaryReader.readUint32();
  51460. if (length != binaryReader.getLength()) {
  51461. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51462. return null;
  51463. }
  51464. var contentLength = binaryReader.readUint32();
  51465. var contentFormat = binaryReader.readUint32();
  51466. var content;
  51467. switch (contentFormat) {
  51468. case ContentFormat.JSON:
  51469. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  51470. break;
  51471. default:
  51472. onError("Unexpected content format: " + contentFormat);
  51473. return null;
  51474. }
  51475. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  51476. var body = binaryReader.readUint8Array(bytesRemaining);
  51477. return {
  51478. json: content,
  51479. bin: body
  51480. };
  51481. };
  51482. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  51483. var ChunkFormat = {
  51484. JSON: 0x4E4F534A,
  51485. BIN: 0x004E4942
  51486. };
  51487. var length = binaryReader.readUint32();
  51488. if (length !== binaryReader.getLength()) {
  51489. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51490. return null;
  51491. }
  51492. // JSON chunk
  51493. var chunkLength = binaryReader.readUint32();
  51494. var chunkFormat = binaryReader.readUint32();
  51495. if (chunkFormat !== ChunkFormat.JSON) {
  51496. onError("First chunk format is not JSON");
  51497. return null;
  51498. }
  51499. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  51500. // Look for BIN chunk
  51501. var bin = null;
  51502. while (binaryReader.getPosition() < binaryReader.getLength()) {
  51503. chunkLength = binaryReader.readUint32();
  51504. chunkFormat = binaryReader.readUint32();
  51505. switch (chunkFormat) {
  51506. case ChunkFormat.JSON:
  51507. onError("Unexpected JSON chunk");
  51508. return null;
  51509. case ChunkFormat.BIN:
  51510. bin = binaryReader.readUint8Array(chunkLength);
  51511. break;
  51512. default:
  51513. // ignore unrecognized chunkFormat
  51514. binaryReader.skipBytes(chunkLength);
  51515. break;
  51516. }
  51517. }
  51518. return {
  51519. json: json,
  51520. bin: bin
  51521. };
  51522. };
  51523. GLTFFileLoader._parseVersion = function (version) {
  51524. if (!version) {
  51525. return null;
  51526. }
  51527. var parts = version.split(".");
  51528. if (parts.length != 2) {
  51529. return null;
  51530. }
  51531. var major = +parts[0];
  51532. if (isNaN(major)) {
  51533. return null;
  51534. }
  51535. var minor = +parts[1];
  51536. if (isNaN(minor)) {
  51537. return null;
  51538. }
  51539. return {
  51540. major: major,
  51541. minor: minor
  51542. };
  51543. };
  51544. GLTFFileLoader._compareVersion = function (a, b) {
  51545. if (a.major > b.major)
  51546. return 1;
  51547. if (a.major < b.major)
  51548. return -1;
  51549. if (a.minor > b.minor)
  51550. return 1;
  51551. if (a.minor < b.minor)
  51552. return -1;
  51553. return 0;
  51554. };
  51555. GLTFFileLoader._decodeBufferToText = function (view) {
  51556. var result = "";
  51557. var length = view.byteLength;
  51558. for (var i = 0; i < length; ++i) {
  51559. result += String.fromCharCode(view[i]);
  51560. }
  51561. return result;
  51562. };
  51563. // V1 options
  51564. GLTFFileLoader.HomogeneousCoordinates = false;
  51565. GLTFFileLoader.IncrementalLoading = true;
  51566. return GLTFFileLoader;
  51567. }());
  51568. BABYLON.GLTFFileLoader = GLTFFileLoader;
  51569. var BinaryReader = (function () {
  51570. function BinaryReader(arrayBuffer) {
  51571. this._arrayBuffer = arrayBuffer;
  51572. this._dataView = new DataView(arrayBuffer);
  51573. this._byteOffset = 0;
  51574. }
  51575. BinaryReader.prototype.getPosition = function () {
  51576. return this._byteOffset;
  51577. };
  51578. BinaryReader.prototype.getLength = function () {
  51579. return this._arrayBuffer.byteLength;
  51580. };
  51581. BinaryReader.prototype.readUint32 = function () {
  51582. var value = this._dataView.getUint32(this._byteOffset, true);
  51583. this._byteOffset += 4;
  51584. return value;
  51585. };
  51586. BinaryReader.prototype.readUint8Array = function (length) {
  51587. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  51588. this._byteOffset += length;
  51589. return value;
  51590. };
  51591. BinaryReader.prototype.skipBytes = function (length) {
  51592. this._byteOffset += length;
  51593. };
  51594. return BinaryReader;
  51595. }());
  51596. if (BABYLON.SceneLoader) {
  51597. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  51598. }
  51599. })(BABYLON || (BABYLON = {}));
  51600. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  51601. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51602. var BABYLON;
  51603. (function (BABYLON) {
  51604. var GLTF1;
  51605. (function (GLTF1) {
  51606. /**
  51607. * Enums
  51608. */
  51609. var EComponentType;
  51610. (function (EComponentType) {
  51611. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  51612. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51613. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  51614. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51615. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  51616. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  51617. var EShaderType;
  51618. (function (EShaderType) {
  51619. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  51620. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  51621. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  51622. var EParameterType;
  51623. (function (EParameterType) {
  51624. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  51625. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51626. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  51627. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51628. EParameterType[EParameterType["INT"] = 5124] = "INT";
  51629. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  51630. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  51631. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  51632. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  51633. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  51634. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  51635. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  51636. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  51637. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  51638. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  51639. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  51640. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  51641. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  51642. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  51643. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  51644. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  51645. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  51646. var ETextureWrapMode;
  51647. (function (ETextureWrapMode) {
  51648. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  51649. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  51650. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  51651. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  51652. var ETextureFilterType;
  51653. (function (ETextureFilterType) {
  51654. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  51655. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  51656. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  51657. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  51658. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  51659. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  51660. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  51661. var ETextureFormat;
  51662. (function (ETextureFormat) {
  51663. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  51664. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  51665. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  51666. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  51667. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  51668. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  51669. var ECullingType;
  51670. (function (ECullingType) {
  51671. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  51672. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  51673. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  51674. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  51675. var EBlendingFunction;
  51676. (function (EBlendingFunction) {
  51677. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  51678. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  51679. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  51680. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  51681. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  51682. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  51683. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  51684. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  51685. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  51686. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  51687. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  51688. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  51689. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  51690. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  51691. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  51692. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  51693. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  51694. })(BABYLON || (BABYLON = {}));
  51695. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  51696. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51697. var BABYLON;
  51698. (function (BABYLON) {
  51699. var GLTF1;
  51700. (function (GLTF1) {
  51701. /**
  51702. * Tokenizer. Used for shaders compatibility
  51703. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  51704. */
  51705. var ETokenType;
  51706. (function (ETokenType) {
  51707. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  51708. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  51709. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  51710. })(ETokenType || (ETokenType = {}));
  51711. var Tokenizer = (function () {
  51712. function Tokenizer(toParse) {
  51713. this._pos = 0;
  51714. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  51715. this._toParse = toParse;
  51716. this._maxPos = toParse.length;
  51717. }
  51718. Tokenizer.prototype.getNextToken = function () {
  51719. if (this.isEnd())
  51720. return ETokenType.END_OF_INPUT;
  51721. this.currentString = this.read();
  51722. this.currentToken = ETokenType.UNKNOWN;
  51723. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  51724. this.currentToken = ETokenType.IDENTIFIER;
  51725. this.currentIdentifier = this.currentString;
  51726. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  51727. this.currentIdentifier += this.currentString;
  51728. this.forward();
  51729. }
  51730. }
  51731. return this.currentToken;
  51732. };
  51733. Tokenizer.prototype.peek = function () {
  51734. return this._toParse[this._pos];
  51735. };
  51736. Tokenizer.prototype.read = function () {
  51737. return this._toParse[this._pos++];
  51738. };
  51739. Tokenizer.prototype.forward = function () {
  51740. this._pos++;
  51741. };
  51742. Tokenizer.prototype.isEnd = function () {
  51743. return this._pos >= this._maxPos;
  51744. };
  51745. return Tokenizer;
  51746. }());
  51747. /**
  51748. * Values
  51749. */
  51750. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  51751. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  51752. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  51753. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  51754. /**
  51755. * Parse
  51756. */
  51757. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  51758. for (var buf in parsedBuffers) {
  51759. var parsedBuffer = parsedBuffers[buf];
  51760. gltfRuntime.buffers[buf] = parsedBuffer;
  51761. gltfRuntime.buffersCount++;
  51762. }
  51763. };
  51764. var parseShaders = function (parsedShaders, gltfRuntime) {
  51765. for (var sha in parsedShaders) {
  51766. var parsedShader = parsedShaders[sha];
  51767. gltfRuntime.shaders[sha] = parsedShader;
  51768. gltfRuntime.shaderscount++;
  51769. }
  51770. };
  51771. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  51772. for (var object in parsedObjects) {
  51773. var parsedObject = parsedObjects[object];
  51774. gltfRuntime[runtimeProperty][object] = parsedObject;
  51775. }
  51776. };
  51777. /**
  51778. * Utils
  51779. */
  51780. var normalizeUVs = function (buffer) {
  51781. if (!buffer) {
  51782. return;
  51783. }
  51784. for (var i = 0; i < buffer.length / 2; i++) {
  51785. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51786. }
  51787. };
  51788. var replaceInString = function (str, searchValue, replaceValue) {
  51789. while (str.indexOf(searchValue) !== -1) {
  51790. str = str.replace(searchValue, replaceValue);
  51791. }
  51792. return str;
  51793. };
  51794. var getAttribute = function (attributeParameter) {
  51795. if (attributeParameter.semantic === "NORMAL") {
  51796. return "normal";
  51797. }
  51798. else if (attributeParameter.semantic === "POSITION") {
  51799. return "position";
  51800. }
  51801. else if (attributeParameter.semantic === "JOINT") {
  51802. return "matricesIndices";
  51803. }
  51804. else if (attributeParameter.semantic === "WEIGHT") {
  51805. return "matricesWeights";
  51806. }
  51807. else if (attributeParameter.semantic === "COLOR") {
  51808. return "color";
  51809. }
  51810. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51811. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51812. return "uv" + (channel === 0 ? "" : channel + 1);
  51813. }
  51814. };
  51815. /**
  51816. * Returns the animation path (glTF -> Babylon)
  51817. */
  51818. var getAnimationPath = function (path) {
  51819. var index = glTFAnimationPaths.indexOf(path);
  51820. if (index !== -1) {
  51821. return babylonAnimationPaths[index];
  51822. }
  51823. return path;
  51824. };
  51825. /**
  51826. * Loads and creates animations
  51827. */
  51828. var loadAnimations = function (gltfRuntime) {
  51829. for (var anim in gltfRuntime.animations) {
  51830. var animation = gltfRuntime.animations[anim];
  51831. var lastAnimation = null;
  51832. for (var i = 0; i < animation.channels.length; i++) {
  51833. // Get parameters and load buffers
  51834. var channel = animation.channels[i];
  51835. var sampler = animation.samplers[channel.sampler];
  51836. if (!sampler) {
  51837. continue;
  51838. }
  51839. var inputData = null;
  51840. var outputData = null;
  51841. if (animation.parameters) {
  51842. inputData = animation.parameters[sampler.input];
  51843. outputData = animation.parameters[sampler.output];
  51844. }
  51845. else {
  51846. inputData = sampler.input;
  51847. outputData = sampler.output;
  51848. }
  51849. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51850. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51851. var targetID = channel.target.id;
  51852. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51853. if (targetNode === null) {
  51854. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51855. }
  51856. if (targetNode === null) {
  51857. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51858. continue;
  51859. }
  51860. var isBone = targetNode instanceof BABYLON.Bone;
  51861. // Get target path (position, rotation or scaling)
  51862. var targetPath = channel.target.path;
  51863. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51864. if (targetPathIndex !== -1) {
  51865. targetPath = babylonAnimationPaths[targetPathIndex];
  51866. }
  51867. // Determine animation type
  51868. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51869. if (!isBone) {
  51870. if (targetPath === "rotationQuaternion") {
  51871. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51872. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51873. }
  51874. else {
  51875. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51876. }
  51877. }
  51878. // Create animation and key frames
  51879. var babylonAnimation = null;
  51880. var keys = [];
  51881. var arrayOffset = 0;
  51882. var modifyKey = false;
  51883. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51884. babylonAnimation = lastAnimation;
  51885. modifyKey = true;
  51886. }
  51887. if (!modifyKey) {
  51888. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51889. }
  51890. // For each frame
  51891. for (var j = 0; j < bufferInput.length; j++) {
  51892. var value = null;
  51893. if (targetPath === "rotationQuaternion") {
  51894. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  51895. arrayOffset += 4;
  51896. }
  51897. else {
  51898. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  51899. arrayOffset += 3;
  51900. }
  51901. if (isBone) {
  51902. var bone = targetNode;
  51903. var translation = BABYLON.Vector3.Zero();
  51904. var rotationQuaternion = new BABYLON.Quaternion();
  51905. var scaling = BABYLON.Vector3.Zero();
  51906. // Warning on decompose
  51907. var mat = bone.getBaseMatrix();
  51908. if (modifyKey) {
  51909. mat = lastAnimation.getKeys()[j].value;
  51910. }
  51911. mat.decompose(scaling, rotationQuaternion, translation);
  51912. if (targetPath === "position") {
  51913. translation = value;
  51914. }
  51915. else if (targetPath === "rotationQuaternion") {
  51916. rotationQuaternion = value;
  51917. }
  51918. else {
  51919. scaling = value;
  51920. }
  51921. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  51922. }
  51923. if (!modifyKey) {
  51924. keys.push({
  51925. frame: bufferInput[j],
  51926. value: value
  51927. });
  51928. }
  51929. else {
  51930. lastAnimation.getKeys()[j].value = value;
  51931. }
  51932. }
  51933. // Finish
  51934. if (!modifyKey) {
  51935. babylonAnimation.setKeys(keys);
  51936. targetNode.animations.push(babylonAnimation);
  51937. }
  51938. lastAnimation = babylonAnimation;
  51939. gltfRuntime.scene.stopAnimation(targetNode);
  51940. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  51941. }
  51942. }
  51943. };
  51944. /**
  51945. * Returns the bones transformation matrix
  51946. */
  51947. var configureBoneTransformation = function (node) {
  51948. var mat = null;
  51949. if (node.translation || node.rotation || node.scale) {
  51950. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  51951. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  51952. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  51953. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  51954. }
  51955. else {
  51956. mat = BABYLON.Matrix.FromArray(node.matrix);
  51957. }
  51958. return mat;
  51959. };
  51960. /**
  51961. * Returns the parent bone
  51962. */
  51963. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  51964. // Try to find
  51965. for (var i = 0; i < newSkeleton.bones.length; i++) {
  51966. if (newSkeleton.bones[i].name === jointName) {
  51967. return newSkeleton.bones[i];
  51968. }
  51969. }
  51970. // Not found, search in gltf nodes
  51971. var nodes = gltfRuntime.nodes;
  51972. for (var nde in nodes) {
  51973. var node = nodes[nde];
  51974. if (!node.jointName) {
  51975. continue;
  51976. }
  51977. var children = node.children;
  51978. for (var i = 0; i < children.length; i++) {
  51979. var child = gltfRuntime.nodes[children[i]];
  51980. if (!child.jointName) {
  51981. continue;
  51982. }
  51983. if (child.jointName === jointName) {
  51984. var mat = configureBoneTransformation(node);
  51985. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  51986. bone.id = nde;
  51987. return bone;
  51988. }
  51989. }
  51990. }
  51991. return null;
  51992. };
  51993. /**
  51994. * Returns the appropriate root node
  51995. */
  51996. var getNodeToRoot = function (nodesToRoot, id) {
  51997. for (var i = 0; i < nodesToRoot.length; i++) {
  51998. var nodeToRoot = nodesToRoot[i];
  51999. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  52000. var child = nodeToRoot.node.children[j];
  52001. if (child === id) {
  52002. return nodeToRoot.bone;
  52003. }
  52004. }
  52005. }
  52006. return null;
  52007. };
  52008. /**
  52009. * Returns the node with the joint name
  52010. */
  52011. var getJointNode = function (gltfRuntime, jointName) {
  52012. var nodes = gltfRuntime.nodes;
  52013. var node = nodes[jointName];
  52014. if (node) {
  52015. return {
  52016. node: node,
  52017. id: jointName
  52018. };
  52019. }
  52020. for (var nde in nodes) {
  52021. node = nodes[nde];
  52022. if (node.jointName === jointName) {
  52023. return {
  52024. node: node,
  52025. id: nde
  52026. };
  52027. }
  52028. }
  52029. return null;
  52030. };
  52031. /**
  52032. * Checks if a nodes is in joints
  52033. */
  52034. var nodeIsInJoints = function (skins, id) {
  52035. for (var i = 0; i < skins.jointNames.length; i++) {
  52036. if (skins.jointNames[i] === id) {
  52037. return true;
  52038. }
  52039. }
  52040. return false;
  52041. };
  52042. /**
  52043. * Fills the nodes to root for bones and builds hierarchy
  52044. */
  52045. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  52046. // Creates nodes for root
  52047. for (var nde in gltfRuntime.nodes) {
  52048. var node = gltfRuntime.nodes[nde];
  52049. var id = nde;
  52050. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  52051. continue;
  52052. }
  52053. // Create node to root bone
  52054. var mat = configureBoneTransformation(node);
  52055. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  52056. bone.id = id;
  52057. nodesToRoot.push({ bone: bone, node: node, id: id });
  52058. }
  52059. // Parenting
  52060. for (var i = 0; i < nodesToRoot.length; i++) {
  52061. var nodeToRoot = nodesToRoot[i];
  52062. var children = nodeToRoot.node.children;
  52063. for (var j = 0; j < children.length; j++) {
  52064. var child = null;
  52065. for (var k = 0; k < nodesToRoot.length; k++) {
  52066. if (nodesToRoot[k].id === children[j]) {
  52067. child = nodesToRoot[k];
  52068. break;
  52069. }
  52070. }
  52071. if (child) {
  52072. child.bone._parent = nodeToRoot.bone;
  52073. nodeToRoot.bone.children.push(child.bone);
  52074. }
  52075. }
  52076. }
  52077. };
  52078. var printMat = function (m) {
  52079. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  52080. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  52081. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  52082. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  52083. };
  52084. /**
  52085. * Imports a skeleton
  52086. */
  52087. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  52088. if (!newSkeleton) {
  52089. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  52090. }
  52091. if (!skins.babylonSkeleton) {
  52092. return newSkeleton;
  52093. }
  52094. // Matrices
  52095. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  52096. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52097. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  52098. // Find the root bones
  52099. var nodesToRoot = [];
  52100. var nodesToRootToAdd = [];
  52101. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  52102. newSkeleton.bones = [];
  52103. // Joints
  52104. for (var i = 0; i < skins.jointNames.length; i++) {
  52105. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52106. var node = jointNode.node;
  52107. if (!node) {
  52108. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  52109. continue;
  52110. }
  52111. var id = jointNode.id;
  52112. // Optimize, if the bone already exists...
  52113. var existingBone = gltfRuntime.scene.getBoneByID(id);
  52114. if (existingBone) {
  52115. newSkeleton.bones.push(existingBone);
  52116. continue;
  52117. }
  52118. // Search for parent bone
  52119. var foundBone = false;
  52120. var parentBone = null;
  52121. for (var j = 0; j < i; j++) {
  52122. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  52123. if (!joint) {
  52124. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  52125. continue;
  52126. }
  52127. var children = joint.children;
  52128. if (!children) {
  52129. continue;
  52130. }
  52131. foundBone = false;
  52132. for (var k = 0; k < children.length; k++) {
  52133. if (children[k] === id) {
  52134. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  52135. foundBone = true;
  52136. break;
  52137. }
  52138. }
  52139. if (foundBone) {
  52140. break;
  52141. }
  52142. }
  52143. // Create bone
  52144. var mat = configureBoneTransformation(node);
  52145. if (!parentBone && nodesToRoot.length > 0) {
  52146. parentBone = getNodeToRoot(nodesToRoot, id);
  52147. if (parentBone) {
  52148. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  52149. nodesToRootToAdd.push(parentBone);
  52150. }
  52151. }
  52152. }
  52153. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  52154. bone.id = id;
  52155. }
  52156. // Polish
  52157. var bones = newSkeleton.bones;
  52158. newSkeleton.bones = [];
  52159. for (var i = 0; i < skins.jointNames.length; i++) {
  52160. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52161. if (!jointNode) {
  52162. continue;
  52163. }
  52164. for (var j = 0; j < bones.length; j++) {
  52165. if (bones[j].id === jointNode.id) {
  52166. newSkeleton.bones.push(bones[j]);
  52167. break;
  52168. }
  52169. }
  52170. }
  52171. newSkeleton.prepare();
  52172. // Finish
  52173. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  52174. newSkeleton.bones.push(nodesToRootToAdd[i]);
  52175. }
  52176. return newSkeleton;
  52177. };
  52178. /**
  52179. * Imports a mesh and its geometries
  52180. */
  52181. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  52182. if (!newMesh) {
  52183. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52184. newMesh.id = id;
  52185. }
  52186. if (!node.babylonNode) {
  52187. return newMesh;
  52188. }
  52189. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  52190. if (!newMesh.material) {
  52191. newMesh.material = multiMat;
  52192. }
  52193. var vertexData = new BABYLON.VertexData();
  52194. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  52195. var verticesStarts = [];
  52196. var verticesCounts = [];
  52197. var indexStarts = [];
  52198. var indexCounts = [];
  52199. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52200. var meshID = meshes[meshIndex];
  52201. var mesh = gltfRuntime.meshes[meshID];
  52202. if (!mesh) {
  52203. continue;
  52204. }
  52205. // Positions, normals and UVs
  52206. for (var i = 0; i < mesh.primitives.length; i++) {
  52207. // Temporary vertex data
  52208. var tempVertexData = new BABYLON.VertexData();
  52209. var primitive = mesh.primitives[i];
  52210. if (primitive.mode !== 4) {
  52211. // continue;
  52212. }
  52213. var attributes = primitive.attributes;
  52214. var accessor = null;
  52215. var buffer = null;
  52216. // Set positions, normal and uvs
  52217. for (var semantic in attributes) {
  52218. // Link accessor and buffer view
  52219. accessor = gltfRuntime.accessors[attributes[semantic]];
  52220. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52221. if (semantic === "NORMAL") {
  52222. tempVertexData.normals = new Float32Array(buffer.length);
  52223. tempVertexData.normals.set(buffer);
  52224. }
  52225. else if (semantic === "POSITION") {
  52226. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  52227. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  52228. for (var j = 0; j < buffer.length; j += 4) {
  52229. tempVertexData.positions[j] = buffer[j];
  52230. tempVertexData.positions[j + 1] = buffer[j + 1];
  52231. tempVertexData.positions[j + 2] = buffer[j + 2];
  52232. }
  52233. }
  52234. else {
  52235. tempVertexData.positions = new Float32Array(buffer.length);
  52236. tempVertexData.positions.set(buffer);
  52237. }
  52238. verticesCounts.push(tempVertexData.positions.length);
  52239. }
  52240. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  52241. var channel = Number(semantic.split("_")[1]);
  52242. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  52243. var uvs = new Float32Array(buffer.length);
  52244. uvs.set(buffer);
  52245. normalizeUVs(uvs);
  52246. tempVertexData.set(uvs, uvKind);
  52247. }
  52248. else if (semantic === "JOINT") {
  52249. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  52250. tempVertexData.matricesIndices.set(buffer);
  52251. }
  52252. else if (semantic === "WEIGHT") {
  52253. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  52254. tempVertexData.matricesWeights.set(buffer);
  52255. }
  52256. else if (semantic === "COLOR") {
  52257. tempVertexData.colors = new Float32Array(buffer.length);
  52258. tempVertexData.colors.set(buffer);
  52259. }
  52260. }
  52261. // Indices
  52262. accessor = gltfRuntime.accessors[primitive.indices];
  52263. if (accessor) {
  52264. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52265. tempVertexData.indices = new Int32Array(buffer.length);
  52266. tempVertexData.indices.set(buffer);
  52267. indexCounts.push(tempVertexData.indices.length);
  52268. }
  52269. else {
  52270. // Set indices on the fly
  52271. var indices = [];
  52272. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  52273. indices.push(j);
  52274. }
  52275. tempVertexData.indices = new Int32Array(indices);
  52276. indexCounts.push(tempVertexData.indices.length);
  52277. }
  52278. vertexData.merge(tempVertexData);
  52279. tempVertexData = undefined;
  52280. // Sub material
  52281. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  52282. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  52283. // Update vertices start and index start
  52284. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  52285. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  52286. }
  52287. }
  52288. // Apply geometry
  52289. geometry.setAllVerticesData(vertexData, false);
  52290. newMesh.computeWorldMatrix(true);
  52291. // Apply submeshes
  52292. newMesh.subMeshes = [];
  52293. var index = 0;
  52294. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52295. var meshID = meshes[meshIndex];
  52296. var mesh = gltfRuntime.meshes[meshID];
  52297. if (!mesh) {
  52298. continue;
  52299. }
  52300. for (var i = 0; i < mesh.primitives.length; i++) {
  52301. if (mesh.primitives[i].mode !== 4) {
  52302. //continue;
  52303. }
  52304. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  52305. index++;
  52306. }
  52307. }
  52308. // Finish
  52309. return newMesh;
  52310. };
  52311. /**
  52312. * Configure node transformation from position, rotation and scaling
  52313. */
  52314. var configureNode = function (newNode, position, rotation, scaling) {
  52315. if (newNode.position) {
  52316. newNode.position = position;
  52317. }
  52318. if (newNode.rotationQuaternion || newNode.rotation) {
  52319. newNode.rotationQuaternion = rotation;
  52320. }
  52321. if (newNode.scaling) {
  52322. newNode.scaling = scaling;
  52323. }
  52324. };
  52325. /**
  52326. * Configures node from transformation matrix
  52327. */
  52328. var configureNodeFromMatrix = function (newNode, node, parent) {
  52329. if (node.matrix) {
  52330. var position = new BABYLON.Vector3(0, 0, 0);
  52331. var rotation = new BABYLON.Quaternion();
  52332. var scaling = new BABYLON.Vector3(0, 0, 0);
  52333. var mat = BABYLON.Matrix.FromArray(node.matrix);
  52334. mat.decompose(scaling, rotation, position);
  52335. configureNode(newNode, position, rotation, scaling);
  52336. }
  52337. else {
  52338. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  52339. }
  52340. newNode.computeWorldMatrix(true);
  52341. };
  52342. /**
  52343. * Imports a node
  52344. */
  52345. var importNode = function (gltfRuntime, node, id, parent) {
  52346. var lastNode = null;
  52347. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  52348. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  52349. return null;
  52350. }
  52351. }
  52352. // Meshes
  52353. if (node.skin) {
  52354. if (node.meshes) {
  52355. var skin = gltfRuntime.skins[node.skin];
  52356. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  52357. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  52358. if (newMesh.skeleton === null) {
  52359. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  52360. if (!skin.babylonSkeleton) {
  52361. skin.babylonSkeleton = newMesh.skeleton;
  52362. }
  52363. }
  52364. lastNode = newMesh;
  52365. }
  52366. }
  52367. else if (node.meshes) {
  52368. /**
  52369. * Improve meshes property
  52370. */
  52371. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  52372. lastNode = newMesh;
  52373. }
  52374. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52375. var light = gltfRuntime.lights[node.light];
  52376. if (light) {
  52377. if (light.type === "ambient") {
  52378. var ambienLight = light[light.type];
  52379. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52380. hemiLight.name = node.name;
  52381. if (ambienLight.color) {
  52382. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  52383. }
  52384. lastNode = hemiLight;
  52385. }
  52386. else if (light.type === "directional") {
  52387. var directionalLight = light[light.type];
  52388. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52389. dirLight.name = node.name;
  52390. if (directionalLight.color) {
  52391. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  52392. }
  52393. lastNode = dirLight;
  52394. }
  52395. else if (light.type === "point") {
  52396. var pointLight = light[light.type];
  52397. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52398. ptLight.name = node.name;
  52399. if (pointLight.color) {
  52400. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  52401. }
  52402. lastNode = ptLight;
  52403. }
  52404. else if (light.type === "spot") {
  52405. var spotLight = light[light.type];
  52406. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  52407. spLight.name = node.name;
  52408. if (spotLight.color) {
  52409. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  52410. }
  52411. if (spotLight.fallOfAngle) {
  52412. spLight.angle = spotLight.fallOfAngle;
  52413. }
  52414. if (spotLight.fallOffExponent) {
  52415. spLight.exponent = spotLight.fallOffExponent;
  52416. }
  52417. lastNode = spLight;
  52418. }
  52419. }
  52420. }
  52421. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52422. var camera = gltfRuntime.cameras[node.camera];
  52423. if (camera) {
  52424. if (camera.type === "orthographic") {
  52425. var orthographicCamera = camera[camera.type];
  52426. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52427. orthoCamera.name = node.name;
  52428. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  52429. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52430. lastNode = orthoCamera;
  52431. }
  52432. else if (camera.type === "perspective") {
  52433. var perspectiveCamera = camera[camera.type];
  52434. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52435. persCamera.name = node.name;
  52436. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52437. if (!perspectiveCamera.aspectRatio) {
  52438. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  52439. }
  52440. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  52441. persCamera.maxZ = perspectiveCamera.zfar;
  52442. persCamera.minZ = perspectiveCamera.znear;
  52443. }
  52444. lastNode = persCamera;
  52445. }
  52446. }
  52447. }
  52448. // Empty node
  52449. if (!node.jointName) {
  52450. if (node.babylonNode) {
  52451. return node.babylonNode;
  52452. }
  52453. else if (lastNode === null) {
  52454. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52455. node.babylonNode = dummy;
  52456. lastNode = dummy;
  52457. }
  52458. }
  52459. if (lastNode !== null) {
  52460. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  52461. configureNodeFromMatrix(lastNode, node, parent);
  52462. }
  52463. else {
  52464. var translation = node.translation || [0, 0, 0];
  52465. var rotation = node.rotation || [0, 0, 0, 1];
  52466. var scale = node.scale || [1, 1, 1];
  52467. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  52468. }
  52469. lastNode.updateCache(true);
  52470. node.babylonNode = lastNode;
  52471. }
  52472. return lastNode;
  52473. };
  52474. /**
  52475. * Traverses nodes and creates them
  52476. */
  52477. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  52478. var node = gltfRuntime.nodes[id];
  52479. var newNode = null;
  52480. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  52481. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  52482. meshIncluded = true;
  52483. }
  52484. else {
  52485. meshIncluded = false;
  52486. }
  52487. }
  52488. else {
  52489. meshIncluded = true;
  52490. }
  52491. if (!node.jointName && meshIncluded) {
  52492. newNode = importNode(gltfRuntime, node, id, parent);
  52493. if (newNode !== null) {
  52494. newNode.id = id;
  52495. newNode.parent = parent;
  52496. }
  52497. }
  52498. if (node.children) {
  52499. for (var i = 0; i < node.children.length; i++) {
  52500. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  52501. }
  52502. }
  52503. };
  52504. /**
  52505. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  52506. */
  52507. var postLoad = function (gltfRuntime) {
  52508. // Nodes
  52509. var currentScene = gltfRuntime.currentScene;
  52510. if (currentScene) {
  52511. for (var i = 0; i < currentScene.nodes.length; i++) {
  52512. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52513. }
  52514. }
  52515. else {
  52516. for (var thing in gltfRuntime.scenes) {
  52517. currentScene = gltfRuntime.scenes[thing];
  52518. for (var i = 0; i < currentScene.nodes.length; i++) {
  52519. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52520. }
  52521. }
  52522. }
  52523. // Set animations
  52524. loadAnimations(gltfRuntime);
  52525. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  52526. var skeleton = gltfRuntime.scene.skeletons[i];
  52527. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  52528. }
  52529. };
  52530. /**
  52531. * onBind shaderrs callback to set uniforms and matrices
  52532. */
  52533. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  52534. var materialValues = material.values || technique.parameters;
  52535. for (var unif in unTreatedUniforms) {
  52536. var uniform = unTreatedUniforms[unif];
  52537. var type = uniform.type;
  52538. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  52539. if (uniform.semantic && !uniform.source && !uniform.node) {
  52540. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  52541. }
  52542. else if (uniform.semantic && (uniform.source || uniform.node)) {
  52543. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  52544. if (source === null) {
  52545. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  52546. }
  52547. if (source === null) {
  52548. continue;
  52549. }
  52550. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  52551. }
  52552. }
  52553. else {
  52554. var value = materialValues[technique.uniforms[unif]];
  52555. if (!value) {
  52556. continue;
  52557. }
  52558. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52559. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  52560. if (texture === null || texture === undefined) {
  52561. continue;
  52562. }
  52563. shaderMaterial.getEffect().setTexture(unif, texture);
  52564. }
  52565. else {
  52566. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  52567. }
  52568. }
  52569. }
  52570. onSuccess(shaderMaterial);
  52571. };
  52572. /**
  52573. * Prepare uniforms to send the only one time
  52574. * Loads the appropriate textures
  52575. */
  52576. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  52577. var materialValues = material.values || technique.parameters;
  52578. var techniqueUniforms = technique.uniforms;
  52579. /**
  52580. * Prepare values here (not matrices)
  52581. */
  52582. for (var unif in unTreatedUniforms) {
  52583. var uniform = unTreatedUniforms[unif];
  52584. var type = uniform.type;
  52585. var value = materialValues[techniqueUniforms[unif]];
  52586. if (value === undefined) {
  52587. // In case the value is the same for all materials
  52588. value = uniform.value;
  52589. }
  52590. if (!value) {
  52591. continue;
  52592. }
  52593. var onLoadTexture = function (uniformName) {
  52594. return function (texture) {
  52595. if (uniform.value) {
  52596. // Static uniform
  52597. shaderMaterial.setTexture(uniformName, texture);
  52598. delete unTreatedUniforms[uniformName];
  52599. }
  52600. };
  52601. };
  52602. // Texture (sampler2D)
  52603. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52604. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  52605. }
  52606. else {
  52607. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  52608. // Static uniform
  52609. delete unTreatedUniforms[unif];
  52610. }
  52611. }
  52612. }
  52613. };
  52614. /**
  52615. * Shader compilation failed
  52616. */
  52617. var onShaderCompileError = function (program, shaderMaterial, onError) {
  52618. return function (effect, error) {
  52619. shaderMaterial.dispose(true);
  52620. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  52621. };
  52622. };
  52623. /**
  52624. * Shader compilation success
  52625. */
  52626. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  52627. return function (_) {
  52628. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  52629. shaderMaterial.onBind = function (mesh) {
  52630. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  52631. };
  52632. };
  52633. };
  52634. /**
  52635. * Returns the appropriate uniform if already handled by babylon
  52636. */
  52637. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  52638. for (var unif in technique.uniforms) {
  52639. var uniform = technique.uniforms[unif];
  52640. var uniformParameter = technique.parameters[uniform];
  52641. if (tokenizer.currentIdentifier === unif) {
  52642. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  52643. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52644. if (transformIndex !== -1) {
  52645. delete unTreatedUniforms[unif];
  52646. return babylonTransforms[transformIndex];
  52647. }
  52648. }
  52649. }
  52650. }
  52651. return tokenizer.currentIdentifier;
  52652. };
  52653. /**
  52654. * All shaders loaded. Create materials one by one
  52655. */
  52656. var importMaterials = function (gltfRuntime) {
  52657. // Create materials
  52658. for (var mat in gltfRuntime.materials) {
  52659. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  52660. }
  52661. };
  52662. /**
  52663. * Implementation of the base glTF spec
  52664. */
  52665. var GLTFLoaderBase = (function () {
  52666. function GLTFLoaderBase() {
  52667. }
  52668. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  52669. var gltfRuntime = {
  52670. extensions: {},
  52671. accessors: {},
  52672. buffers: {},
  52673. bufferViews: {},
  52674. meshes: {},
  52675. lights: {},
  52676. cameras: {},
  52677. nodes: {},
  52678. images: {},
  52679. textures: {},
  52680. shaders: {},
  52681. programs: {},
  52682. samplers: {},
  52683. techniques: {},
  52684. materials: {},
  52685. animations: {},
  52686. skins: {},
  52687. extensionsUsed: [],
  52688. scenes: {},
  52689. buffersCount: 0,
  52690. shaderscount: 0,
  52691. scene: scene,
  52692. rootUrl: rootUrl,
  52693. loadedBufferCount: 0,
  52694. loadedBufferViews: {},
  52695. loadedShaderCount: 0,
  52696. importOnlyMeshes: false,
  52697. dummyNodes: []
  52698. };
  52699. // Parse
  52700. if (parsedData.extensions) {
  52701. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  52702. }
  52703. if (parsedData.extensionsUsed) {
  52704. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  52705. }
  52706. if (parsedData.buffers) {
  52707. parseBuffers(parsedData.buffers, gltfRuntime);
  52708. }
  52709. if (parsedData.bufferViews) {
  52710. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  52711. }
  52712. if (parsedData.accessors) {
  52713. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  52714. }
  52715. if (parsedData.meshes) {
  52716. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  52717. }
  52718. if (parsedData.lights) {
  52719. parseObject(parsedData.lights, "lights", gltfRuntime);
  52720. }
  52721. if (parsedData.cameras) {
  52722. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  52723. }
  52724. if (parsedData.nodes) {
  52725. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  52726. }
  52727. if (parsedData.images) {
  52728. parseObject(parsedData.images, "images", gltfRuntime);
  52729. }
  52730. if (parsedData.textures) {
  52731. parseObject(parsedData.textures, "textures", gltfRuntime);
  52732. }
  52733. if (parsedData.shaders) {
  52734. parseShaders(parsedData.shaders, gltfRuntime);
  52735. }
  52736. if (parsedData.programs) {
  52737. parseObject(parsedData.programs, "programs", gltfRuntime);
  52738. }
  52739. if (parsedData.samplers) {
  52740. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  52741. }
  52742. if (parsedData.techniques) {
  52743. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  52744. }
  52745. if (parsedData.materials) {
  52746. parseObject(parsedData.materials, "materials", gltfRuntime);
  52747. }
  52748. if (parsedData.animations) {
  52749. parseObject(parsedData.animations, "animations", gltfRuntime);
  52750. }
  52751. if (parsedData.skins) {
  52752. parseObject(parsedData.skins, "skins", gltfRuntime);
  52753. }
  52754. if (parsedData.scenes) {
  52755. gltfRuntime.scenes = parsedData.scenes;
  52756. }
  52757. if (parsedData.scene && parsedData.scenes) {
  52758. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  52759. }
  52760. return gltfRuntime;
  52761. };
  52762. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52763. var buffer = gltfRuntime.buffers[id];
  52764. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  52765. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  52766. }
  52767. else {
  52768. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  52769. onError(request.status + " " + request.statusText);
  52770. });
  52771. }
  52772. };
  52773. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52774. var texture = gltfRuntime.textures[id];
  52775. if (!texture || !texture.source) {
  52776. onError(null);
  52777. return;
  52778. }
  52779. if (texture.babylonTexture) {
  52780. onSuccess(null);
  52781. return;
  52782. }
  52783. var source = gltfRuntime.images[texture.source];
  52784. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52785. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52786. }
  52787. else {
  52788. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52789. onError(request.status + " " + request.statusText);
  52790. });
  52791. }
  52792. };
  52793. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52794. var texture = gltfRuntime.textures[id];
  52795. if (texture.babylonTexture) {
  52796. onSuccess(texture.babylonTexture);
  52797. return;
  52798. }
  52799. var sampler = gltfRuntime.samplers[texture.sampler];
  52800. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52801. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52802. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52803. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52804. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52805. var blob = new Blob([buffer]);
  52806. var blobURL = URL.createObjectURL(blob);
  52807. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52808. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52809. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52810. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52811. newTexture.name = id;
  52812. texture.babylonTexture = newTexture;
  52813. onSuccess(newTexture);
  52814. };
  52815. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52816. var shader = gltfRuntime.shaders[id];
  52817. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52818. var shaderString = atob(shader.uri.split(",")[1]);
  52819. onSuccess(shaderString);
  52820. }
  52821. else {
  52822. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52823. onError(request.status + " " + request.statusText);
  52824. });
  52825. }
  52826. };
  52827. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52828. var material = gltfRuntime.materials[id];
  52829. var technique = gltfRuntime.techniques[material.technique];
  52830. if (!technique) {
  52831. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52832. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52833. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52834. onSuccess(defaultMaterial);
  52835. return;
  52836. }
  52837. var program = gltfRuntime.programs[technique.program];
  52838. var states = technique.states;
  52839. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52840. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52841. var newVertexShader = "";
  52842. var newPixelShader = "";
  52843. var vertexTokenizer = new Tokenizer(vertexShader);
  52844. var pixelTokenizer = new Tokenizer(pixelShader);
  52845. var unTreatedUniforms = {};
  52846. var uniforms = [];
  52847. var attributes = [];
  52848. var samplers = [];
  52849. // Fill uniform, sampler2D and attributes
  52850. for (var unif in technique.uniforms) {
  52851. var uniform = technique.uniforms[unif];
  52852. var uniformParameter = technique.parameters[uniform];
  52853. unTreatedUniforms[unif] = uniformParameter;
  52854. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52855. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52856. if (transformIndex !== -1) {
  52857. uniforms.push(babylonTransforms[transformIndex]);
  52858. delete unTreatedUniforms[unif];
  52859. }
  52860. else {
  52861. uniforms.push(unif);
  52862. }
  52863. }
  52864. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52865. samplers.push(unif);
  52866. }
  52867. else {
  52868. uniforms.push(unif);
  52869. }
  52870. }
  52871. for (var attr in technique.attributes) {
  52872. var attribute = technique.attributes[attr];
  52873. var attributeParameter = technique.parameters[attribute];
  52874. if (attributeParameter.semantic) {
  52875. attributes.push(getAttribute(attributeParameter));
  52876. }
  52877. }
  52878. // Configure vertex shader
  52879. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52880. var tokenType = vertexTokenizer.currentToken;
  52881. if (tokenType !== ETokenType.IDENTIFIER) {
  52882. newVertexShader += vertexTokenizer.currentString;
  52883. continue;
  52884. }
  52885. var foundAttribute = false;
  52886. for (var attr in technique.attributes) {
  52887. var attribute = technique.attributes[attr];
  52888. var attributeParameter = technique.parameters[attribute];
  52889. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  52890. newVertexShader += getAttribute(attributeParameter);
  52891. foundAttribute = true;
  52892. break;
  52893. }
  52894. }
  52895. if (foundAttribute) {
  52896. continue;
  52897. }
  52898. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  52899. }
  52900. // Configure pixel shader
  52901. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  52902. var tokenType = pixelTokenizer.currentToken;
  52903. if (tokenType !== ETokenType.IDENTIFIER) {
  52904. newPixelShader += pixelTokenizer.currentString;
  52905. continue;
  52906. }
  52907. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  52908. }
  52909. // Create shader material
  52910. var shaderPath = {
  52911. vertex: program.vertexShader + id,
  52912. fragment: program.fragmentShader + id
  52913. };
  52914. var options = {
  52915. attributes: attributes,
  52916. uniforms: uniforms,
  52917. samplers: samplers,
  52918. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  52919. };
  52920. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  52921. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  52922. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  52923. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  52924. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  52925. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52926. if (states && states.functions) {
  52927. var functions = states.functions;
  52928. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  52929. shaderMaterial.backFaceCulling = false;
  52930. }
  52931. var blendFunc = functions.blendFuncSeparate;
  52932. if (blendFunc) {
  52933. 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) {
  52934. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  52935. }
  52936. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52937. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52938. }
  52939. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52940. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  52941. }
  52942. 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) {
  52943. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  52944. }
  52945. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52946. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  52947. }
  52948. 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) {
  52949. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  52950. }
  52951. }
  52952. }
  52953. };
  52954. return GLTFLoaderBase;
  52955. }());
  52956. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  52957. /**
  52958. * glTF V1 Loader
  52959. */
  52960. var GLTFLoader = (function () {
  52961. function GLTFLoader() {
  52962. }
  52963. GLTFLoader.RegisterExtension = function (extension) {
  52964. if (GLTFLoader.Extensions[extension.name]) {
  52965. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  52966. return;
  52967. }
  52968. GLTFLoader.Extensions[extension.name] = extension;
  52969. };
  52970. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  52971. var _this = this;
  52972. scene.useRightHandedSystem = true;
  52973. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52974. gltfRuntime.importOnlyMeshes = true;
  52975. if (meshesNames === "") {
  52976. gltfRuntime.importMeshesNames = [];
  52977. }
  52978. else if (typeof meshesNames === "string") {
  52979. gltfRuntime.importMeshesNames = [meshesNames];
  52980. }
  52981. else if (meshesNames && !(meshesNames instanceof Array)) {
  52982. gltfRuntime.importMeshesNames = [meshesNames];
  52983. }
  52984. else {
  52985. gltfRuntime.importMeshesNames = [];
  52986. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  52987. }
  52988. // Create nodes
  52989. _this._createNodes(gltfRuntime);
  52990. var meshes = [];
  52991. var skeletons = [];
  52992. // Fill arrays of meshes and skeletons
  52993. for (var nde in gltfRuntime.nodes) {
  52994. var node = gltfRuntime.nodes[nde];
  52995. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  52996. meshes.push(node.babylonNode);
  52997. }
  52998. }
  52999. for (var skl in gltfRuntime.skins) {
  53000. var skin = gltfRuntime.skins[skl];
  53001. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53002. skeletons.push(skin.babylonSkeleton);
  53003. }
  53004. }
  53005. // Load buffers, shaders, materials, etc.
  53006. _this._loadBuffersAsync(gltfRuntime, function () {
  53007. _this._loadShadersAsync(gltfRuntime, function () {
  53008. importMaterials(gltfRuntime);
  53009. postLoad(gltfRuntime);
  53010. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53011. onSuccess(meshes, null, skeletons);
  53012. }
  53013. });
  53014. }, onProgress);
  53015. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53016. onSuccess(meshes, null, skeletons);
  53017. }
  53018. }, onError);
  53019. return true;
  53020. };
  53021. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53022. var _this = this;
  53023. scene.useRightHandedSystem = true;
  53024. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53025. // Load runtime extensios
  53026. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  53027. // Create nodes
  53028. _this._createNodes(gltfRuntime);
  53029. // Load buffers, shaders, materials, etc.
  53030. _this._loadBuffersAsync(gltfRuntime, function () {
  53031. _this._loadShadersAsync(gltfRuntime, function () {
  53032. importMaterials(gltfRuntime);
  53033. postLoad(gltfRuntime);
  53034. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  53035. onSuccess();
  53036. }
  53037. });
  53038. });
  53039. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  53040. onSuccess();
  53041. }
  53042. }, onError);
  53043. }, onError);
  53044. };
  53045. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  53046. var hasShaders = false;
  53047. var processShader = function (sha, shader) {
  53048. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  53049. gltfRuntime.loadedShaderCount++;
  53050. if (shaderString) {
  53051. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  53052. }
  53053. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  53054. onload();
  53055. }
  53056. }, function () {
  53057. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  53058. });
  53059. };
  53060. for (var sha in gltfRuntime.shaders) {
  53061. hasShaders = true;
  53062. var shader = gltfRuntime.shaders[sha];
  53063. if (shader) {
  53064. processShader.bind(this, sha, shader)();
  53065. }
  53066. else {
  53067. BABYLON.Tools.Error("No shader named: " + sha);
  53068. }
  53069. }
  53070. if (!hasShaders) {
  53071. onload();
  53072. }
  53073. };
  53074. ;
  53075. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  53076. var hasBuffers = false;
  53077. var processBuffer = function (buf, buffer) {
  53078. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  53079. gltfRuntime.loadedBufferCount++;
  53080. if (bufferView) {
  53081. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  53082. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  53083. }
  53084. gltfRuntime.loadedBufferViews[buf] = bufferView;
  53085. }
  53086. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  53087. onLoad();
  53088. }
  53089. }, function () {
  53090. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  53091. });
  53092. };
  53093. for (var buf in gltfRuntime.buffers) {
  53094. hasBuffers = true;
  53095. var buffer = gltfRuntime.buffers[buf];
  53096. if (buffer) {
  53097. processBuffer.bind(this, buf, buffer)();
  53098. }
  53099. else {
  53100. BABYLON.Tools.Error("No buffer named: " + buf);
  53101. }
  53102. }
  53103. if (!hasBuffers) {
  53104. onLoad();
  53105. }
  53106. };
  53107. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  53108. var currentScene = gltfRuntime.currentScene;
  53109. if (currentScene) {
  53110. // Only one scene even if multiple scenes are defined
  53111. for (var i = 0; i < currentScene.nodes.length; i++) {
  53112. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53113. }
  53114. }
  53115. else {
  53116. // Load all scenes
  53117. for (var thing in gltfRuntime.scenes) {
  53118. currentScene = gltfRuntime.scenes[thing];
  53119. for (var i = 0; i < currentScene.nodes.length; i++) {
  53120. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53121. }
  53122. }
  53123. }
  53124. };
  53125. GLTFLoader.Extensions = {};
  53126. return GLTFLoader;
  53127. }());
  53128. GLTF1.GLTFLoader = GLTFLoader;
  53129. ;
  53130. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  53131. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53132. })(BABYLON || (BABYLON = {}));
  53133. //# sourceMappingURL=babylon.glTFLoader.js.map
  53134. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53135. var BABYLON;
  53136. (function (BABYLON) {
  53137. var GLTF1;
  53138. (function (GLTF1) {
  53139. /**
  53140. * Utils functions for GLTF
  53141. */
  53142. var GLTFUtils = (function () {
  53143. function GLTFUtils() {
  53144. }
  53145. /**
  53146. * Sets the given "parameter" matrix
  53147. * @param scene: the {BABYLON.Scene} object
  53148. * @param source: the source node where to pick the matrix
  53149. * @param parameter: the GLTF technique parameter
  53150. * @param uniformName: the name of the shader's uniform
  53151. * @param shaderMaterial: the shader material
  53152. */
  53153. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  53154. var mat = null;
  53155. if (parameter.semantic === "MODEL") {
  53156. mat = source.getWorldMatrix();
  53157. }
  53158. else if (parameter.semantic === "PROJECTION") {
  53159. mat = scene.getProjectionMatrix();
  53160. }
  53161. else if (parameter.semantic === "VIEW") {
  53162. mat = scene.getViewMatrix();
  53163. }
  53164. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  53165. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  53166. }
  53167. else if (parameter.semantic === "MODELVIEW") {
  53168. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  53169. }
  53170. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  53171. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  53172. }
  53173. else if (parameter.semantic === "MODELINVERSE") {
  53174. mat = source.getWorldMatrix().invert();
  53175. }
  53176. else if (parameter.semantic === "VIEWINVERSE") {
  53177. mat = scene.getViewMatrix().invert();
  53178. }
  53179. else if (parameter.semantic === "PROJECTIONINVERSE") {
  53180. mat = scene.getProjectionMatrix().invert();
  53181. }
  53182. else if (parameter.semantic === "MODELVIEWINVERSE") {
  53183. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  53184. }
  53185. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  53186. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  53187. }
  53188. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  53189. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  53190. }
  53191. else {
  53192. debugger;
  53193. }
  53194. switch (parameter.type) {
  53195. case GLTF1.EParameterType.FLOAT_MAT2:
  53196. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  53197. break;
  53198. case GLTF1.EParameterType.FLOAT_MAT3:
  53199. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  53200. break;
  53201. case GLTF1.EParameterType.FLOAT_MAT4:
  53202. shaderMaterial.setMatrix(uniformName, mat);
  53203. break;
  53204. default: break;
  53205. }
  53206. };
  53207. /**
  53208. * Sets the given "parameter" matrix
  53209. * @param shaderMaterial: the shader material
  53210. * @param uniform: the name of the shader's uniform
  53211. * @param value: the value of the uniform
  53212. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  53213. */
  53214. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  53215. switch (type) {
  53216. case GLTF1.EParameterType.FLOAT:
  53217. shaderMaterial.setFloat(uniform, value);
  53218. return true;
  53219. case GLTF1.EParameterType.FLOAT_VEC2:
  53220. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  53221. return true;
  53222. case GLTF1.EParameterType.FLOAT_VEC3:
  53223. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  53224. return true;
  53225. case GLTF1.EParameterType.FLOAT_VEC4:
  53226. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  53227. return true;
  53228. default: return false;
  53229. }
  53230. };
  53231. /**
  53232. * If the uri is a base64 string
  53233. * @param uri: the uri to test
  53234. */
  53235. GLTFUtils.IsBase64 = function (uri) {
  53236. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  53237. };
  53238. /**
  53239. * Decode the base64 uri
  53240. * @param uri: the uri to decode
  53241. */
  53242. GLTFUtils.DecodeBase64 = function (uri) {
  53243. var decodedString = atob(uri.split(",")[1]);
  53244. var bufferLength = decodedString.length;
  53245. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  53246. for (var i = 0; i < bufferLength; i++) {
  53247. bufferView[i] = decodedString.charCodeAt(i);
  53248. }
  53249. return bufferView.buffer;
  53250. };
  53251. /**
  53252. * Returns the wrap mode of the texture
  53253. * @param mode: the mode value
  53254. */
  53255. GLTFUtils.GetWrapMode = function (mode) {
  53256. switch (mode) {
  53257. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  53258. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  53259. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53260. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53261. }
  53262. };
  53263. /**
  53264. * Returns the byte stride giving an accessor
  53265. * @param accessor: the GLTF accessor objet
  53266. */
  53267. GLTFUtils.GetByteStrideFromType = function (accessor) {
  53268. // Needs this function since "byteStride" isn't requiered in glTF format
  53269. var type = accessor.type;
  53270. switch (type) {
  53271. case "VEC2": return 2;
  53272. case "VEC3": return 3;
  53273. case "VEC4": return 4;
  53274. case "MAT2": return 4;
  53275. case "MAT3": return 9;
  53276. case "MAT4": return 16;
  53277. default: return 1;
  53278. }
  53279. };
  53280. /**
  53281. * Returns the texture filter mode giving a mode value
  53282. * @param mode: the filter mode value
  53283. */
  53284. GLTFUtils.GetTextureFilterMode = function (mode) {
  53285. switch (mode) {
  53286. case GLTF1.ETextureFilterType.LINEAR:
  53287. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  53288. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  53289. case GLTF1.ETextureFilterType.NEAREST:
  53290. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53291. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  53292. }
  53293. };
  53294. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  53295. var byteOffset = bufferView.byteOffset + byteOffset;
  53296. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  53297. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  53298. throw new Error("Buffer access is out of range");
  53299. }
  53300. var buffer = loadedBufferView.buffer;
  53301. byteOffset += loadedBufferView.byteOffset;
  53302. switch (componentType) {
  53303. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  53304. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  53305. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  53306. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  53307. default: return new Float32Array(buffer, byteOffset, byteLength);
  53308. }
  53309. };
  53310. /**
  53311. * Returns a buffer from its accessor
  53312. * @param gltfRuntime: the GLTF runtime
  53313. * @param accessor: the GLTF accessor
  53314. */
  53315. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  53316. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  53317. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  53318. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  53319. };
  53320. /**
  53321. * Decodes a buffer view into a string
  53322. * @param view: the buffer view
  53323. */
  53324. GLTFUtils.DecodeBufferToText = function (view) {
  53325. var result = "";
  53326. var length = view.byteLength;
  53327. for (var i = 0; i < length; ++i) {
  53328. result += String.fromCharCode(view[i]);
  53329. }
  53330. return result;
  53331. };
  53332. /**
  53333. * Returns the default material of gltf. Related to
  53334. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  53335. * @param scene: the Babylon.js scene
  53336. */
  53337. GLTFUtils.GetDefaultMaterial = function (scene) {
  53338. if (!GLTFUtils._DefaultMaterial) {
  53339. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  53340. "precision highp float;",
  53341. "",
  53342. "uniform mat4 worldView;",
  53343. "uniform mat4 projection;",
  53344. "",
  53345. "attribute vec3 position;",
  53346. "",
  53347. "void main(void)",
  53348. "{",
  53349. " gl_Position = projection * worldView * vec4(position, 1.0);",
  53350. "}"
  53351. ].join("\n");
  53352. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  53353. "precision highp float;",
  53354. "",
  53355. "uniform vec4 u_emission;",
  53356. "",
  53357. "void main(void)",
  53358. "{",
  53359. " gl_FragColor = u_emission;",
  53360. "}"
  53361. ].join("\n");
  53362. var shaderPath = {
  53363. vertex: "GLTFDefaultMaterial",
  53364. fragment: "GLTFDefaultMaterial"
  53365. };
  53366. var options = {
  53367. attributes: ["position"],
  53368. uniforms: ["worldView", "projection", "u_emission"],
  53369. samplers: [],
  53370. needAlphaBlending: false
  53371. };
  53372. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  53373. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  53374. }
  53375. return GLTFUtils._DefaultMaterial;
  53376. };
  53377. // The GLTF default material
  53378. GLTFUtils._DefaultMaterial = null;
  53379. return GLTFUtils;
  53380. }());
  53381. GLTF1.GLTFUtils = GLTFUtils;
  53382. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53383. })(BABYLON || (BABYLON = {}));
  53384. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  53385. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53386. var BABYLON;
  53387. (function (BABYLON) {
  53388. var GLTF1;
  53389. (function (GLTF1) {
  53390. var GLTFLoaderExtension = (function () {
  53391. function GLTFLoaderExtension(name) {
  53392. this._name = name;
  53393. }
  53394. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  53395. get: function () {
  53396. return this._name;
  53397. },
  53398. enumerable: true,
  53399. configurable: true
  53400. });
  53401. /**
  53402. * Defines an override for loading the runtime
  53403. * Return true to stop further extensions from loading the runtime
  53404. */
  53405. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53406. return false;
  53407. };
  53408. /**
  53409. * Defines an onverride for creating gltf runtime
  53410. * Return true to stop further extensions from creating the runtime
  53411. */
  53412. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53413. return false;
  53414. };
  53415. /**
  53416. * Defines an override for loading buffers
  53417. * Return true to stop further extensions from loading this buffer
  53418. */
  53419. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53420. return false;
  53421. };
  53422. /**
  53423. * Defines an override for loading texture buffers
  53424. * Return true to stop further extensions from loading this texture data
  53425. */
  53426. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53427. return false;
  53428. };
  53429. /**
  53430. * Defines an override for creating textures
  53431. * Return true to stop further extensions from loading this texture
  53432. */
  53433. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53434. return false;
  53435. };
  53436. /**
  53437. * Defines an override for loading shader strings
  53438. * Return true to stop further extensions from loading this shader data
  53439. */
  53440. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53441. return false;
  53442. };
  53443. /**
  53444. * Defines an override for loading materials
  53445. * Return true to stop further extensions from loading this material
  53446. */
  53447. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53448. return false;
  53449. };
  53450. // ---------
  53451. // Utilities
  53452. // ---------
  53453. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53454. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53455. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  53456. }, function () {
  53457. setTimeout(function () {
  53458. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53459. });
  53460. });
  53461. };
  53462. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53463. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53464. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  53465. }, function () {
  53466. setTimeout(function () {
  53467. onSuccess();
  53468. });
  53469. });
  53470. };
  53471. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53472. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53473. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53474. }, function () {
  53475. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53476. });
  53477. };
  53478. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  53479. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  53480. };
  53481. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53482. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53483. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53484. }, function () {
  53485. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53486. });
  53487. };
  53488. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53489. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53490. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53491. }, function () {
  53492. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53493. });
  53494. };
  53495. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53496. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53497. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53498. }, function () {
  53499. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53500. });
  53501. };
  53502. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53503. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53504. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53505. }, function () {
  53506. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53507. });
  53508. };
  53509. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  53510. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  53511. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  53512. if (func(loaderExtension)) {
  53513. return;
  53514. }
  53515. }
  53516. defaultFunc();
  53517. };
  53518. return GLTFLoaderExtension;
  53519. }());
  53520. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  53521. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53522. })(BABYLON || (BABYLON = {}));
  53523. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  53524. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53525. var BABYLON;
  53526. (function (BABYLON) {
  53527. var GLTF1;
  53528. (function (GLTF1) {
  53529. var BinaryExtensionBufferName = "binary_glTF";
  53530. var EContentFormat;
  53531. (function (EContentFormat) {
  53532. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  53533. })(EContentFormat || (EContentFormat = {}));
  53534. ;
  53535. ;
  53536. ;
  53537. var GLTFBinaryExtension = (function (_super) {
  53538. __extends(GLTFBinaryExtension, _super);
  53539. function GLTFBinaryExtension() {
  53540. return _super.call(this, "KHR_binary_glTF") || this;
  53541. }
  53542. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53543. var extensionsUsed = data.json.extensionsUsed;
  53544. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  53545. return false;
  53546. }
  53547. this._bin = data.bin;
  53548. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53549. return true;
  53550. };
  53551. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53552. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  53553. return false;
  53554. }
  53555. if (id !== BinaryExtensionBufferName) {
  53556. return false;
  53557. }
  53558. onSuccess(this._bin);
  53559. return true;
  53560. };
  53561. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53562. var texture = gltfRuntime.textures[id];
  53563. var source = gltfRuntime.images[texture.source];
  53564. if (!source.extensions || !(this.name in source.extensions)) {
  53565. return false;
  53566. }
  53567. var sourceExt = source.extensions[this.name];
  53568. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  53569. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53570. onSuccess(buffer);
  53571. return true;
  53572. };
  53573. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53574. var shader = gltfRuntime.shaders[id];
  53575. if (!shader.extensions || !(this.name in shader.extensions)) {
  53576. return false;
  53577. }
  53578. var binaryExtensionShader = shader.extensions[this.name];
  53579. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  53580. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53581. setTimeout(function () {
  53582. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  53583. onSuccess(shaderString);
  53584. });
  53585. return true;
  53586. };
  53587. return GLTFBinaryExtension;
  53588. }(GLTF1.GLTFLoaderExtension));
  53589. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  53590. var BinaryReader = (function () {
  53591. function BinaryReader(arrayBuffer) {
  53592. this._arrayBuffer = arrayBuffer;
  53593. this._dataView = new DataView(arrayBuffer);
  53594. this._byteOffset = 0;
  53595. }
  53596. BinaryReader.prototype.getUint32 = function () {
  53597. var value = this._dataView.getUint32(this._byteOffset, true);
  53598. this._byteOffset += 4;
  53599. return value;
  53600. };
  53601. BinaryReader.prototype.getUint8Array = function (length) {
  53602. if (!length) {
  53603. length = this._arrayBuffer.byteLength - this._byteOffset;
  53604. }
  53605. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  53606. this._byteOffset += length;
  53607. return value;
  53608. };
  53609. return BinaryReader;
  53610. }());
  53611. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  53612. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53613. })(BABYLON || (BABYLON = {}));
  53614. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  53615. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53616. var BABYLON;
  53617. (function (BABYLON) {
  53618. var GLTF1;
  53619. (function (GLTF1) {
  53620. ;
  53621. ;
  53622. ;
  53623. var GLTFMaterialsCommonExtension = (function (_super) {
  53624. __extends(GLTFMaterialsCommonExtension, _super);
  53625. function GLTFMaterialsCommonExtension() {
  53626. return _super.call(this, "KHR_materials_common") || this;
  53627. }
  53628. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53629. if (!gltfRuntime.extensions)
  53630. return false;
  53631. var extension = gltfRuntime.extensions[this.name];
  53632. if (!extension)
  53633. return false;
  53634. // Create lights
  53635. var lights = extension.lights;
  53636. if (lights) {
  53637. for (var thing in lights) {
  53638. var light = lights[thing];
  53639. switch (light.type) {
  53640. case "ambient":
  53641. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  53642. var ambient = light.ambient;
  53643. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  53644. break;
  53645. case "point":
  53646. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  53647. var point = light.point;
  53648. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  53649. break;
  53650. case "directional":
  53651. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  53652. var directional = light.directional;
  53653. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  53654. break;
  53655. case "spot":
  53656. var spot = light.spot;
  53657. 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);
  53658. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  53659. break;
  53660. default:
  53661. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  53662. break;
  53663. }
  53664. }
  53665. }
  53666. return false;
  53667. };
  53668. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53669. var material = gltfRuntime.materials[id];
  53670. if (!material || !material.extensions)
  53671. return false;
  53672. var extension = material.extensions[this.name];
  53673. if (!extension)
  53674. return false;
  53675. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  53676. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53677. if (extension.technique === "CONSTANT") {
  53678. standardMaterial.disableLighting = true;
  53679. }
  53680. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  53681. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  53682. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  53683. // Ambient
  53684. if (typeof extension.values.ambient === "string") {
  53685. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  53686. }
  53687. else {
  53688. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  53689. }
  53690. // Diffuse
  53691. if (typeof extension.values.diffuse === "string") {
  53692. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  53693. }
  53694. else {
  53695. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  53696. }
  53697. // Emission
  53698. if (typeof extension.values.emission === "string") {
  53699. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  53700. }
  53701. else {
  53702. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  53703. }
  53704. // Specular
  53705. if (typeof extension.values.specular === "string") {
  53706. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  53707. }
  53708. else {
  53709. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  53710. }
  53711. return true;
  53712. };
  53713. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  53714. // Create buffer from texture url
  53715. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  53716. // Create texture from buffer
  53717. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  53718. }, onError);
  53719. };
  53720. return GLTFMaterialsCommonExtension;
  53721. }(GLTF1.GLTFLoaderExtension));
  53722. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  53723. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  53724. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53725. })(BABYLON || (BABYLON = {}));
  53726. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  53727. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53728. var BABYLON;
  53729. (function (BABYLON) {
  53730. var GLTF2;
  53731. (function (GLTF2) {
  53732. /**
  53733. * Enums
  53734. */
  53735. var EComponentType;
  53736. (function (EComponentType) {
  53737. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  53738. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  53739. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  53740. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  53741. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  53742. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  53743. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  53744. var EMeshPrimitiveMode;
  53745. (function (EMeshPrimitiveMode) {
  53746. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  53747. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  53748. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  53749. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  53750. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  53751. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  53752. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  53753. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  53754. var ETextureMagFilter;
  53755. (function (ETextureMagFilter) {
  53756. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  53757. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  53758. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  53759. var ETextureMinFilter;
  53760. (function (ETextureMinFilter) {
  53761. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  53762. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  53763. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  53764. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  53765. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  53766. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  53767. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  53768. var ETextureWrapMode;
  53769. (function (ETextureWrapMode) {
  53770. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  53771. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  53772. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  53773. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  53774. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53775. })(BABYLON || (BABYLON = {}));
  53776. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  53777. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53778. var BABYLON;
  53779. (function (BABYLON) {
  53780. var GLTF2;
  53781. (function (GLTF2) {
  53782. var GLTFLoader = (function () {
  53783. function GLTFLoader(parent) {
  53784. this._renderReady = false;
  53785. this._disposed = false;
  53786. this._objectURLs = new Array();
  53787. this._blockPendingTracking = false;
  53788. // Observable with boolean indicating success or error.
  53789. this._renderReadyObservable = new BABYLON.Observable();
  53790. // Count of pending work that needs to complete before the asset is rendered.
  53791. this._renderPendingCount = 0;
  53792. // Count of pending work that needs to complete before the loader is cleared.
  53793. this._loaderPendingCount = 0;
  53794. this._parent = parent;
  53795. }
  53796. GLTFLoader.RegisterExtension = function (extension) {
  53797. if (GLTFLoader.Extensions[extension.name]) {
  53798. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53799. return;
  53800. }
  53801. GLTFLoader.Extensions[extension.name] = extension;
  53802. // Keep the order of registration so that extensions registered first are called first.
  53803. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53804. };
  53805. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53806. get: function () {
  53807. return this._gltf;
  53808. },
  53809. enumerable: true,
  53810. configurable: true
  53811. });
  53812. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53813. get: function () {
  53814. return this._babylonScene;
  53815. },
  53816. enumerable: true,
  53817. configurable: true
  53818. });
  53819. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53820. if (this._renderReady) {
  53821. func();
  53822. }
  53823. else {
  53824. this._renderReadyObservable.add(func);
  53825. }
  53826. };
  53827. GLTFLoader.prototype.dispose = function () {
  53828. if (this._disposed) {
  53829. return;
  53830. }
  53831. this._disposed = true;
  53832. // Revoke object urls created during load
  53833. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53834. this._objectURLs.length = 0;
  53835. this._gltf = undefined;
  53836. this._babylonScene = undefined;
  53837. this._rootUrl = undefined;
  53838. this._defaultMaterial = undefined;
  53839. this._successCallback = undefined;
  53840. this._errorCallback = undefined;
  53841. this._renderReady = false;
  53842. this._renderReadyObservable.clear();
  53843. this._renderPendingCount = 0;
  53844. this._loaderPendingCount = 0;
  53845. };
  53846. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53847. var _this = this;
  53848. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53849. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53850. }, onProgress, onError);
  53851. };
  53852. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53853. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53854. };
  53855. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53856. this._loadData(data);
  53857. this._babylonScene = scene;
  53858. this._rootUrl = rootUrl;
  53859. this._successCallback = onSuccess;
  53860. this._progressCallback = onProgress;
  53861. this._errorCallback = onError;
  53862. this.addPendingData(this);
  53863. this._loadScene(nodeNames);
  53864. this._loadAnimations();
  53865. this.removePendingData(this);
  53866. };
  53867. GLTFLoader.prototype._onError = function (message) {
  53868. this._errorCallback(message);
  53869. this.dispose();
  53870. };
  53871. GLTFLoader.prototype._onProgress = function (event) {
  53872. this._progressCallback(event);
  53873. };
  53874. GLTFLoader.prototype._onRenderReady = function () {
  53875. switch (this._parent.coordinateSystemMode) {
  53876. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53877. if (!this._babylonScene.useRightHandedSystem) {
  53878. this._addRightHandToLeftHandRootTransform();
  53879. }
  53880. break;
  53881. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53882. // do nothing
  53883. break;
  53884. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53885. this._babylonScene.useRightHandedSystem = true;
  53886. break;
  53887. default:
  53888. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  53889. break;
  53890. }
  53891. this._showMeshes();
  53892. this._startAnimations();
  53893. this._successCallback();
  53894. this._renderReadyObservable.notifyObservers(this);
  53895. };
  53896. GLTFLoader.prototype._onLoaderComplete = function () {
  53897. if (this._parent.onComplete) {
  53898. this._parent.onComplete();
  53899. }
  53900. };
  53901. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  53902. if (this._parent.onFirstLODComplete) {
  53903. this._parent.onFirstLODComplete();
  53904. }
  53905. };
  53906. GLTFLoader.prototype._loadData = function (data) {
  53907. this._gltf = data.json;
  53908. var binaryBuffer;
  53909. var buffers = this._gltf.buffers;
  53910. if (buffers.length > 0 && buffers[0].uri === undefined) {
  53911. binaryBuffer = buffers[0];
  53912. }
  53913. if (data.bin) {
  53914. if (binaryBuffer) {
  53915. if (binaryBuffer.byteLength != data.bin.byteLength) {
  53916. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  53917. }
  53918. }
  53919. else {
  53920. BABYLON.Tools.Warn("Unexpected BIN chunk");
  53921. }
  53922. binaryBuffer.loadedData = data.bin;
  53923. }
  53924. };
  53925. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  53926. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  53927. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  53928. rootMesh.rotation.y = Math.PI;
  53929. var nodes = this._gltf.nodes;
  53930. for (var i = 0; i < nodes.length; i++) {
  53931. var mesh = nodes[i].babylonMesh;
  53932. if (mesh && !mesh.parent) {
  53933. mesh.parent = rootMesh;
  53934. }
  53935. }
  53936. };
  53937. GLTFLoader.prototype._getMeshes = function () {
  53938. var meshes = [];
  53939. var nodes = this._gltf.nodes;
  53940. if (nodes) {
  53941. nodes.forEach(function (node) {
  53942. if (node.babylonMesh) {
  53943. meshes.push(node.babylonMesh);
  53944. }
  53945. });
  53946. }
  53947. return meshes;
  53948. };
  53949. GLTFLoader.prototype._getSkeletons = function () {
  53950. var skeletons = [];
  53951. var skins = this._gltf.skins;
  53952. if (skins) {
  53953. skins.forEach(function (skin) {
  53954. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53955. skeletons.push(skin.babylonSkeleton);
  53956. }
  53957. });
  53958. }
  53959. return skeletons;
  53960. };
  53961. GLTFLoader.prototype._getAnimationTargets = function () {
  53962. var targets = [];
  53963. var animations = this._gltf.animations;
  53964. if (animations) {
  53965. animations.forEach(function (animation) {
  53966. targets.push.apply(targets, animation.targets);
  53967. });
  53968. }
  53969. return targets;
  53970. };
  53971. GLTFLoader.prototype._showMeshes = function () {
  53972. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  53973. };
  53974. GLTFLoader.prototype._startAnimations = function () {
  53975. var _this = this;
  53976. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  53977. };
  53978. GLTFLoader.prototype._loadScene = function (nodeNames) {
  53979. var _this = this;
  53980. var scene = this._gltf.scenes[this._gltf.scene || 0];
  53981. var nodeIndices = scene.nodes;
  53982. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  53983. node.index = index;
  53984. node.parent = parentNode;
  53985. return true;
  53986. });
  53987. var materials = this._gltf.materials;
  53988. if (materials) {
  53989. materials.forEach(function (material, index) { return material.index = index; });
  53990. }
  53991. if (nodeNames) {
  53992. if (!(nodeNames instanceof Array)) {
  53993. nodeNames = [nodeNames];
  53994. }
  53995. var filteredNodeIndices = new Array();
  53996. this._traverseNodes(nodeIndices, function (node) {
  53997. if (nodeNames.indexOf(node.name) === -1) {
  53998. return true;
  53999. }
  54000. filteredNodeIndices.push(node.index);
  54001. return false;
  54002. });
  54003. nodeIndices = filteredNodeIndices;
  54004. }
  54005. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  54006. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  54007. };
  54008. GLTFLoader.prototype._loadSkin = function (node) {
  54009. var _this = this;
  54010. if (node.skin !== undefined) {
  54011. var skin = this._gltf.skins[node.skin];
  54012. var skeletonId = "skeleton" + node.skin;
  54013. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  54014. skin.index = node.skin;
  54015. for (var i = 0; i < skin.joints.length; i++) {
  54016. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  54017. }
  54018. if (skin.skeleton === undefined) {
  54019. // TODO: handle when skeleton is not defined
  54020. throw new Error("Not implemented");
  54021. }
  54022. if (skin.inverseBindMatrices === undefined) {
  54023. // TODO: handle when inverse bind matrices are not defined
  54024. throw new Error("Not implemented");
  54025. }
  54026. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  54027. this._loadAccessorAsync(accessor, function (data) {
  54028. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  54029. });
  54030. }
  54031. return true;
  54032. };
  54033. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  54034. var jointIndex = skin.joints.indexOf(node.index);
  54035. if (jointIndex === -1) {
  54036. this._createBone(node, skin);
  54037. }
  54038. var babylonBone = node.babylonSkinToBones[skin.index];
  54039. // TODO: explain the math
  54040. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  54041. matrix.invertToRef(matrix);
  54042. if (parentNode) {
  54043. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  54044. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  54045. }
  54046. babylonBone.updateMatrix(matrix);
  54047. return true;
  54048. };
  54049. GLTFLoader.prototype._createBone = function (node, skin) {
  54050. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  54051. node.babylonSkinToBones = node.babylonSkinToBones || {};
  54052. node.babylonSkinToBones[skin.index] = babylonBone;
  54053. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54054. node.babylonAnimationTargets.push(babylonBone);
  54055. return babylonBone;
  54056. };
  54057. GLTFLoader.prototype._loadMesh = function (node) {
  54058. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  54059. babylonMesh.isVisible = false;
  54060. this._loadTransform(node, babylonMesh);
  54061. if (node.mesh !== undefined) {
  54062. var mesh = this._gltf.meshes[node.mesh];
  54063. this._loadMeshData(node, mesh, babylonMesh);
  54064. }
  54065. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  54066. node.babylonMesh = babylonMesh;
  54067. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54068. node.babylonAnimationTargets.push(node.babylonMesh);
  54069. if (node.skin !== undefined) {
  54070. var skin = this._gltf.skins[node.skin];
  54071. babylonMesh.skeleton = skin.babylonSkeleton;
  54072. }
  54073. if (node.camera !== undefined) {
  54074. // TODO: handle cameras
  54075. }
  54076. return true;
  54077. };
  54078. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  54079. var _this = this;
  54080. babylonMesh.name = mesh.name || babylonMesh.name;
  54081. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  54082. babylonMesh.material = babylonMultiMaterial;
  54083. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  54084. var vertexData = new BABYLON.VertexData();
  54085. vertexData.positions = [];
  54086. vertexData.indices = [];
  54087. var subMeshInfos = [];
  54088. var loadedPrimitives = 0;
  54089. var totalPrimitives = mesh.primitives.length;
  54090. var _loop_1 = function (i) {
  54091. var primitive = mesh.primitives[i];
  54092. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  54093. // TODO: handle other primitive modes
  54094. throw new Error("Not implemented");
  54095. }
  54096. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  54097. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  54098. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  54099. subMeshInfos.push({
  54100. materialIndex: i,
  54101. verticesStart: vertexData.positions.length,
  54102. verticesCount: subVertexData.positions.length,
  54103. indicesStart: vertexData.indices.length,
  54104. indicesCount: subVertexData.indices.length,
  54105. loadMaterial: function () {
  54106. if (primitive.material === undefined) {
  54107. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  54108. }
  54109. else {
  54110. var material = _this._gltf.materials[primitive.material];
  54111. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  54112. if (isNew && _this._parent.onMaterialLoaded) {
  54113. _this._parent.onMaterialLoaded(babylonMaterial);
  54114. }
  54115. if (_this._parent.onBeforeMaterialReadyAsync) {
  54116. _this.addLoaderPendingData(material);
  54117. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  54118. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54119. _this.removeLoaderPendingData(material);
  54120. });
  54121. }
  54122. else {
  54123. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54124. }
  54125. });
  54126. }
  54127. }
  54128. });
  54129. vertexData.merge(subVertexData);
  54130. if (++loadedPrimitives === totalPrimitives) {
  54131. geometry.setAllVerticesData(vertexData, false);
  54132. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  54133. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  54134. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  54135. babylonMesh.subMeshes = [];
  54136. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  54137. }
  54138. });
  54139. };
  54140. var this_1 = this;
  54141. for (var i = 0; i < totalPrimitives; i++) {
  54142. _loop_1(i);
  54143. }
  54144. };
  54145. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  54146. var _this = this;
  54147. var attributes = primitive.attributes;
  54148. if (!attributes) {
  54149. this._onError("Primitive has no attributes");
  54150. return;
  54151. }
  54152. var vertexData = new BABYLON.VertexData();
  54153. var loadedAttributes = 0;
  54154. var totalAttributes = Object.keys(attributes).length;
  54155. var _loop_2 = function (semantic) {
  54156. accessor = this_2._gltf.accessors[attributes[semantic]];
  54157. this_2._loadAccessorAsync(accessor, function (data) {
  54158. switch (semantic) {
  54159. case "NORMAL":
  54160. vertexData.normals = data;
  54161. break;
  54162. case "POSITION":
  54163. vertexData.positions = data;
  54164. break;
  54165. case "TANGENT":
  54166. vertexData.tangents = data;
  54167. break;
  54168. case "TEXCOORD_0":
  54169. vertexData.uvs = data;
  54170. break;
  54171. case "TEXCOORD_1":
  54172. vertexData.uvs2 = data;
  54173. break;
  54174. case "JOINTS_0":
  54175. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  54176. break;
  54177. case "WEIGHTS_0":
  54178. vertexData.matricesWeights = data;
  54179. break;
  54180. case "COLOR_0":
  54181. vertexData.colors = data;
  54182. break;
  54183. default:
  54184. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54185. break;
  54186. }
  54187. if (++loadedAttributes === totalAttributes) {
  54188. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  54189. if (indicesAccessor) {
  54190. _this._loadAccessorAsync(indicesAccessor, function (data) {
  54191. vertexData.indices = data;
  54192. onSuccess(vertexData);
  54193. });
  54194. }
  54195. else {
  54196. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  54197. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  54198. onSuccess(vertexData);
  54199. }
  54200. }
  54201. });
  54202. };
  54203. var this_2 = this, accessor;
  54204. for (var semantic in attributes) {
  54205. _loop_2(semantic);
  54206. }
  54207. };
  54208. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  54209. var targets = primitive.targets;
  54210. if (!targets) {
  54211. return;
  54212. }
  54213. if (!babylonMesh.morphTargetManager) {
  54214. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  54215. }
  54216. for (var index = 0; index < targets.length; index++) {
  54217. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  54218. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  54219. }
  54220. };
  54221. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  54222. var targets = primitive.targets;
  54223. if (!targets) {
  54224. return;
  54225. }
  54226. var _loop_3 = function () {
  54227. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  54228. attributes = targets[index];
  54229. var _loop_4 = function (semantic) {
  54230. accessor = this_3._gltf.accessors[attributes[semantic]];
  54231. this_3._loadAccessorAsync(accessor, function (data) {
  54232. if (accessor.name) {
  54233. babylonMorphTarget.name = accessor.name;
  54234. }
  54235. // glTF stores morph target information as deltas while babylon.js expects the final data.
  54236. // As a result we have to add the original data to the delta to calculate the final data.
  54237. var values = data;
  54238. switch (semantic) {
  54239. case "NORMAL":
  54240. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  54241. babylonMorphTarget.setNormals(values);
  54242. break;
  54243. case "POSITION":
  54244. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  54245. babylonMorphTarget.setPositions(values);
  54246. break;
  54247. case "TANGENT":
  54248. // Tangent data for morph targets is stored as xyz delta.
  54249. // The vertexData.tangent is stored as xyzw.
  54250. // So we need to skip every fourth vertexData.tangent.
  54251. for (var i = 0, j = 0; i < values.length; i++, j++) {
  54252. values[i] += vertexData.tangents[j];
  54253. if ((i + 1) % 3 == 0) {
  54254. j++;
  54255. }
  54256. }
  54257. babylonMorphTarget.setTangents(values);
  54258. break;
  54259. default:
  54260. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54261. break;
  54262. }
  54263. });
  54264. };
  54265. for (var semantic in attributes) {
  54266. _loop_4(semantic);
  54267. }
  54268. };
  54269. var this_3 = this, attributes, accessor;
  54270. for (var index = 0; index < targets.length; index++) {
  54271. _loop_3();
  54272. }
  54273. };
  54274. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  54275. var position = BABYLON.Vector3.Zero();
  54276. var rotation = BABYLON.Quaternion.Identity();
  54277. var scaling = BABYLON.Vector3.One();
  54278. if (node.matrix) {
  54279. var mat = BABYLON.Matrix.FromArray(node.matrix);
  54280. mat.decompose(scaling, rotation, position);
  54281. }
  54282. else {
  54283. if (node.translation)
  54284. position = BABYLON.Vector3.FromArray(node.translation);
  54285. if (node.rotation)
  54286. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  54287. if (node.scale)
  54288. scaling = BABYLON.Vector3.FromArray(node.scale);
  54289. }
  54290. babylonMesh.position = position;
  54291. babylonMesh.rotationQuaternion = rotation;
  54292. babylonMesh.scaling = scaling;
  54293. };
  54294. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  54295. if (parentNode === void 0) { parentNode = null; }
  54296. for (var i = 0; i < indices.length; i++) {
  54297. this._traverseNode(indices[i], action, parentNode);
  54298. }
  54299. };
  54300. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  54301. if (parentNode === void 0) { parentNode = null; }
  54302. var node = this._gltf.nodes[index];
  54303. if (!action(node, index, parentNode)) {
  54304. return;
  54305. }
  54306. if (node.children) {
  54307. for (var i = 0; i < node.children.length; i++) {
  54308. this._traverseNode(node.children[i], action, node);
  54309. }
  54310. }
  54311. };
  54312. GLTFLoader.prototype._loadAnimations = function () {
  54313. var animations = this._gltf.animations;
  54314. if (!animations || animations.length === 0) {
  54315. return;
  54316. }
  54317. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  54318. var animation = animations[animationIndex];
  54319. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  54320. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  54321. }
  54322. }
  54323. };
  54324. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  54325. var channel = animation.channels[channelIndex];
  54326. var samplerIndex = channel.sampler;
  54327. var sampler = animation.samplers[samplerIndex];
  54328. var targetNode = this._gltf.nodes[channel.target.node];
  54329. if (!targetNode) {
  54330. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  54331. return;
  54332. }
  54333. var targetPath = {
  54334. "translation": "position",
  54335. "rotation": "rotationQuaternion",
  54336. "scale": "scaling",
  54337. "weights": "influence"
  54338. }[channel.target.path];
  54339. if (!targetPath) {
  54340. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  54341. return;
  54342. }
  54343. var animationType = {
  54344. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54345. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  54346. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54347. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  54348. }[targetPath];
  54349. var inputData;
  54350. var outputData;
  54351. var checkSuccess = function () {
  54352. if (!inputData || !outputData) {
  54353. return;
  54354. }
  54355. var outputBufferOffset = 0;
  54356. var getNextOutputValue = {
  54357. "position": function () {
  54358. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54359. outputBufferOffset += 3;
  54360. return value;
  54361. },
  54362. "rotationQuaternion": function () {
  54363. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  54364. outputBufferOffset += 4;
  54365. return value;
  54366. },
  54367. "scaling": function () {
  54368. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54369. outputBufferOffset += 3;
  54370. return value;
  54371. },
  54372. "influence": function () {
  54373. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  54374. var value = new Array(numTargets);
  54375. for (var i = 0; i < numTargets; i++) {
  54376. value[i] = outputData[outputBufferOffset++];
  54377. }
  54378. return value;
  54379. },
  54380. }[targetPath];
  54381. var getNextKey = {
  54382. "LINEAR": function (frameIndex) { return ({
  54383. frame: inputData[frameIndex],
  54384. value: getNextOutputValue()
  54385. }); },
  54386. "CUBICSPLINE": function (frameIndex) { return ({
  54387. frame: inputData[frameIndex],
  54388. inTangent: getNextOutputValue(),
  54389. value: getNextOutputValue(),
  54390. outTangent: getNextOutputValue()
  54391. }); },
  54392. }[sampler.interpolation];
  54393. var keys = new Array(inputData.length);
  54394. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  54395. keys[frameIndex] = getNextKey(frameIndex);
  54396. }
  54397. animation.targets = animation.targets || [];
  54398. if (targetPath === "influence") {
  54399. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  54400. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  54401. var morphTarget = morphTargetManager.getTarget(targetIndex);
  54402. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  54403. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54404. babylonAnimation.setKeys(keys.map(function (key) { return ({
  54405. frame: key.frame,
  54406. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  54407. value: key.value[targetIndex],
  54408. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  54409. }); }));
  54410. morphTarget.animations.push(babylonAnimation);
  54411. animation.targets.push(morphTarget);
  54412. }
  54413. }
  54414. else {
  54415. var animationName = animation.name || "anim" + animationIndex;
  54416. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54417. babylonAnimation.setKeys(keys);
  54418. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  54419. var target = targetNode.babylonAnimationTargets[i];
  54420. target.animations.push(babylonAnimation.clone());
  54421. animation.targets.push(target);
  54422. }
  54423. }
  54424. };
  54425. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  54426. inputData = data;
  54427. checkSuccess();
  54428. });
  54429. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  54430. outputData = data;
  54431. checkSuccess();
  54432. });
  54433. };
  54434. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  54435. var _this = this;
  54436. var buffer = this._gltf.buffers[index];
  54437. this.addPendingData(buffer);
  54438. if (buffer.loadedData) {
  54439. setTimeout(function () {
  54440. onSuccess(buffer.loadedData);
  54441. _this.removePendingData(buffer);
  54442. });
  54443. }
  54444. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  54445. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  54446. buffer.loadedData = new Uint8Array(data);
  54447. setTimeout(function () {
  54448. onSuccess(buffer.loadedData);
  54449. _this.removePendingData(buffer);
  54450. });
  54451. }
  54452. else if (buffer.loadedObservable) {
  54453. buffer.loadedObservable.add(function (buffer) {
  54454. onSuccess(buffer.loadedData);
  54455. _this.removePendingData(buffer);
  54456. });
  54457. }
  54458. else {
  54459. buffer.loadedObservable = new BABYLON.Observable();
  54460. buffer.loadedObservable.add(function (buffer) {
  54461. onSuccess(buffer.loadedData);
  54462. _this.removePendingData(buffer);
  54463. });
  54464. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  54465. buffer.loadedData = new Uint8Array(data);
  54466. buffer.loadedObservable.notifyObservers(buffer);
  54467. buffer.loadedObservable = null;
  54468. }, function (event) {
  54469. if (!_this._disposed) {
  54470. _this._onProgress(event);
  54471. }
  54472. }, this._babylonScene.database, true, function (request) {
  54473. if (!_this._disposed) {
  54474. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  54475. _this.removePendingData(buffer);
  54476. }
  54477. });
  54478. }
  54479. };
  54480. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  54481. var _this = this;
  54482. byteOffset += (bufferView.byteOffset || 0);
  54483. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  54484. if (byteOffset + byteLength > bufferData.byteLength) {
  54485. _this._onError("Buffer access is out of range");
  54486. return;
  54487. }
  54488. var buffer = bufferData.buffer;
  54489. byteOffset += bufferData.byteOffset;
  54490. var bufferViewData;
  54491. switch (componentType) {
  54492. case GLTF2.EComponentType.BYTE:
  54493. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  54494. break;
  54495. case GLTF2.EComponentType.UNSIGNED_BYTE:
  54496. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  54497. break;
  54498. case GLTF2.EComponentType.SHORT:
  54499. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  54500. break;
  54501. case GLTF2.EComponentType.UNSIGNED_SHORT:
  54502. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  54503. break;
  54504. case GLTF2.EComponentType.UNSIGNED_INT:
  54505. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  54506. break;
  54507. case GLTF2.EComponentType.FLOAT:
  54508. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  54509. break;
  54510. default:
  54511. _this._onError("Invalid component type (" + componentType + ")");
  54512. return;
  54513. }
  54514. onSuccess(bufferViewData);
  54515. });
  54516. };
  54517. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  54518. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  54519. var byteOffset = accessor.byteOffset || 0;
  54520. var byteLength = accessor.count * this._getByteStrideFromType(accessor);
  54521. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  54522. };
  54523. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  54524. switch (accessor.type) {
  54525. case "SCALAR": return 1;
  54526. case "VEC2": return 2;
  54527. case "VEC3": return 3;
  54528. case "VEC4": return 4;
  54529. case "MAT2": return 4;
  54530. case "MAT3": return 9;
  54531. case "MAT4": return 16;
  54532. default:
  54533. this._onError("Invalid accessor type (" + accessor.type + ")");
  54534. return 0;
  54535. }
  54536. };
  54537. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  54538. set: function (value) {
  54539. this._blockPendingTracking = value;
  54540. },
  54541. enumerable: true,
  54542. configurable: true
  54543. });
  54544. GLTFLoader.prototype.addPendingData = function (data) {
  54545. if (!this._renderReady) {
  54546. this._renderPendingCount++;
  54547. }
  54548. this.addLoaderPendingData(data);
  54549. };
  54550. GLTFLoader.prototype.removePendingData = function (data) {
  54551. if (!this._renderReady) {
  54552. if (--this._renderPendingCount === 0) {
  54553. this._renderReady = true;
  54554. this._onRenderReady();
  54555. }
  54556. }
  54557. this.removeLoaderPendingData(data);
  54558. };
  54559. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  54560. if (!this._nonBlockingData) {
  54561. this._nonBlockingData = new Array();
  54562. }
  54563. this._nonBlockingData.push(data);
  54564. };
  54565. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  54566. if (this._blockPendingTracking) {
  54567. this.addLoaderNonBlockingPendingData(data);
  54568. return;
  54569. }
  54570. this._loaderPendingCount++;
  54571. };
  54572. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  54573. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  54574. if (indexInPending !== -1) {
  54575. this._nonBlockingData.splice(indexInPending, 1);
  54576. }
  54577. else if (--this._loaderPendingCount === 0) {
  54578. this._onLoaderFirstLODComplete();
  54579. }
  54580. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  54581. this._onLoaderComplete();
  54582. this.dispose();
  54583. }
  54584. };
  54585. GLTFLoader.prototype._getDefaultMaterial = function () {
  54586. if (!this._defaultMaterial) {
  54587. var id = "__gltf_default";
  54588. var material = this._babylonScene.getMaterialByName(id);
  54589. if (!material) {
  54590. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  54591. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54592. material.metallic = 1;
  54593. material.roughness = 1;
  54594. }
  54595. this._defaultMaterial = material;
  54596. }
  54597. return this._defaultMaterial;
  54598. };
  54599. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  54600. var babylonMaterial = material.babylonMaterial;
  54601. // Ensure metallic workflow
  54602. babylonMaterial.metallic = 1;
  54603. babylonMaterial.roughness = 1;
  54604. var properties = material.pbrMetallicRoughness;
  54605. if (!properties) {
  54606. return;
  54607. }
  54608. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  54609. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  54610. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  54611. if (properties.baseColorTexture) {
  54612. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  54613. }
  54614. if (properties.metallicRoughnessTexture) {
  54615. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  54616. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  54617. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  54618. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  54619. }
  54620. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  54621. };
  54622. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  54623. if (material.babylonMaterial) {
  54624. assign(material.babylonMaterial, false);
  54625. return;
  54626. }
  54627. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  54628. return;
  54629. }
  54630. this.createPbrMaterial(material);
  54631. this.loadMaterialBaseProperties(material);
  54632. this._loadMaterialMetallicRoughnessProperties(material);
  54633. assign(material.babylonMaterial, true);
  54634. };
  54635. GLTFLoader.prototype.createPbrMaterial = function (material) {
  54636. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  54637. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54638. material.babylonMaterial = babylonMaterial;
  54639. };
  54640. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  54641. var babylonMaterial = material.babylonMaterial;
  54642. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  54643. if (material.doubleSided) {
  54644. babylonMaterial.backFaceCulling = false;
  54645. babylonMaterial.twoSidedLighting = true;
  54646. }
  54647. if (material.normalTexture) {
  54648. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  54649. babylonMaterial.invertNormalMapX = true;
  54650. babylonMaterial.invertNormalMapY = false;
  54651. if (material.normalTexture.scale !== undefined) {
  54652. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  54653. }
  54654. }
  54655. if (material.occlusionTexture) {
  54656. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  54657. babylonMaterial.useAmbientInGrayScale = true;
  54658. if (material.occlusionTexture.strength !== undefined) {
  54659. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  54660. }
  54661. }
  54662. if (material.emissiveTexture) {
  54663. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  54664. }
  54665. };
  54666. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  54667. var babylonMaterial = material.babylonMaterial;
  54668. var alphaMode = material.alphaMode || "OPAQUE";
  54669. switch (alphaMode) {
  54670. case "OPAQUE":
  54671. // default is opaque
  54672. break;
  54673. case "MASK":
  54674. case "BLEND":
  54675. if (colorFactor) {
  54676. babylonMaterial.alpha = colorFactor[3];
  54677. }
  54678. if (babylonMaterial.albedoTexture) {
  54679. babylonMaterial.albedoTexture.hasAlpha = true;
  54680. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  54681. }
  54682. break;
  54683. default:
  54684. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  54685. break;
  54686. }
  54687. };
  54688. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  54689. var _this = this;
  54690. var texture = this._gltf.textures[textureInfo.index];
  54691. var texCoord = textureInfo.texCoord || 0;
  54692. if (!texture || texture.source === undefined) {
  54693. return null;
  54694. }
  54695. // check the cache first
  54696. var babylonTexture;
  54697. if (texture.babylonTextures) {
  54698. babylonTexture = texture.babylonTextures[texCoord];
  54699. if (!babylonTexture) {
  54700. for (var i = 0; i < texture.babylonTextures.length; i++) {
  54701. babylonTexture = texture.babylonTextures[i];
  54702. if (babylonTexture) {
  54703. babylonTexture = babylonTexture.clone();
  54704. babylonTexture.coordinatesIndex = texCoord;
  54705. break;
  54706. }
  54707. }
  54708. }
  54709. return babylonTexture;
  54710. }
  54711. var source = this._gltf.images[texture.source];
  54712. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  54713. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  54714. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  54715. this.addPendingData(texture);
  54716. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  54717. if (!_this._disposed) {
  54718. _this.removePendingData(texture);
  54719. }
  54720. }, function () {
  54721. if (!_this._disposed) {
  54722. _this._onError("Failed to load texture '" + source.uri + "'");
  54723. _this.removePendingData(texture);
  54724. }
  54725. });
  54726. var setTextureData = function (data) {
  54727. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  54728. _this._objectURLs.push(url);
  54729. babylonTexture.updateURL(url);
  54730. };
  54731. if (!source.uri) {
  54732. var bufferView = this._gltf.bufferViews[source.bufferView];
  54733. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  54734. }
  54735. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  54736. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  54737. }
  54738. else {
  54739. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  54740. if (!_this._disposed) {
  54741. _this._onProgress(event);
  54742. }
  54743. }, this._babylonScene.database, true, function (request) {
  54744. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  54745. });
  54746. }
  54747. babylonTexture.coordinatesIndex = texCoord;
  54748. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  54749. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  54750. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  54751. // Cache the texture
  54752. texture.babylonTextures = texture.babylonTextures || [];
  54753. texture.babylonTextures[texCoord] = babylonTexture;
  54754. if (this._parent.onTextureLoaded) {
  54755. this._parent.onTextureLoaded(babylonTexture);
  54756. }
  54757. return babylonTexture;
  54758. };
  54759. GLTFLoader.Extensions = {};
  54760. return GLTFLoader;
  54761. }());
  54762. GLTF2.GLTFLoader = GLTFLoader;
  54763. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  54764. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54765. })(BABYLON || (BABYLON = {}));
  54766. //# sourceMappingURL=babylon.glTFLoader.js.map
  54767. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54768. var BABYLON;
  54769. (function (BABYLON) {
  54770. var GLTF2;
  54771. (function (GLTF2) {
  54772. /**
  54773. * Utils functions for GLTF
  54774. */
  54775. var GLTFUtils = (function () {
  54776. function GLTFUtils() {
  54777. }
  54778. /**
  54779. * If the uri is a base64 string
  54780. * @param uri: the uri to test
  54781. */
  54782. GLTFUtils.IsBase64 = function (uri) {
  54783. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54784. };
  54785. /**
  54786. * Decode the base64 uri
  54787. * @param uri: the uri to decode
  54788. */
  54789. GLTFUtils.DecodeBase64 = function (uri) {
  54790. var decodedString = atob(uri.split(",")[1]);
  54791. var bufferLength = decodedString.length;
  54792. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54793. for (var i = 0; i < bufferLength; i++) {
  54794. bufferView[i] = decodedString.charCodeAt(i);
  54795. }
  54796. return bufferView.buffer;
  54797. };
  54798. GLTFUtils.ForEach = function (view, func) {
  54799. for (var index = 0; index < view.length; index++) {
  54800. func(view[index], index);
  54801. }
  54802. };
  54803. GLTFUtils.GetTextureWrapMode = function (mode) {
  54804. // Set defaults if undefined
  54805. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54806. switch (mode) {
  54807. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  54808. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54809. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54810. default:
  54811. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54812. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54813. }
  54814. };
  54815. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54816. // Set defaults if undefined
  54817. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54818. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54819. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  54820. switch (minFilter) {
  54821. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  54822. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  54823. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  54824. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  54825. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  54826. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54827. default:
  54828. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54829. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54830. }
  54831. }
  54832. else {
  54833. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  54834. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  54835. }
  54836. switch (minFilter) {
  54837. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  54838. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  54839. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54840. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  54841. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  54842. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  54843. default:
  54844. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54845. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54846. }
  54847. }
  54848. };
  54849. /**
  54850. * Decodes a buffer view into a string
  54851. * @param view: the buffer view
  54852. */
  54853. GLTFUtils.DecodeBufferToText = function (view) {
  54854. var result = "";
  54855. var length = view.byteLength;
  54856. for (var i = 0; i < length; ++i) {
  54857. result += String.fromCharCode(view[i]);
  54858. }
  54859. return result;
  54860. };
  54861. return GLTFUtils;
  54862. }());
  54863. GLTF2.GLTFUtils = GLTFUtils;
  54864. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54865. })(BABYLON || (BABYLON = {}));
  54866. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  54867. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54868. var BABYLON;
  54869. (function (BABYLON) {
  54870. var GLTF2;
  54871. (function (GLTF2) {
  54872. var GLTFLoaderExtension = (function () {
  54873. function GLTFLoaderExtension() {
  54874. this.enabled = true;
  54875. }
  54876. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  54877. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  54878. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  54879. };
  54880. GLTFLoaderExtension._ApplyExtensions = function (action) {
  54881. var extensions = GLTFLoaderExtension._Extensions;
  54882. if (!extensions) {
  54883. return;
  54884. }
  54885. for (var i = 0; i < extensions.length; i++) {
  54886. var extension = extensions[i];
  54887. if (extension.enabled && action(extension)) {
  54888. return true;
  54889. }
  54890. }
  54891. return false;
  54892. };
  54893. //
  54894. // Utilities
  54895. //
  54896. GLTFLoaderExtension._Extensions = [];
  54897. return GLTFLoaderExtension;
  54898. }());
  54899. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  54900. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54901. })(BABYLON || (BABYLON = {}));
  54902. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  54903. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54904. var BABYLON;
  54905. (function (BABYLON) {
  54906. var GLTF2;
  54907. (function (GLTF2) {
  54908. var Extensions;
  54909. (function (Extensions) {
  54910. var MSFTLOD = (function (_super) {
  54911. __extends(MSFTLOD, _super);
  54912. function MSFTLOD() {
  54913. return _super !== null && _super.apply(this, arguments) || this;
  54914. }
  54915. Object.defineProperty(MSFTLOD.prototype, "name", {
  54916. get: function () {
  54917. return "MSFT_lod";
  54918. },
  54919. enumerable: true,
  54920. configurable: true
  54921. });
  54922. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  54923. if (!material.extensions) {
  54924. return false;
  54925. }
  54926. var properties = material.extensions[this.name];
  54927. if (!properties) {
  54928. return false;
  54929. }
  54930. // Clear out the extension so that it won't get loaded again.
  54931. material.extensions[this.name] = undefined;
  54932. // Tell the loader not to clear its state until the highest LOD is loaded.
  54933. var materialLODs = [material.index].concat(properties.ids);
  54934. loader.addLoaderPendingData(material);
  54935. for (var index = 0; index < materialLODs.length; index++) {
  54936. loader.addLoaderNonBlockingPendingData(index);
  54937. }
  54938. // Start with the lowest quality LOD.
  54939. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  54940. return true;
  54941. };
  54942. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  54943. var _this = this;
  54944. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  54945. if (lod !== materialLODs.length - 1) {
  54946. loader.blockPendingTracking = true;
  54947. }
  54948. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  54949. assign(babylonMaterial, isNew);
  54950. loader.removeLoaderPendingData(lod);
  54951. // Loading is considered complete if this is the lowest quality LOD.
  54952. if (lod === materialLODs.length - 1) {
  54953. loader.removeLoaderPendingData(material);
  54954. }
  54955. if (lod === 0) {
  54956. loader.blockPendingTracking = false;
  54957. return;
  54958. }
  54959. // Load the next LOD when the loader is ready to render and
  54960. // all active material textures of the current LOD are loaded.
  54961. loader.executeWhenRenderReady(function () {
  54962. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  54963. setTimeout(function () {
  54964. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  54965. }, MSFTLOD.MinimalLODDelay);
  54966. });
  54967. });
  54968. });
  54969. };
  54970. /**
  54971. * Specify the minimal delay between LODs in ms (default = 250)
  54972. */
  54973. MSFTLOD.MinimalLODDelay = 250;
  54974. return MSFTLOD;
  54975. }(GLTF2.GLTFLoaderExtension));
  54976. Extensions.MSFTLOD = MSFTLOD;
  54977. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  54978. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54979. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54980. })(BABYLON || (BABYLON = {}));
  54981. //# sourceMappingURL=MSFT_lod.js.map
  54982. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54983. var BABYLON;
  54984. (function (BABYLON) {
  54985. var GLTF2;
  54986. (function (GLTF2) {
  54987. var Extensions;
  54988. (function (Extensions) {
  54989. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  54990. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  54991. function KHRMaterialsPbrSpecularGlossiness() {
  54992. return _super !== null && _super.apply(this, arguments) || this;
  54993. }
  54994. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  54995. get: function () {
  54996. return "KHR_materials_pbrSpecularGlossiness";
  54997. },
  54998. enumerable: true,
  54999. configurable: true
  55000. });
  55001. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  55002. if (!material.extensions) {
  55003. return false;
  55004. }
  55005. var properties = material.extensions[this.name];
  55006. if (!properties) {
  55007. return false;
  55008. }
  55009. loader.createPbrMaterial(material);
  55010. loader.loadMaterialBaseProperties(material);
  55011. this._loadSpecularGlossinessProperties(loader, material, properties);
  55012. assign(material.babylonMaterial, true);
  55013. return true;
  55014. };
  55015. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  55016. var babylonMaterial = material.babylonMaterial;
  55017. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  55018. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  55019. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  55020. if (properties.diffuseTexture) {
  55021. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  55022. loader.loadMaterialAlphaProperties(material);
  55023. }
  55024. if (properties.specularGlossinessTexture) {
  55025. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  55026. babylonMaterial.reflectivityTexture.hasAlpha = true;
  55027. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  55028. }
  55029. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  55030. };
  55031. return KHRMaterialsPbrSpecularGlossiness;
  55032. }(GLTF2.GLTFLoaderExtension));
  55033. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  55034. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  55035. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55036. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55037. })(BABYLON || (BABYLON = {}));
  55038. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  55039. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55040. module.exports = BABYLON;
  55041. };