babylon.max.js 3.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * 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".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * 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".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. 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);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = 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 as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. 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. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. 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]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. 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]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. 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);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. 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);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. 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);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. 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);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. 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);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * 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".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * 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".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. 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);
  3500. };
  3501. /**
  3502. * 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".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * 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".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. 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);
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. 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);
  3554. };
  3555. /**
  3556. * 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.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. 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);
  3576. };
  3577. /**
  3578. * 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.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * 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.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. 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);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * 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.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. 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);
  3627. };
  3628. /**
  3629. * 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.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. 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);
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. 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);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. 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);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * 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.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. 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)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. 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;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. 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)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback, targetKey) {
  4743. return function (target, propertyKey) {
  4744. var key = targetKey || ("_" + propertyKey);
  4745. Object.defineProperty(target, propertyKey, {
  4746. get: function () {
  4747. return this[key];
  4748. },
  4749. set: function (value) {
  4750. if (this[key] === value) {
  4751. return;
  4752. }
  4753. this[key] = value;
  4754. if (setCallback) {
  4755. target[setCallback].apply(this);
  4756. }
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. };
  4762. }
  4763. function expandToProperty(callback, targetKey) {
  4764. return generateExpandMember(callback, targetKey);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. if (BABYLON.Tags) {
  4808. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4809. }
  4810. // Properties
  4811. for (var property in entity.__serializableMembers) {
  4812. var propertyDescriptor = entity.__serializableMembers[property];
  4813. var targetPropertyName = propertyDescriptor.sourceName || property;
  4814. var propertyType = propertyDescriptor.type;
  4815. var sourceProperty = entity[property];
  4816. if (sourceProperty !== undefined && sourceProperty !== null) {
  4817. switch (propertyType) {
  4818. case 0:
  4819. serializationObject[targetPropertyName] = sourceProperty;
  4820. break;
  4821. case 1:
  4822. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4823. break;
  4824. case 2:
  4825. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4826. break;
  4827. case 3:
  4828. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4829. break;
  4830. case 4:
  4831. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4832. break;
  4833. case 5:
  4834. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4835. break;
  4836. case 6:
  4837. serializationObject[targetPropertyName] = sourceProperty.id;
  4838. break;
  4839. case 7:
  4840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4841. break;
  4842. }
  4843. }
  4844. }
  4845. return serializationObject;
  4846. };
  4847. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4848. var destination = creationFunction();
  4849. // Tags
  4850. if (BABYLON.Tags) {
  4851. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4852. }
  4853. // Properties
  4854. for (var property in destination.__serializableMembers) {
  4855. var propertyDescriptor = destination.__serializableMembers[property];
  4856. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4857. var propertyType = propertyDescriptor.type;
  4858. if (sourceProperty !== undefined && sourceProperty !== null) {
  4859. switch (propertyType) {
  4860. case 0:
  4861. destination[property] = sourceProperty;
  4862. break;
  4863. case 1:
  4864. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4865. break;
  4866. case 2:
  4867. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4868. break;
  4869. case 3:
  4870. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4871. break;
  4872. case 4:
  4873. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4874. break;
  4875. case 5:
  4876. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4877. break;
  4878. case 6:
  4879. destination[property] = scene.getLastMeshByID(sourceProperty);
  4880. break;
  4881. case 7:
  4882. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4883. break;
  4884. }
  4885. }
  4886. }
  4887. return destination;
  4888. };
  4889. SerializationHelper.Clone = function (creationFunction, source) {
  4890. var destination = creationFunction();
  4891. // Tags
  4892. if (BABYLON.Tags) {
  4893. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4894. }
  4895. // Properties
  4896. for (var property in destination.__serializableMembers) {
  4897. var propertyDescriptor = destination.__serializableMembers[property];
  4898. var sourceProperty = source[property];
  4899. var propertyType = propertyDescriptor.type;
  4900. if (sourceProperty !== undefined && sourceProperty !== null) {
  4901. switch (propertyType) {
  4902. case 0: // Value
  4903. case 6:
  4904. destination[property] = sourceProperty;
  4905. break;
  4906. case 1: // Texture
  4907. case 2: // Color3
  4908. case 3: // FresnelParameters
  4909. case 4: // Vector2
  4910. case 5: // Vector3
  4911. case 7:
  4912. destination[property] = sourceProperty.clone();
  4913. break;
  4914. }
  4915. }
  4916. }
  4917. return destination;
  4918. };
  4919. return SerializationHelper;
  4920. }());
  4921. BABYLON.SerializationHelper = SerializationHelper;
  4922. })(BABYLON || (BABYLON = {}));
  4923. //# sourceMappingURL=babylon.decorators.js.map
  4924. var BABYLON;
  4925. (function (BABYLON) {
  4926. /**
  4927. * A class serves as a medium between the observable and its observers
  4928. */
  4929. var EventState = (function () {
  4930. /**
  4931. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4932. */
  4933. function EventState(mask, skipNextObservers) {
  4934. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4935. this.initalize(mask, skipNextObservers);
  4936. }
  4937. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4938. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4939. this.mask = mask;
  4940. this.skipNextObservers = skipNextObservers;
  4941. return this;
  4942. };
  4943. return EventState;
  4944. }());
  4945. BABYLON.EventState = EventState;
  4946. /**
  4947. * Represent an Observer registered to a given Observable object.
  4948. */
  4949. var Observer = (function () {
  4950. function Observer(callback, mask) {
  4951. this.callback = callback;
  4952. this.mask = mask;
  4953. }
  4954. return Observer;
  4955. }());
  4956. BABYLON.Observer = Observer;
  4957. /**
  4958. * The Observable class is a simple implementation of the Observable pattern.
  4959. * 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.
  4960. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4961. * 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).
  4962. * 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.
  4963. */
  4964. var Observable = (function () {
  4965. function Observable() {
  4966. this._observers = new Array();
  4967. this._eventState = new EventState(0);
  4968. }
  4969. /**
  4970. * Create a new Observer with the specified callback
  4971. * @param callback the callback that will be executed for that Observer
  4972. * @param mask the mask used to filter observers
  4973. * @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.
  4974. */
  4975. Observable.prototype.add = function (callback, mask, insertFirst) {
  4976. if (mask === void 0) { mask = -1; }
  4977. if (insertFirst === void 0) { insertFirst = false; }
  4978. if (!callback) {
  4979. return null;
  4980. }
  4981. var observer = new Observer(callback, mask);
  4982. if (insertFirst) {
  4983. this._observers.unshift(observer);
  4984. }
  4985. else {
  4986. this._observers.push(observer);
  4987. }
  4988. return observer;
  4989. };
  4990. /**
  4991. * Remove an Observer from the Observable object
  4992. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4993. */
  4994. Observable.prototype.remove = function (observer) {
  4995. var index = this._observers.indexOf(observer);
  4996. if (index !== -1) {
  4997. this._observers.splice(index, 1);
  4998. return true;
  4999. }
  5000. return false;
  5001. };
  5002. /**
  5003. * Remove a callback from the Observable object
  5004. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5005. */
  5006. Observable.prototype.removeCallback = function (callback) {
  5007. for (var index = 0; index < this._observers.length; index++) {
  5008. if (this._observers[index].callback === callback) {
  5009. this._observers.splice(index, 1);
  5010. return true;
  5011. }
  5012. }
  5013. return false;
  5014. };
  5015. /**
  5016. * Notify all Observers by calling their respective callback with the given data
  5017. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5018. * @param eventData
  5019. * @param mask
  5020. */
  5021. Observable.prototype.notifyObservers = function (eventData, mask) {
  5022. if (mask === void 0) { mask = -1; }
  5023. var state = this._eventState;
  5024. state.mask = mask;
  5025. state.skipNextObservers = false;
  5026. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5027. var obs = _a[_i];
  5028. if (obs.mask & mask) {
  5029. obs.callback(eventData, state);
  5030. }
  5031. if (state.skipNextObservers) {
  5032. return false;
  5033. }
  5034. }
  5035. return true;
  5036. };
  5037. /**
  5038. * return true is the Observable has at least one Observer registered
  5039. */
  5040. Observable.prototype.hasObservers = function () {
  5041. return this._observers.length > 0;
  5042. };
  5043. /**
  5044. * Clear the list of observers
  5045. */
  5046. Observable.prototype.clear = function () {
  5047. this._observers = new Array();
  5048. };
  5049. /**
  5050. * Clone the current observable
  5051. */
  5052. Observable.prototype.clone = function () {
  5053. var result = new Observable();
  5054. result._observers = this._observers.slice(0);
  5055. return result;
  5056. };
  5057. /**
  5058. * Does this observable handles observer registered with a given mask
  5059. * @param {number} trigger - the mask to be tested
  5060. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5061. **/
  5062. Observable.prototype.hasSpecificMask = function (mask) {
  5063. if (mask === void 0) { mask = -1; }
  5064. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5065. var obs = _a[_i];
  5066. if (obs.mask & mask && obs.mask === mask) {
  5067. return true;
  5068. }
  5069. }
  5070. return false;
  5071. };
  5072. return Observable;
  5073. }());
  5074. BABYLON.Observable = Observable;
  5075. })(BABYLON || (BABYLON = {}));
  5076. //# sourceMappingURL=babylon.observable.js.map
  5077. var BABYLON;
  5078. (function (BABYLON) {
  5079. var SmartArray = (function () {
  5080. function SmartArray(capacity) {
  5081. this.length = 0;
  5082. this._duplicateId = 0;
  5083. this.data = new Array(capacity);
  5084. this._id = SmartArray._GlobalId++;
  5085. }
  5086. SmartArray.prototype.push = function (value) {
  5087. this.data[this.length++] = value;
  5088. if (this.length > this.data.length) {
  5089. this.data.length *= 2;
  5090. }
  5091. if (!value.__smartArrayFlags) {
  5092. value.__smartArrayFlags = {};
  5093. }
  5094. value.__smartArrayFlags[this._id] = this._duplicateId;
  5095. };
  5096. SmartArray.prototype.forEach = function (func) {
  5097. for (var index = 0; index < this.length; index++) {
  5098. func(this.data[index]);
  5099. }
  5100. };
  5101. SmartArray.prototype.pushNoDuplicate = function (value) {
  5102. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5103. return false;
  5104. }
  5105. this.push(value);
  5106. return true;
  5107. };
  5108. SmartArray.prototype.sort = function (compareFn) {
  5109. this.data.sort(compareFn);
  5110. };
  5111. SmartArray.prototype.reset = function () {
  5112. this.length = 0;
  5113. this._duplicateId++;
  5114. };
  5115. SmartArray.prototype.dispose = function () {
  5116. this.reset();
  5117. this.data.length = 0;
  5118. };
  5119. SmartArray.prototype.concat = function (array) {
  5120. if (array.length === 0) {
  5121. return;
  5122. }
  5123. if (this.length + array.length > this.data.length) {
  5124. this.data.length = (this.length + array.length) * 2;
  5125. }
  5126. for (var index = 0; index < array.length; index++) {
  5127. this.data[this.length++] = (array.data || array)[index];
  5128. }
  5129. };
  5130. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5131. if (array.length === 0) {
  5132. return;
  5133. }
  5134. if (this.length + array.length > this.data.length) {
  5135. this.data.length = (this.length + array.length) * 2;
  5136. }
  5137. for (var index = 0; index < array.length; index++) {
  5138. var item = (array.data || array)[index];
  5139. this.pushNoDuplicate(item);
  5140. }
  5141. };
  5142. SmartArray.prototype.indexOf = function (value) {
  5143. var position = this.data.indexOf(value);
  5144. if (position >= this.length) {
  5145. return -1;
  5146. }
  5147. return position;
  5148. };
  5149. SmartArray.prototype.contains = function (value) {
  5150. return this.data.indexOf(value) !== -1;
  5151. };
  5152. return SmartArray;
  5153. }());
  5154. // Statics
  5155. SmartArray._GlobalId = 0;
  5156. BABYLON.SmartArray = SmartArray;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.smartArray.js.map
  5159. var BABYLON;
  5160. (function (BABYLON) {
  5161. // Screenshots
  5162. var screenshotCanvas;
  5163. var cloneValue = function (source, destinationObject) {
  5164. if (!source)
  5165. return null;
  5166. if (source instanceof BABYLON.Mesh) {
  5167. return null;
  5168. }
  5169. if (source instanceof BABYLON.SubMesh) {
  5170. return source.clone(destinationObject);
  5171. }
  5172. else if (source.clone) {
  5173. return source.clone();
  5174. }
  5175. return null;
  5176. };
  5177. var Tools = (function () {
  5178. function Tools() {
  5179. }
  5180. ;
  5181. /**
  5182. * Interpolates between a and b via alpha
  5183. * @param a The lower value (returned when alpha = 0)
  5184. * @param b The upper value (returned when alpha = 1)
  5185. * @param alpha The interpolation-factor
  5186. * @return The mixed value
  5187. */
  5188. Tools.Mix = function (a, b, alpha) {
  5189. return a * (1 - alpha) + b * alpha;
  5190. };
  5191. Tools.Instantiate = function (className) {
  5192. var arr = className.split(".");
  5193. var fn = (window || this);
  5194. for (var i = 0, len = arr.length; i < len; i++) {
  5195. fn = fn[arr[i]];
  5196. }
  5197. if (typeof fn !== "function") {
  5198. return null;
  5199. }
  5200. return fn;
  5201. };
  5202. Tools.SetImmediate = function (action) {
  5203. if (window.setImmediate) {
  5204. window.setImmediate(action);
  5205. }
  5206. else {
  5207. setTimeout(action, 1);
  5208. }
  5209. };
  5210. Tools.IsExponentOfTwo = function (value) {
  5211. var count = 1;
  5212. do {
  5213. count *= 2;
  5214. } while (count < value);
  5215. return count === value;
  5216. };
  5217. /**
  5218. * Find the next highest power of two.
  5219. * @param x Number to start search from.
  5220. * @return Next highest power of two.
  5221. */
  5222. Tools.CeilingPOT = function (x) {
  5223. x--;
  5224. x |= x >> 1;
  5225. x |= x >> 2;
  5226. x |= x >> 4;
  5227. x |= x >> 8;
  5228. x |= x >> 16;
  5229. x++;
  5230. return x;
  5231. };
  5232. /**
  5233. * Find the next lowest power of two.
  5234. * @param x Number to start search from.
  5235. * @return Next lowest power of two.
  5236. */
  5237. Tools.FloorPOT = function (x) {
  5238. x = x | (x >> 1);
  5239. x = x | (x >> 2);
  5240. x = x | (x >> 4);
  5241. x = x | (x >> 8);
  5242. x = x | (x >> 16);
  5243. return x - (x >> 1);
  5244. };
  5245. /**
  5246. * Find the nearest power of two.
  5247. * @param x Number to start search from.
  5248. * @return Next nearest power of two.
  5249. */
  5250. Tools.NearestPOT = function (x) {
  5251. var c = Tools.CeilingPOT(x);
  5252. var f = Tools.FloorPOT(x);
  5253. return (c - x) > (x - f) ? f : c;
  5254. };
  5255. Tools.GetExponentOfTwo = function (value, max, mode) {
  5256. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5257. var pot;
  5258. switch (mode) {
  5259. case BABYLON.Engine.SCALEMODE_FLOOR:
  5260. pot = Tools.FloorPOT(value);
  5261. break;
  5262. case BABYLON.Engine.SCALEMODE_NEAREST:
  5263. pot = Tools.NearestPOT(value);
  5264. break;
  5265. case BABYLON.Engine.SCALEMODE_CEILING:
  5266. pot = Tools.CeilingPOT(value);
  5267. break;
  5268. }
  5269. return Math.min(pot, max);
  5270. };
  5271. Tools.GetFilename = function (path) {
  5272. var index = path.lastIndexOf("/");
  5273. if (index < 0)
  5274. return path;
  5275. return path.substring(index + 1);
  5276. };
  5277. Tools.GetDOMTextContent = function (element) {
  5278. var result = "";
  5279. var child = element.firstChild;
  5280. while (child) {
  5281. if (child.nodeType === 3) {
  5282. result += child.textContent;
  5283. }
  5284. child = child.nextSibling;
  5285. }
  5286. return result;
  5287. };
  5288. Tools.ToDegrees = function (angle) {
  5289. return angle * 180 / Math.PI;
  5290. };
  5291. Tools.ToRadians = function (angle) {
  5292. return angle * Math.PI / 180;
  5293. };
  5294. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5295. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5296. var output = "";
  5297. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5298. var i = 0;
  5299. var bytes = new Uint8Array(buffer);
  5300. while (i < bytes.length) {
  5301. chr1 = bytes[i++];
  5302. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5303. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5304. enc1 = chr1 >> 2;
  5305. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5306. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5307. enc4 = chr3 & 63;
  5308. if (isNaN(chr2)) {
  5309. enc3 = enc4 = 64;
  5310. }
  5311. else if (isNaN(chr3)) {
  5312. enc4 = 64;
  5313. }
  5314. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5315. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5316. }
  5317. return "data:image/png;base64," + output;
  5318. };
  5319. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5320. if (bias === void 0) { bias = null; }
  5321. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5322. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5323. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5324. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5325. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5326. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5327. }
  5328. if (bias) {
  5329. minimum.x -= minimum.x * bias.x + bias.y;
  5330. minimum.y -= minimum.y * bias.x + bias.y;
  5331. minimum.z -= minimum.z * bias.x + bias.y;
  5332. maximum.x += maximum.x * bias.x + bias.y;
  5333. maximum.y += maximum.y * bias.x + bias.y;
  5334. maximum.z += maximum.z * bias.x + bias.y;
  5335. }
  5336. return {
  5337. minimum: minimum,
  5338. maximum: maximum
  5339. };
  5340. };
  5341. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5342. if (bias === void 0) { bias = null; }
  5343. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5344. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5345. if (!stride) {
  5346. stride = 3;
  5347. }
  5348. for (var index = start; index < start + count; index++) {
  5349. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5350. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5351. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5352. }
  5353. if (bias) {
  5354. minimum.x -= minimum.x * bias.x + bias.y;
  5355. minimum.y -= minimum.y * bias.x + bias.y;
  5356. minimum.z -= minimum.z * bias.x + bias.y;
  5357. maximum.x += maximum.x * bias.x + bias.y;
  5358. maximum.y += maximum.y * bias.x + bias.y;
  5359. maximum.z += maximum.z * bias.x + bias.y;
  5360. }
  5361. return {
  5362. minimum: minimum,
  5363. maximum: maximum
  5364. };
  5365. };
  5366. Tools.Vector2ArrayFeeder = function (array) {
  5367. return function (index) {
  5368. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5369. var length = isFloatArray ? array.length / 2 : array.length;
  5370. if (index >= length) {
  5371. return null;
  5372. }
  5373. if (isFloatArray) {
  5374. var fa = array;
  5375. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5376. }
  5377. var a = array;
  5378. return a[index];
  5379. };
  5380. };
  5381. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5382. if (bias === void 0) { bias = null; }
  5383. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5384. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5385. var i = 0;
  5386. var cur = feeder(i++);
  5387. while (cur) {
  5388. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5389. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5390. cur = feeder(i++);
  5391. }
  5392. if (bias) {
  5393. minimum.x -= minimum.x * bias.x + bias.y;
  5394. minimum.y -= minimum.y * bias.x + bias.y;
  5395. maximum.x += maximum.x * bias.x + bias.y;
  5396. maximum.y += maximum.y * bias.x + bias.y;
  5397. }
  5398. return {
  5399. minimum: minimum,
  5400. maximum: maximum
  5401. };
  5402. };
  5403. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5404. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5405. return undefined;
  5406. return Array.isArray(obj) ? obj : [obj];
  5407. };
  5408. // Misc.
  5409. Tools.GetPointerPrefix = function () {
  5410. var eventPrefix = "pointer";
  5411. // Check if pointer events are supported
  5412. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5413. eventPrefix = "mouse";
  5414. }
  5415. return eventPrefix;
  5416. };
  5417. /**
  5418. * @param func - the function to be called
  5419. * @param requester - the object that will request the next frame. Falls back to window.
  5420. */
  5421. Tools.QueueNewFrame = function (func, requester) {
  5422. if (requester === void 0) { requester = window; }
  5423. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5424. /*if(requester.isPresenting) {
  5425. return;
  5426. } else*/ if (requester.requestAnimationFrame)
  5427. requester.requestAnimationFrame(func);
  5428. else if (requester.msRequestAnimationFrame)
  5429. requester.msRequestAnimationFrame(func);
  5430. else if (requester.webkitRequestAnimationFrame)
  5431. requester.webkitRequestAnimationFrame(func);
  5432. else if (requester.mozRequestAnimationFrame)
  5433. requester.mozRequestAnimationFrame(func);
  5434. else if (requester.oRequestAnimationFrame)
  5435. requester.oRequestAnimationFrame(func);
  5436. else {
  5437. window.setTimeout(func, 16);
  5438. }
  5439. };
  5440. Tools.RequestFullscreen = function (element) {
  5441. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5442. if (!requestFunction)
  5443. return;
  5444. requestFunction.call(element);
  5445. };
  5446. Tools.ExitFullscreen = function () {
  5447. if (document.exitFullscreen) {
  5448. document.exitFullscreen();
  5449. }
  5450. else if (document.mozCancelFullScreen) {
  5451. document.mozCancelFullScreen();
  5452. }
  5453. else if (document.webkitCancelFullScreen) {
  5454. document.webkitCancelFullScreen();
  5455. }
  5456. else if (document.msCancelFullScreen) {
  5457. document.msCancelFullScreen();
  5458. }
  5459. };
  5460. Tools.SetCorsBehavior = function (url, img) {
  5461. if (Tools.CorsBehavior) {
  5462. switch (typeof (Tools.CorsBehavior)) {
  5463. case "function":
  5464. var result = Tools.CorsBehavior(url);
  5465. if (result) {
  5466. img.crossOrigin = result;
  5467. }
  5468. break;
  5469. case "string":
  5470. default:
  5471. img.crossOrigin = Tools.CorsBehavior;
  5472. break;
  5473. }
  5474. }
  5475. };
  5476. // External files
  5477. Tools.CleanUrl = function (url) {
  5478. url = url.replace(/#/mg, "%23");
  5479. return url;
  5480. };
  5481. Tools.LoadImage = function (url, onload, onerror, database) {
  5482. if (url instanceof ArrayBuffer) {
  5483. url = Tools.EncodeArrayBufferTobase64(url);
  5484. }
  5485. url = Tools.CleanUrl(url);
  5486. var img = new Image();
  5487. if (url.substr(0, 5) !== "data:") {
  5488. Tools.SetCorsBehavior(url, img);
  5489. }
  5490. img.onload = function () {
  5491. onload(img);
  5492. };
  5493. img.onerror = function (err) {
  5494. Tools.Error("Error while trying to load image: " + url);
  5495. if (Tools.UseFallbackTexture) {
  5496. img.src = Tools.fallbackTexture;
  5497. onload(img);
  5498. }
  5499. else {
  5500. onerror();
  5501. }
  5502. };
  5503. var noIndexedDB = function () {
  5504. img.src = url;
  5505. };
  5506. var loadFromIndexedDB = function () {
  5507. database.loadImageFromDB(url, img);
  5508. };
  5509. //ANY database to do!
  5510. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5511. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5512. }
  5513. else {
  5514. if (url.indexOf("file:") !== 0) {
  5515. noIndexedDB();
  5516. }
  5517. else {
  5518. var textureName = url.substring(5).toLowerCase();
  5519. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5520. try {
  5521. var blobURL;
  5522. try {
  5523. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5524. }
  5525. catch (ex) {
  5526. // Chrome doesn't support oneTimeOnly parameter
  5527. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5528. }
  5529. img.src = blobURL;
  5530. }
  5531. catch (e) {
  5532. img.src = null;
  5533. }
  5534. }
  5535. else {
  5536. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5537. img.src = Tools.fallbackTexture;
  5538. }
  5539. }
  5540. }
  5541. return img;
  5542. };
  5543. //ANY
  5544. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5545. url = Tools.CleanUrl(url);
  5546. var noIndexedDB = function () {
  5547. var request = new XMLHttpRequest();
  5548. var loadUrl = Tools.BaseUrl + url;
  5549. request.open('GET', loadUrl, true);
  5550. if (useArrayBuffer) {
  5551. request.responseType = "arraybuffer";
  5552. }
  5553. request.onprogress = progressCallBack;
  5554. request.onreadystatechange = function () {
  5555. // In case of undefined state in some browsers.
  5556. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5557. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5558. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5559. callback(!useArrayBuffer ? request.responseText : request.response);
  5560. }
  5561. else {
  5562. if (onError) {
  5563. onError(request);
  5564. }
  5565. else {
  5566. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5567. }
  5568. }
  5569. }
  5570. };
  5571. request.send(null);
  5572. };
  5573. var loadFromIndexedDB = function () {
  5574. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5575. };
  5576. if (url.indexOf("file:") !== -1) {
  5577. var fileName = url.substring(5).toLowerCase();
  5578. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5579. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5580. }
  5581. else {
  5582. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5583. }
  5584. }
  5585. else {
  5586. // Caching all files
  5587. if (database && database.enableSceneOffline) {
  5588. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5589. }
  5590. else {
  5591. noIndexedDB();
  5592. }
  5593. }
  5594. };
  5595. /**
  5596. * Load a script (identified by an url). When the url returns, the
  5597. * content of this file is added into a new script element, attached to the DOM (body element)
  5598. */
  5599. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5600. var head = document.getElementsByTagName('head')[0];
  5601. var script = document.createElement('script');
  5602. script.type = 'text/javascript';
  5603. script.src = scriptUrl;
  5604. var self = this;
  5605. script.onload = function () {
  5606. if (onSuccess) {
  5607. onSuccess();
  5608. }
  5609. };
  5610. script.onerror = function () {
  5611. if (onError) {
  5612. onError();
  5613. }
  5614. };
  5615. head.appendChild(script);
  5616. };
  5617. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5618. var reader = new FileReader();
  5619. reader.onload = function (e) {
  5620. //target doesn't have result from ts 1.3
  5621. callback(e.target['result']);
  5622. };
  5623. reader.onprogress = progressCallback;
  5624. reader.readAsDataURL(fileToLoad);
  5625. };
  5626. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5627. var reader = new FileReader();
  5628. reader.onerror = function (e) {
  5629. Tools.Log("Error while reading file: " + fileToLoad.name);
  5630. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5631. };
  5632. reader.onload = function (e) {
  5633. //target doesn't have result from ts 1.3
  5634. callback(e.target['result']);
  5635. };
  5636. reader.onprogress = progressCallBack;
  5637. if (!useArrayBuffer) {
  5638. // Asynchronous read
  5639. reader.readAsText(fileToLoad);
  5640. }
  5641. else {
  5642. reader.readAsArrayBuffer(fileToLoad);
  5643. }
  5644. };
  5645. //returns a downloadable url to a file content.
  5646. Tools.FileAsURL = function (content) {
  5647. var fileBlob = new Blob([content]);
  5648. var url = window.URL || window.webkitURL;
  5649. var link = url.createObjectURL(fileBlob);
  5650. return link;
  5651. };
  5652. // Misc.
  5653. Tools.Format = function (value, decimals) {
  5654. if (decimals === void 0) { decimals = 2; }
  5655. return value.toFixed(decimals);
  5656. };
  5657. Tools.CheckExtends = function (v, min, max) {
  5658. if (v.x < min.x)
  5659. min.x = v.x;
  5660. if (v.y < min.y)
  5661. min.y = v.y;
  5662. if (v.z < min.z)
  5663. min.z = v.z;
  5664. if (v.x > max.x)
  5665. max.x = v.x;
  5666. if (v.y > max.y)
  5667. max.y = v.y;
  5668. if (v.z > max.z)
  5669. max.z = v.z;
  5670. };
  5671. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5672. for (var prop in source) {
  5673. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5674. continue;
  5675. }
  5676. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5677. continue;
  5678. }
  5679. var sourceValue = source[prop];
  5680. var typeOfSourceValue = typeof sourceValue;
  5681. if (typeOfSourceValue === "function") {
  5682. continue;
  5683. }
  5684. if (typeOfSourceValue === "object") {
  5685. if (sourceValue instanceof Array) {
  5686. destination[prop] = [];
  5687. if (sourceValue.length > 0) {
  5688. if (typeof sourceValue[0] == "object") {
  5689. for (var index = 0; index < sourceValue.length; index++) {
  5690. var clonedValue = cloneValue(sourceValue[index], destination);
  5691. if (destination[prop].indexOf(clonedValue) === -1) {
  5692. destination[prop].push(clonedValue);
  5693. }
  5694. }
  5695. }
  5696. else {
  5697. destination[prop] = sourceValue.slice(0);
  5698. }
  5699. }
  5700. }
  5701. else {
  5702. destination[prop] = cloneValue(sourceValue, destination);
  5703. }
  5704. }
  5705. else {
  5706. destination[prop] = sourceValue;
  5707. }
  5708. }
  5709. };
  5710. Tools.IsEmpty = function (obj) {
  5711. for (var i in obj) {
  5712. return false;
  5713. }
  5714. return true;
  5715. };
  5716. Tools.RegisterTopRootEvents = function (events) {
  5717. for (var index = 0; index < events.length; index++) {
  5718. var event = events[index];
  5719. window.addEventListener(event.name, event.handler, false);
  5720. try {
  5721. if (window.parent) {
  5722. window.parent.addEventListener(event.name, event.handler, false);
  5723. }
  5724. }
  5725. catch (e) {
  5726. // Silently fails...
  5727. }
  5728. }
  5729. };
  5730. Tools.UnregisterTopRootEvents = function (events) {
  5731. for (var index = 0; index < events.length; index++) {
  5732. var event = events[index];
  5733. window.removeEventListener(event.name, event.handler);
  5734. try {
  5735. if (window.parent) {
  5736. window.parent.removeEventListener(event.name, event.handler);
  5737. }
  5738. }
  5739. catch (e) {
  5740. // Silently fails...
  5741. }
  5742. }
  5743. };
  5744. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5745. if (mimeType === void 0) { mimeType = "image/png"; }
  5746. // Read the contents of the framebuffer
  5747. var numberOfChannelsByLine = width * 4;
  5748. var halfHeight = height / 2;
  5749. //Reading datas from WebGL
  5750. var data = engine.readPixels(0, 0, width, height);
  5751. //To flip image on Y axis.
  5752. for (var i = 0; i < halfHeight; i++) {
  5753. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5754. var currentCell = j + i * numberOfChannelsByLine;
  5755. var targetLine = height - i - 1;
  5756. var targetCell = j + targetLine * numberOfChannelsByLine;
  5757. var temp = data[currentCell];
  5758. data[currentCell] = data[targetCell];
  5759. data[targetCell] = temp;
  5760. }
  5761. }
  5762. // Create a 2D canvas to store the result
  5763. if (!screenshotCanvas) {
  5764. screenshotCanvas = document.createElement('canvas');
  5765. }
  5766. screenshotCanvas.width = width;
  5767. screenshotCanvas.height = height;
  5768. var context = screenshotCanvas.getContext('2d');
  5769. // Copy the pixels to a 2D canvas
  5770. var imageData = context.createImageData(width, height);
  5771. var castData = (imageData.data);
  5772. castData.set(data);
  5773. context.putImageData(imageData, 0, 0);
  5774. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5775. };
  5776. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5777. if (mimeType === void 0) { mimeType = "image/png"; }
  5778. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5779. if (successCallback) {
  5780. successCallback(base64Image);
  5781. }
  5782. else {
  5783. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5784. if (("download" in document.createElement("a"))) {
  5785. var a = window.document.createElement("a");
  5786. a.href = base64Image;
  5787. var date = new Date();
  5788. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5789. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5790. window.document.body.appendChild(a);
  5791. a.addEventListener("click", function () {
  5792. a.parentElement.removeChild(a);
  5793. });
  5794. a.click();
  5795. //Or opening a new tab with the image if it is not possible to automatically start download.
  5796. }
  5797. else {
  5798. var newWindow = window.open("");
  5799. var img = newWindow.document.createElement("img");
  5800. img.src = base64Image;
  5801. newWindow.document.body.appendChild(img);
  5802. }
  5803. }
  5804. };
  5805. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5806. if (mimeType === void 0) { mimeType = "image/png"; }
  5807. var width;
  5808. var height;
  5809. // If a precision value is specified
  5810. if (size.precision) {
  5811. width = Math.round(engine.getRenderWidth() * size.precision);
  5812. height = Math.round(width / engine.getAspectRatio(camera));
  5813. }
  5814. else if (size.width && size.height) {
  5815. width = size.width;
  5816. height = size.height;
  5817. }
  5818. else if (size.width && !size.height) {
  5819. width = size.width;
  5820. height = Math.round(width / engine.getAspectRatio(camera));
  5821. }
  5822. else if (size.height && !size.width) {
  5823. height = size.height;
  5824. width = Math.round(height * engine.getAspectRatio(camera));
  5825. }
  5826. else if (!isNaN(size)) {
  5827. height = size;
  5828. width = size;
  5829. }
  5830. else {
  5831. Tools.Error("Invalid 'size' parameter !");
  5832. return;
  5833. }
  5834. if (!screenshotCanvas) {
  5835. screenshotCanvas = document.createElement('canvas');
  5836. }
  5837. screenshotCanvas.width = width;
  5838. screenshotCanvas.height = height;
  5839. var renderContext = screenshotCanvas.getContext("2d");
  5840. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5841. var newWidth = width;
  5842. var newHeight = newWidth / ratio;
  5843. if (newHeight > height) {
  5844. newHeight = height;
  5845. newWidth = newHeight * ratio;
  5846. }
  5847. var offsetX = Math.max(0, width - newWidth) / 2;
  5848. var offsetY = Math.max(0, height - newHeight) / 2;
  5849. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5850. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5851. };
  5852. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5853. if (mimeType === void 0) { mimeType = "image/png"; }
  5854. if (samples === void 0) { samples = 1; }
  5855. var width;
  5856. var height;
  5857. //If a precision value is specified
  5858. if (size.precision) {
  5859. width = Math.round(engine.getRenderWidth() * size.precision);
  5860. height = Math.round(width / engine.getAspectRatio(camera));
  5861. size = { width: width, height: height };
  5862. }
  5863. else if (size.width && size.height) {
  5864. width = size.width;
  5865. height = size.height;
  5866. }
  5867. else if (size.width && !size.height) {
  5868. width = size.width;
  5869. height = Math.round(width / engine.getAspectRatio(camera));
  5870. size = { width: width, height: height };
  5871. }
  5872. else if (size.height && !size.width) {
  5873. height = size.height;
  5874. width = Math.round(height * engine.getAspectRatio(camera));
  5875. size = { width: width, height: height };
  5876. }
  5877. else if (!isNaN(size)) {
  5878. height = size;
  5879. width = size;
  5880. }
  5881. else {
  5882. Tools.Error("Invalid 'size' parameter !");
  5883. return;
  5884. }
  5885. var scene = camera.getScene();
  5886. var previousCamera = null;
  5887. if (scene.activeCamera !== camera) {
  5888. previousCamera = scene.activeCamera;
  5889. scene.activeCamera = camera;
  5890. }
  5891. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5892. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5893. texture.renderList = scene.meshes;
  5894. texture.samples = samples;
  5895. texture.onAfterRenderObservable.add(function () {
  5896. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5897. });
  5898. scene.incrementRenderId();
  5899. scene.resetCachedMaterial();
  5900. texture.render(true);
  5901. texture.dispose();
  5902. if (previousCamera) {
  5903. scene.activeCamera = previousCamera;
  5904. }
  5905. camera.getProjectionMatrix(true); // Force cache refresh;
  5906. };
  5907. // XHR response validator for local file scenario
  5908. Tools.ValidateXHRData = function (xhr, dataType) {
  5909. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5910. if (dataType === void 0) { dataType = 7; }
  5911. try {
  5912. if (dataType & 1) {
  5913. if (xhr.responseText && xhr.responseText.length > 0) {
  5914. return true;
  5915. }
  5916. else if (dataType === 1) {
  5917. return false;
  5918. }
  5919. }
  5920. if (dataType & 2) {
  5921. // Check header width and height since there is no "TGA" magic number
  5922. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5923. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5924. return true;
  5925. }
  5926. else if (dataType === 2) {
  5927. return false;
  5928. }
  5929. }
  5930. if (dataType & 4) {
  5931. // Check for the "DDS" magic number
  5932. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5933. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5934. return true;
  5935. }
  5936. else {
  5937. return false;
  5938. }
  5939. }
  5940. }
  5941. catch (e) {
  5942. // Global protection
  5943. }
  5944. return false;
  5945. };
  5946. /**
  5947. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5948. * Be aware Math.random() could cause collisions, but:
  5949. * "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"
  5950. */
  5951. Tools.RandomId = function () {
  5952. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5953. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5954. return v.toString(16);
  5955. });
  5956. };
  5957. Object.defineProperty(Tools, "NoneLogLevel", {
  5958. get: function () {
  5959. return Tools._NoneLogLevel;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. Object.defineProperty(Tools, "MessageLogLevel", {
  5965. get: function () {
  5966. return Tools._MessageLogLevel;
  5967. },
  5968. enumerable: true,
  5969. configurable: true
  5970. });
  5971. Object.defineProperty(Tools, "WarningLogLevel", {
  5972. get: function () {
  5973. return Tools._WarningLogLevel;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(Tools, "ErrorLogLevel", {
  5979. get: function () {
  5980. return Tools._ErrorLogLevel;
  5981. },
  5982. enumerable: true,
  5983. configurable: true
  5984. });
  5985. Object.defineProperty(Tools, "AllLogLevel", {
  5986. get: function () {
  5987. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Tools._AddLogEntry = function (entry) {
  5993. Tools._LogCache = entry + Tools._LogCache;
  5994. if (Tools.OnNewCacheEntry) {
  5995. Tools.OnNewCacheEntry(entry);
  5996. }
  5997. };
  5998. Tools._FormatMessage = function (message) {
  5999. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6000. var date = new Date();
  6001. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6002. };
  6003. Tools._LogDisabled = function (message) {
  6004. // nothing to do
  6005. };
  6006. Tools._LogEnabled = function (message) {
  6007. var formattedMessage = Tools._FormatMessage(message);
  6008. console.log("BJS - " + formattedMessage);
  6009. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6010. Tools._AddLogEntry(entry);
  6011. };
  6012. Tools._WarnDisabled = function (message) {
  6013. // nothing to do
  6014. };
  6015. Tools._WarnEnabled = function (message) {
  6016. var formattedMessage = Tools._FormatMessage(message);
  6017. console.warn("BJS - " + formattedMessage);
  6018. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6019. Tools._AddLogEntry(entry);
  6020. };
  6021. Tools._ErrorDisabled = function (message) {
  6022. // nothing to do
  6023. };
  6024. Tools._ErrorEnabled = function (message) {
  6025. Tools.errorsCount++;
  6026. var formattedMessage = Tools._FormatMessage(message);
  6027. console.error("BJS - " + formattedMessage);
  6028. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6029. Tools._AddLogEntry(entry);
  6030. };
  6031. Object.defineProperty(Tools, "LogCache", {
  6032. get: function () {
  6033. return Tools._LogCache;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Tools.ClearLogCache = function () {
  6039. Tools._LogCache = "";
  6040. Tools.errorsCount = 0;
  6041. };
  6042. Object.defineProperty(Tools, "LogLevels", {
  6043. set: function (level) {
  6044. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6045. Tools.Log = Tools._LogEnabled;
  6046. }
  6047. else {
  6048. Tools.Log = Tools._LogDisabled;
  6049. }
  6050. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6051. Tools.Warn = Tools._WarnEnabled;
  6052. }
  6053. else {
  6054. Tools.Warn = Tools._WarnDisabled;
  6055. }
  6056. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6057. Tools.Error = Tools._ErrorEnabled;
  6058. }
  6059. else {
  6060. Tools.Error = Tools._ErrorDisabled;
  6061. }
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6067. get: function () {
  6068. return Tools._PerformanceNoneLogLevel;
  6069. },
  6070. enumerable: true,
  6071. configurable: true
  6072. });
  6073. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6074. get: function () {
  6075. return Tools._PerformanceUserMarkLogLevel;
  6076. },
  6077. enumerable: true,
  6078. configurable: true
  6079. });
  6080. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6081. get: function () {
  6082. return Tools._PerformanceConsoleLogLevel;
  6083. },
  6084. enumerable: true,
  6085. configurable: true
  6086. });
  6087. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6088. set: function (level) {
  6089. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6090. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6091. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6092. return;
  6093. }
  6094. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6095. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6096. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6097. return;
  6098. }
  6099. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6100. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6106. };
  6107. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6108. };
  6109. Tools._StartUserMark = function (counterName, condition) {
  6110. if (condition === void 0) { condition = true; }
  6111. if (!condition || !Tools._performance.mark) {
  6112. return;
  6113. }
  6114. Tools._performance.mark(counterName + "-Begin");
  6115. };
  6116. Tools._EndUserMark = function (counterName, condition) {
  6117. if (condition === void 0) { condition = true; }
  6118. if (!condition || !Tools._performance.mark) {
  6119. return;
  6120. }
  6121. Tools._performance.mark(counterName + "-End");
  6122. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6123. };
  6124. Tools._StartPerformanceConsole = function (counterName, condition) {
  6125. if (condition === void 0) { condition = true; }
  6126. if (!condition) {
  6127. return;
  6128. }
  6129. Tools._StartUserMark(counterName, condition);
  6130. if (console.time) {
  6131. console.time(counterName);
  6132. }
  6133. };
  6134. Tools._EndPerformanceConsole = function (counterName, condition) {
  6135. if (condition === void 0) { condition = true; }
  6136. if (!condition) {
  6137. return;
  6138. }
  6139. Tools._EndUserMark(counterName, condition);
  6140. if (console.time) {
  6141. console.timeEnd(counterName);
  6142. }
  6143. };
  6144. Object.defineProperty(Tools, "Now", {
  6145. get: function () {
  6146. if (window.performance && window.performance.now) {
  6147. return window.performance.now();
  6148. }
  6149. return new Date().getTime();
  6150. },
  6151. enumerable: true,
  6152. configurable: true
  6153. });
  6154. /**
  6155. * This method will return the name of the class used to create the instance of the given object.
  6156. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6157. * @param object the object to get the class name from
  6158. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6159. */
  6160. Tools.getClassName = function (object, isType) {
  6161. if (isType === void 0) { isType = false; }
  6162. var name = null;
  6163. if (!isType && object.getClassName) {
  6164. name = object.getClassName();
  6165. }
  6166. else {
  6167. if (object instanceof Object) {
  6168. var classObj = isType ? object : Object.getPrototypeOf(object);
  6169. name = classObj.constructor["__bjsclassName__"];
  6170. }
  6171. if (!name) {
  6172. name = typeof object;
  6173. }
  6174. }
  6175. return name;
  6176. };
  6177. Tools.first = function (array, predicate) {
  6178. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6179. var el = array_1[_i];
  6180. if (predicate(el)) {
  6181. return el;
  6182. }
  6183. }
  6184. };
  6185. /**
  6186. * This method will return the name of the full name of the class, including its owning module (if any).
  6187. * 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).
  6188. * @param object the object to get the class name from
  6189. * @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.
  6190. */
  6191. Tools.getFullClassName = function (object, isType) {
  6192. if (isType === void 0) { isType = false; }
  6193. var className = null;
  6194. var moduleName = null;
  6195. if (!isType && object.getClassName) {
  6196. className = object.getClassName();
  6197. }
  6198. else {
  6199. if (object instanceof Object) {
  6200. var classObj = isType ? object : Object.getPrototypeOf(object);
  6201. className = classObj.constructor["__bjsclassName__"];
  6202. moduleName = classObj.constructor["__bjsmoduleName__"];
  6203. }
  6204. if (!className) {
  6205. className = typeof object;
  6206. }
  6207. }
  6208. if (!className) {
  6209. return null;
  6210. }
  6211. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6212. };
  6213. /**
  6214. * 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.
  6215. * @param array
  6216. */
  6217. Tools.arrayOrStringFeeder = function (array) {
  6218. return function (index) {
  6219. if (index >= array.length) {
  6220. return null;
  6221. }
  6222. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6223. if (val && val.getHashCode) {
  6224. val = val.getHashCode();
  6225. }
  6226. if (typeof val === "string") {
  6227. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6228. }
  6229. return val;
  6230. };
  6231. };
  6232. /**
  6233. * Compute the hashCode of a stream of number
  6234. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6235. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6236. * @return the hash code computed
  6237. */
  6238. Tools.hashCodeFromStream = function (feeder) {
  6239. // Based from here: http://stackoverflow.com/a/7616484/802124
  6240. var hash = 0;
  6241. var index = 0;
  6242. var chr = feeder(index++);
  6243. while (chr != null) {
  6244. hash = ((hash << 5) - hash) + chr;
  6245. hash |= 0; // Convert to 32bit integer
  6246. chr = feeder(index++);
  6247. }
  6248. return hash;
  6249. };
  6250. return Tools;
  6251. }());
  6252. Tools.BaseUrl = "";
  6253. Tools.CorsBehavior = "anonymous";
  6254. Tools.UseFallbackTexture = true;
  6255. // Used in case of a texture loading problem
  6256. 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";
  6257. // Logs
  6258. Tools._NoneLogLevel = 0;
  6259. Tools._MessageLogLevel = 1;
  6260. Tools._WarningLogLevel = 2;
  6261. Tools._ErrorLogLevel = 4;
  6262. Tools._LogCache = "";
  6263. Tools.errorsCount = 0;
  6264. Tools.Log = Tools._LogEnabled;
  6265. Tools.Warn = Tools._WarnEnabled;
  6266. Tools.Error = Tools._ErrorEnabled;
  6267. // Performances
  6268. Tools._PerformanceNoneLogLevel = 0;
  6269. Tools._PerformanceUserMarkLogLevel = 1;
  6270. Tools._PerformanceConsoleLogLevel = 2;
  6271. Tools._performance = window.performance;
  6272. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6273. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6274. BABYLON.Tools = Tools;
  6275. /**
  6276. * This class is used to track a performance counter which is number based.
  6277. * The user has access to many properties which give statistics of different nature
  6278. *
  6279. * The implementer can track two kinds of Performance Counter: time and count
  6280. * 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.
  6281. * 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.
  6282. */
  6283. var PerfCounter = (function () {
  6284. function PerfCounter() {
  6285. this._startMonitoringTime = 0;
  6286. this._min = 0;
  6287. this._max = 0;
  6288. this._average = 0;
  6289. this._lastSecAverage = 0;
  6290. this._current = 0;
  6291. this._totalValueCount = 0;
  6292. this._totalAccumulated = 0;
  6293. this._lastSecAccumulated = 0;
  6294. this._lastSecTime = 0;
  6295. this._lastSecValueCount = 0;
  6296. }
  6297. Object.defineProperty(PerfCounter.prototype, "min", {
  6298. /**
  6299. * Returns the smallest value ever
  6300. */
  6301. get: function () {
  6302. return this._min;
  6303. },
  6304. enumerable: true,
  6305. configurable: true
  6306. });
  6307. Object.defineProperty(PerfCounter.prototype, "max", {
  6308. /**
  6309. * Returns the biggest value ever
  6310. */
  6311. get: function () {
  6312. return this._max;
  6313. },
  6314. enumerable: true,
  6315. configurable: true
  6316. });
  6317. Object.defineProperty(PerfCounter.prototype, "average", {
  6318. /**
  6319. * Returns the average value since the performance counter is running
  6320. */
  6321. get: function () {
  6322. return this._average;
  6323. },
  6324. enumerable: true,
  6325. configurable: true
  6326. });
  6327. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6328. /**
  6329. * Returns the average value of the last second the counter was monitored
  6330. */
  6331. get: function () {
  6332. return this._lastSecAverage;
  6333. },
  6334. enumerable: true,
  6335. configurable: true
  6336. });
  6337. Object.defineProperty(PerfCounter.prototype, "current", {
  6338. /**
  6339. * Returns the current value
  6340. */
  6341. get: function () {
  6342. return this._current;
  6343. },
  6344. enumerable: true,
  6345. configurable: true
  6346. });
  6347. Object.defineProperty(PerfCounter.prototype, "total", {
  6348. get: function () {
  6349. return this._totalAccumulated;
  6350. },
  6351. enumerable: true,
  6352. configurable: true
  6353. });
  6354. /**
  6355. * Call this method to start monitoring a new frame.
  6356. * 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.
  6357. */
  6358. PerfCounter.prototype.fetchNewFrame = function () {
  6359. this._totalValueCount++;
  6360. this._current = 0;
  6361. this._lastSecValueCount++;
  6362. };
  6363. /**
  6364. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6365. * @param newCount the count value to add to the monitored count
  6366. * @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.
  6367. */
  6368. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6369. if (!PerfCounter.Enabled) {
  6370. return;
  6371. }
  6372. this._current += newCount;
  6373. if (fetchResult) {
  6374. this._fetchResult();
  6375. }
  6376. };
  6377. /**
  6378. * Start monitoring this performance counter
  6379. */
  6380. PerfCounter.prototype.beginMonitoring = function () {
  6381. if (!PerfCounter.Enabled) {
  6382. return;
  6383. }
  6384. this._startMonitoringTime = Tools.Now;
  6385. };
  6386. /**
  6387. * Compute the time lapsed since the previous beginMonitoring() call.
  6388. * @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
  6389. */
  6390. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6391. if (newFrame === void 0) { newFrame = true; }
  6392. if (!PerfCounter.Enabled) {
  6393. return;
  6394. }
  6395. if (newFrame) {
  6396. this.fetchNewFrame();
  6397. }
  6398. var currentTime = Tools.Now;
  6399. this._current = currentTime - this._startMonitoringTime;
  6400. if (newFrame) {
  6401. this._fetchResult();
  6402. }
  6403. };
  6404. PerfCounter.prototype._fetchResult = function () {
  6405. this._totalAccumulated += this._current;
  6406. this._lastSecAccumulated += this._current;
  6407. // Min/Max update
  6408. this._min = Math.min(this._min, this._current);
  6409. this._max = Math.max(this._max, this._current);
  6410. this._average = this._totalAccumulated / this._totalValueCount;
  6411. // Reset last sec?
  6412. var now = Tools.Now;
  6413. if ((now - this._lastSecTime) > 1000) {
  6414. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6415. this._lastSecTime = now;
  6416. this._lastSecAccumulated = 0;
  6417. this._lastSecValueCount = 0;
  6418. }
  6419. };
  6420. return PerfCounter;
  6421. }());
  6422. PerfCounter.Enabled = true;
  6423. BABYLON.PerfCounter = PerfCounter;
  6424. /**
  6425. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6426. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6427. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6428. * @param name The name of the class, case should be preserved
  6429. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6430. */
  6431. function className(name, module) {
  6432. return function (target) {
  6433. target["__bjsclassName__"] = name;
  6434. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6435. };
  6436. }
  6437. BABYLON.className = className;
  6438. /**
  6439. * An implementation of a loop for asynchronous functions.
  6440. */
  6441. var AsyncLoop = (function () {
  6442. /**
  6443. * Constroctor.
  6444. * @param iterations the number of iterations.
  6445. * @param _fn the function to run each iteration
  6446. * @param _successCallback the callback that will be called upon succesful execution
  6447. * @param offset starting offset.
  6448. */
  6449. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6450. if (offset === void 0) { offset = 0; }
  6451. this.iterations = iterations;
  6452. this._fn = _fn;
  6453. this._successCallback = _successCallback;
  6454. this.index = offset - 1;
  6455. this._done = false;
  6456. }
  6457. /**
  6458. * Execute the next iteration. Must be called after the last iteration was finished.
  6459. */
  6460. AsyncLoop.prototype.executeNext = function () {
  6461. if (!this._done) {
  6462. if (this.index + 1 < this.iterations) {
  6463. ++this.index;
  6464. this._fn(this);
  6465. }
  6466. else {
  6467. this.breakLoop();
  6468. }
  6469. }
  6470. };
  6471. /**
  6472. * Break the loop and run the success callback.
  6473. */
  6474. AsyncLoop.prototype.breakLoop = function () {
  6475. this._done = true;
  6476. this._successCallback();
  6477. };
  6478. /**
  6479. * Helper function
  6480. */
  6481. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6482. if (offset === void 0) { offset = 0; }
  6483. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6484. loop.executeNext();
  6485. return loop;
  6486. };
  6487. /**
  6488. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6489. * @param iterations total number of iterations
  6490. * @param syncedIterations number of synchronous iterations in each async iteration.
  6491. * @param fn the function to call each iteration.
  6492. * @param callback a success call back that will be called when iterating stops.
  6493. * @param breakFunction a break condition (optional)
  6494. * @param timeout timeout settings for the setTimeout function. default - 0.
  6495. * @constructor
  6496. */
  6497. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6498. if (timeout === void 0) { timeout = 0; }
  6499. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6500. if (breakFunction && breakFunction())
  6501. loop.breakLoop();
  6502. else {
  6503. setTimeout(function () {
  6504. for (var i = 0; i < syncedIterations; ++i) {
  6505. var iteration = (loop.index * syncedIterations) + i;
  6506. if (iteration >= iterations)
  6507. break;
  6508. fn(iteration);
  6509. if (breakFunction && breakFunction()) {
  6510. loop.breakLoop();
  6511. break;
  6512. }
  6513. }
  6514. loop.executeNext();
  6515. }, timeout);
  6516. }
  6517. }, callback);
  6518. };
  6519. return AsyncLoop;
  6520. }());
  6521. BABYLON.AsyncLoop = AsyncLoop;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.tools.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. var Internals;
  6527. (function (Internals) {
  6528. var _AlphaState = (function () {
  6529. /**
  6530. * Initializes the state.
  6531. */
  6532. function _AlphaState() {
  6533. this._isAlphaBlendDirty = false;
  6534. this._isBlendFunctionParametersDirty = false;
  6535. this._isBlendEquationParametersDirty = false;
  6536. this._isBlendConstantsDirty = false;
  6537. this._alphaBlend = false;
  6538. this._blendFunctionParameters = new Array(4);
  6539. this._blendEquationParameters = new Array(2);
  6540. this._blendConstants = new Array(4);
  6541. this.reset();
  6542. }
  6543. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6544. get: function () {
  6545. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6546. },
  6547. enumerable: true,
  6548. configurable: true
  6549. });
  6550. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6551. get: function () {
  6552. return this._alphaBlend;
  6553. },
  6554. set: function (value) {
  6555. if (this._alphaBlend === value) {
  6556. return;
  6557. }
  6558. this._alphaBlend = value;
  6559. this._isAlphaBlendDirty = true;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6565. if (this._blendConstants[0] === r &&
  6566. this._blendConstants[1] === g &&
  6567. this._blendConstants[2] === b &&
  6568. this._blendConstants[3] === a) {
  6569. return;
  6570. }
  6571. this._blendConstants[0] = r;
  6572. this._blendConstants[1] = g;
  6573. this._blendConstants[2] = b;
  6574. this._blendConstants[3] = a;
  6575. this._isBlendConstantsDirty = true;
  6576. };
  6577. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6578. if (this._blendFunctionParameters[0] === value0 &&
  6579. this._blendFunctionParameters[1] === value1 &&
  6580. this._blendFunctionParameters[2] === value2 &&
  6581. this._blendFunctionParameters[3] === value3) {
  6582. return;
  6583. }
  6584. this._blendFunctionParameters[0] = value0;
  6585. this._blendFunctionParameters[1] = value1;
  6586. this._blendFunctionParameters[2] = value2;
  6587. this._blendFunctionParameters[3] = value3;
  6588. this._isBlendFunctionParametersDirty = true;
  6589. };
  6590. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6591. if (this._blendEquationParameters[0] === rgb &&
  6592. this._blendEquationParameters[1] === alpha) {
  6593. return;
  6594. }
  6595. this._blendEquationParameters[0] = rgb;
  6596. this._blendEquationParameters[1] = alpha;
  6597. this._isBlendEquationParametersDirty = true;
  6598. };
  6599. _AlphaState.prototype.reset = function () {
  6600. this._alphaBlend = false;
  6601. this._blendFunctionParameters[0] = null;
  6602. this._blendFunctionParameters[1] = null;
  6603. this._blendFunctionParameters[2] = null;
  6604. this._blendFunctionParameters[3] = null;
  6605. this._blendEquationParameters[0] = null;
  6606. this._blendEquationParameters[1] = null;
  6607. this._blendConstants[0] = null;
  6608. this._blendConstants[1] = null;
  6609. this._blendConstants[2] = null;
  6610. this._blendConstants[3] = null;
  6611. this._isAlphaBlendDirty = true;
  6612. this._isBlendFunctionParametersDirty = false;
  6613. this._isBlendEquationParametersDirty = false;
  6614. this._isBlendConstantsDirty = false;
  6615. };
  6616. _AlphaState.prototype.apply = function (gl) {
  6617. if (!this.isDirty) {
  6618. return;
  6619. }
  6620. // Alpha blend
  6621. if (this._isAlphaBlendDirty) {
  6622. if (this._alphaBlend) {
  6623. gl.enable(gl.BLEND);
  6624. }
  6625. else {
  6626. gl.disable(gl.BLEND);
  6627. }
  6628. this._isAlphaBlendDirty = false;
  6629. }
  6630. // Alpha function
  6631. if (this._isBlendFunctionParametersDirty) {
  6632. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6633. this._isBlendFunctionParametersDirty = false;
  6634. }
  6635. // Alpha equation
  6636. if (this._isBlendEquationParametersDirty) {
  6637. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6638. this._isBlendEquationParametersDirty = false;
  6639. }
  6640. // Constants
  6641. if (this._isBlendConstantsDirty) {
  6642. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6643. this._isBlendConstantsDirty = false;
  6644. }
  6645. };
  6646. return _AlphaState;
  6647. }());
  6648. Internals._AlphaState = _AlphaState;
  6649. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6650. })(BABYLON || (BABYLON = {}));
  6651. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6652. var BABYLON;
  6653. (function (BABYLON) {
  6654. var Internals;
  6655. (function (Internals) {
  6656. var _DepthCullingState = (function () {
  6657. /**
  6658. * Initializes the state.
  6659. */
  6660. function _DepthCullingState() {
  6661. this._isDepthTestDirty = false;
  6662. this._isDepthMaskDirty = false;
  6663. this._isDepthFuncDirty = false;
  6664. this._isCullFaceDirty = false;
  6665. this._isCullDirty = false;
  6666. this._isZOffsetDirty = false;
  6667. this.reset();
  6668. }
  6669. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6670. get: function () {
  6671. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6672. },
  6673. enumerable: true,
  6674. configurable: true
  6675. });
  6676. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6677. get: function () {
  6678. return this._zOffset;
  6679. },
  6680. set: function (value) {
  6681. if (this._zOffset === value) {
  6682. return;
  6683. }
  6684. this._zOffset = value;
  6685. this._isZOffsetDirty = true;
  6686. },
  6687. enumerable: true,
  6688. configurable: true
  6689. });
  6690. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6691. get: function () {
  6692. return this._cullFace;
  6693. },
  6694. set: function (value) {
  6695. if (this._cullFace === value) {
  6696. return;
  6697. }
  6698. this._cullFace = value;
  6699. this._isCullFaceDirty = true;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6705. get: function () {
  6706. return this._cull;
  6707. },
  6708. set: function (value) {
  6709. if (this._cull === value) {
  6710. return;
  6711. }
  6712. this._cull = value;
  6713. this._isCullDirty = true;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6719. get: function () {
  6720. return this._depthFunc;
  6721. },
  6722. set: function (value) {
  6723. if (this._depthFunc === value) {
  6724. return;
  6725. }
  6726. this._depthFunc = value;
  6727. this._isDepthFuncDirty = true;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6733. get: function () {
  6734. return this._depthMask;
  6735. },
  6736. set: function (value) {
  6737. if (this._depthMask === value) {
  6738. return;
  6739. }
  6740. this._depthMask = value;
  6741. this._isDepthMaskDirty = true;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6747. get: function () {
  6748. return this._depthTest;
  6749. },
  6750. set: function (value) {
  6751. if (this._depthTest === value) {
  6752. return;
  6753. }
  6754. this._depthTest = value;
  6755. this._isDepthTestDirty = true;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. _DepthCullingState.prototype.reset = function () {
  6761. this._depthMask = true;
  6762. this._depthTest = true;
  6763. this._depthFunc = null;
  6764. this._cullFace = null;
  6765. this._cull = null;
  6766. this._zOffset = 0;
  6767. this._isDepthTestDirty = true;
  6768. this._isDepthMaskDirty = true;
  6769. this._isDepthFuncDirty = false;
  6770. this._isCullFaceDirty = false;
  6771. this._isCullDirty = false;
  6772. this._isZOffsetDirty = false;
  6773. };
  6774. _DepthCullingState.prototype.apply = function (gl) {
  6775. if (!this.isDirty) {
  6776. return;
  6777. }
  6778. // Cull
  6779. if (this._isCullDirty) {
  6780. if (this.cull) {
  6781. gl.enable(gl.CULL_FACE);
  6782. }
  6783. else {
  6784. gl.disable(gl.CULL_FACE);
  6785. }
  6786. this._isCullDirty = false;
  6787. }
  6788. // Cull face
  6789. if (this._isCullFaceDirty) {
  6790. gl.cullFace(this.cullFace);
  6791. this._isCullFaceDirty = false;
  6792. }
  6793. // Depth mask
  6794. if (this._isDepthMaskDirty) {
  6795. gl.depthMask(this.depthMask);
  6796. this._isDepthMaskDirty = false;
  6797. }
  6798. // Depth test
  6799. if (this._isDepthTestDirty) {
  6800. if (this.depthTest) {
  6801. gl.enable(gl.DEPTH_TEST);
  6802. }
  6803. else {
  6804. gl.disable(gl.DEPTH_TEST);
  6805. }
  6806. this._isDepthTestDirty = false;
  6807. }
  6808. // Depth func
  6809. if (this._isDepthFuncDirty) {
  6810. gl.depthFunc(this.depthFunc);
  6811. this._isDepthFuncDirty = false;
  6812. }
  6813. // zOffset
  6814. if (this._isZOffsetDirty) {
  6815. if (this.zOffset) {
  6816. gl.enable(gl.POLYGON_OFFSET_FILL);
  6817. gl.polygonOffset(this.zOffset, 0);
  6818. }
  6819. else {
  6820. gl.disable(gl.POLYGON_OFFSET_FILL);
  6821. }
  6822. this._isZOffsetDirty = false;
  6823. }
  6824. };
  6825. return _DepthCullingState;
  6826. }());
  6827. Internals._DepthCullingState = _DepthCullingState;
  6828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6829. })(BABYLON || (BABYLON = {}));
  6830. //# sourceMappingURL=babylon.depthCullingState.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var Internals;
  6834. (function (Internals) {
  6835. var _StencilState = (function () {
  6836. function _StencilState() {
  6837. this._isStencilTestDirty = false;
  6838. this._isStencilMaskDirty = false;
  6839. this._isStencilFuncDirty = false;
  6840. this._isStencilOpDirty = false;
  6841. this.reset();
  6842. }
  6843. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6844. get: function () {
  6845. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6851. get: function () {
  6852. return this._stencilFunc;
  6853. },
  6854. set: function (value) {
  6855. if (this._stencilFunc === value) {
  6856. return;
  6857. }
  6858. this._stencilFunc = value;
  6859. this._isStencilFuncDirty = true;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6865. get: function () {
  6866. return this._stencilFuncRef;
  6867. },
  6868. set: function (value) {
  6869. if (this._stencilFuncRef === value) {
  6870. return;
  6871. }
  6872. this._stencilFuncRef = value;
  6873. this._isStencilFuncDirty = true;
  6874. },
  6875. enumerable: true,
  6876. configurable: true
  6877. });
  6878. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6879. get: function () {
  6880. return this._stencilFuncMask;
  6881. },
  6882. set: function (value) {
  6883. if (this._stencilFuncMask === value) {
  6884. return;
  6885. }
  6886. this._stencilFuncMask = value;
  6887. this._isStencilFuncDirty = true;
  6888. },
  6889. enumerable: true,
  6890. configurable: true
  6891. });
  6892. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6893. get: function () {
  6894. return this._stencilOpStencilFail;
  6895. },
  6896. set: function (value) {
  6897. if (this._stencilOpStencilFail === value) {
  6898. return;
  6899. }
  6900. this._stencilOpStencilFail = value;
  6901. this._isStencilOpDirty = true;
  6902. },
  6903. enumerable: true,
  6904. configurable: true
  6905. });
  6906. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6907. get: function () {
  6908. return this._stencilOpDepthFail;
  6909. },
  6910. set: function (value) {
  6911. if (this._stencilOpDepthFail === value) {
  6912. return;
  6913. }
  6914. this._stencilOpDepthFail = value;
  6915. this._isStencilOpDirty = true;
  6916. },
  6917. enumerable: true,
  6918. configurable: true
  6919. });
  6920. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6921. get: function () {
  6922. return this._stencilOpStencilDepthPass;
  6923. },
  6924. set: function (value) {
  6925. if (this._stencilOpStencilDepthPass === value) {
  6926. return;
  6927. }
  6928. this._stencilOpStencilDepthPass = value;
  6929. this._isStencilOpDirty = true;
  6930. },
  6931. enumerable: true,
  6932. configurable: true
  6933. });
  6934. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6935. get: function () {
  6936. return this._stencilMask;
  6937. },
  6938. set: function (value) {
  6939. if (this._stencilMask === value) {
  6940. return;
  6941. }
  6942. this._stencilMask = value;
  6943. this._isStencilMaskDirty = true;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6949. get: function () {
  6950. return this._stencilTest;
  6951. },
  6952. set: function (value) {
  6953. if (this._stencilTest === value) {
  6954. return;
  6955. }
  6956. this._stencilTest = value;
  6957. this._isStencilTestDirty = true;
  6958. },
  6959. enumerable: true,
  6960. configurable: true
  6961. });
  6962. _StencilState.prototype.reset = function () {
  6963. this._stencilTest = false;
  6964. this._stencilMask = 0xFF;
  6965. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6966. this._stencilFuncRef = 1;
  6967. this._stencilFuncMask = 0xFF;
  6968. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6969. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6970. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6971. this._isStencilTestDirty = true;
  6972. this._isStencilMaskDirty = true;
  6973. this._isStencilFuncDirty = true;
  6974. this._isStencilOpDirty = true;
  6975. };
  6976. _StencilState.prototype.apply = function (gl) {
  6977. if (!this.isDirty) {
  6978. return;
  6979. }
  6980. // Stencil test
  6981. if (this._isStencilTestDirty) {
  6982. if (this.stencilTest) {
  6983. gl.enable(gl.STENCIL_TEST);
  6984. }
  6985. else {
  6986. gl.disable(gl.STENCIL_TEST);
  6987. }
  6988. this._isStencilTestDirty = false;
  6989. }
  6990. // Stencil mask
  6991. if (this._isStencilMaskDirty) {
  6992. gl.stencilMask(this.stencilMask);
  6993. this._isStencilMaskDirty = false;
  6994. }
  6995. // Stencil func
  6996. if (this._isStencilFuncDirty) {
  6997. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6998. this._isStencilFuncDirty = false;
  6999. }
  7000. // Stencil op
  7001. if (this._isStencilOpDirty) {
  7002. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7003. this._isStencilOpDirty = false;
  7004. }
  7005. };
  7006. return _StencilState;
  7007. }());
  7008. Internals._StencilState = _StencilState;
  7009. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7010. })(BABYLON || (BABYLON = {}));
  7011. //# sourceMappingURL=babylon.stencilState.js.map
  7012. var BABYLON;
  7013. (function (BABYLON) {
  7014. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7015. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7016. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7017. gl.compileShader(shader);
  7018. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7019. throw new Error(gl.getShaderInfoLog(shader));
  7020. }
  7021. return shader;
  7022. };
  7023. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7024. var magFilter = gl.NEAREST;
  7025. var minFilter = gl.NEAREST;
  7026. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7027. magFilter = gl.LINEAR;
  7028. if (generateMipMaps) {
  7029. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7030. }
  7031. else {
  7032. minFilter = gl.LINEAR;
  7033. }
  7034. }
  7035. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7036. magFilter = gl.LINEAR;
  7037. if (generateMipMaps) {
  7038. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7039. }
  7040. else {
  7041. minFilter = gl.LINEAR;
  7042. }
  7043. }
  7044. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7045. magFilter = gl.NEAREST;
  7046. if (generateMipMaps) {
  7047. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7048. }
  7049. else {
  7050. minFilter = gl.NEAREST;
  7051. }
  7052. }
  7053. return {
  7054. min: minFilter,
  7055. mag: magFilter
  7056. };
  7057. };
  7058. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7060. var engine = scene.getEngine();
  7061. if (!engine) {
  7062. return;
  7063. }
  7064. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7065. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7066. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7068. texture._baseWidth = width;
  7069. texture._baseHeight = height;
  7070. texture._width = potWidth;
  7071. texture._height = potHeight;
  7072. texture.isReady = true;
  7073. processFunction(potWidth, potHeight);
  7074. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7077. if (!noMipmap && !isCompressed) {
  7078. gl.generateMipmap(gl.TEXTURE_2D);
  7079. }
  7080. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7081. engine.resetTextureCache();
  7082. scene._removePendingData(texture);
  7083. texture.onLoadedCallbacks.forEach(function (callback) {
  7084. callback();
  7085. });
  7086. texture.onLoadedCallbacks = [];
  7087. };
  7088. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7089. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7090. var img;
  7091. var onload = function () {
  7092. loadedImages[index] = img;
  7093. loadedImages._internalCount++;
  7094. scene._removePendingData(img);
  7095. if (loadedImages._internalCount === 6) {
  7096. onfinish(loadedImages);
  7097. }
  7098. };
  7099. var onerror = function () {
  7100. scene._removePendingData(img);
  7101. if (onErrorCallBack) {
  7102. onErrorCallBack();
  7103. }
  7104. };
  7105. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7106. scene._addPendingData(img);
  7107. };
  7108. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7109. if (onError === void 0) { onError = null; }
  7110. var loadedImages = [];
  7111. loadedImages._internalCount = 0;
  7112. for (var index = 0; index < 6; index++) {
  7113. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7114. }
  7115. };
  7116. var InstancingAttributeInfo = (function () {
  7117. function InstancingAttributeInfo() {
  7118. }
  7119. return InstancingAttributeInfo;
  7120. }());
  7121. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7122. var EngineCapabilities = (function () {
  7123. function EngineCapabilities() {
  7124. }
  7125. return EngineCapabilities;
  7126. }());
  7127. BABYLON.EngineCapabilities = EngineCapabilities;
  7128. /**
  7129. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7130. */
  7131. var Engine = (function () {
  7132. /**
  7133. * @constructor
  7134. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7135. * @param {boolean} [antialias] - enable antialias
  7136. * @param options - further options to be sent to the getContext function
  7137. */
  7138. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7139. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7140. var _this = this;
  7141. // Public members
  7142. this.isFullscreen = false;
  7143. this.isPointerLock = false;
  7144. this.cullBackFaces = true;
  7145. this.renderEvenInBackground = true;
  7146. this.preventCacheWipeBetweenFrames = false;
  7147. // To enable/disable IDB support and avoid XHR on .manifest
  7148. this.enableOfflineSupport = BABYLON.Database;
  7149. this.scenes = new Array();
  7150. // Observables
  7151. /**
  7152. * Observable event triggered each time the rendering canvas is resized
  7153. */
  7154. this.onResizeObservable = new BABYLON.Observable();
  7155. /**
  7156. * Observable event triggered each time the canvas lost focus
  7157. */
  7158. this.onCanvasBlurObservable = new BABYLON.Observable();
  7159. this._windowIsBackground = false;
  7160. this._webGLVersion = 1.0;
  7161. this._badOS = false;
  7162. this._drawCalls = new BABYLON.PerfCounter();
  7163. this._renderingQueueLaunched = false;
  7164. this._activeRenderLoops = [];
  7165. // FPS
  7166. this.fpsRange = 60;
  7167. this.previousFramesDuration = [];
  7168. this.fps = 60;
  7169. this.deltaTime = 0;
  7170. // States
  7171. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7172. this._stencilState = new BABYLON.Internals._StencilState();
  7173. this._alphaState = new BABYLON.Internals._AlphaState();
  7174. this._alphaMode = Engine.ALPHA_DISABLE;
  7175. // Cache
  7176. this._loadedTexturesCache = new Array();
  7177. this._maxTextureChannels = 16;
  7178. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7179. this._compiledEffects = {};
  7180. this._vertexAttribArraysEnabled = [];
  7181. this._uintIndicesCurrentlySet = false;
  7182. this._currentBoundBuffer = new Array();
  7183. this._currentBufferPointers = [];
  7184. this._currentInstanceLocations = new Array();
  7185. this._currentInstanceBuffers = new Array();
  7186. this._vaoRecordInProgress = false;
  7187. this._mustWipeVertexAttributes = false;
  7188. // Hardware supported Compressed Textures
  7189. this._texturesSupported = new Array();
  7190. this._onVRFullScreenTriggered = function () {
  7191. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7192. //get the old size before we change
  7193. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7194. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7195. //get the width and height, change the render size
  7196. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7197. var width, height;
  7198. _this.setHardwareScalingLevel(1);
  7199. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7200. }
  7201. else {
  7202. //When the specs are implemented, need to uncomment this.
  7203. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7204. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7205. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7206. _this._vrDisplayEnabled = undefined;
  7207. }
  7208. };
  7209. this._renderingCanvas = canvas;
  7210. Engine.Instances.push(this);
  7211. options = options || {};
  7212. if (antialias != null) {
  7213. options.antialias = antialias;
  7214. }
  7215. if (options.preserveDrawingBuffer === undefined) {
  7216. options.preserveDrawingBuffer = false;
  7217. }
  7218. if (options.audioEngine === undefined) {
  7219. options.audioEngine = true;
  7220. }
  7221. if (options.stencil === undefined) {
  7222. options.stencil = true;
  7223. }
  7224. // GL
  7225. if (!options.disableWebGL2Support) {
  7226. try {
  7227. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7228. if (this._gl) {
  7229. this._webGLVersion = 2.0;
  7230. }
  7231. }
  7232. catch (e) {
  7233. // Do nothing
  7234. }
  7235. }
  7236. if (!this._gl) {
  7237. if (!canvas) {
  7238. throw new Error("The provided canvas is null or undefined.");
  7239. }
  7240. try {
  7241. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7242. }
  7243. catch (e) {
  7244. throw new Error("WebGL not supported");
  7245. }
  7246. }
  7247. if (!this._gl) {
  7248. throw new Error("WebGL not supported");
  7249. }
  7250. this._onBlur = function () {
  7251. _this._windowIsBackground = true;
  7252. };
  7253. this._onFocus = function () {
  7254. _this._windowIsBackground = false;
  7255. };
  7256. this._onCanvasBlur = function () {
  7257. _this.onCanvasBlurObservable.notifyObservers(_this);
  7258. };
  7259. window.addEventListener("blur", this._onBlur);
  7260. window.addEventListener("focus", this._onFocus);
  7261. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7262. // Viewport
  7263. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7264. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7265. this.resize();
  7266. // Caps
  7267. this._isStencilEnable = options.stencil;
  7268. this._caps = new EngineCapabilities();
  7269. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7270. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7271. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7272. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7273. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7274. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7275. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7276. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7277. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7278. // Infos
  7279. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7280. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7281. if (rendererInfo != null) {
  7282. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7283. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7284. }
  7285. if (!this._glVendor) {
  7286. this._glVendor = "Unknown vendor";
  7287. }
  7288. if (!this._glRenderer) {
  7289. this._glRenderer = "Unknown renderer";
  7290. }
  7291. // Extensions
  7292. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7293. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7294. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7295. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7296. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7297. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7298. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7299. 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');
  7300. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7301. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7302. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7303. this._caps.highPrecisionShaderSupported = true;
  7304. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7305. // Checks if some of the format renders first to allow the use of webgl inspector.
  7306. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7307. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7308. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7309. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7310. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7311. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7312. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7313. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7314. // Vertex array object
  7315. if (this._webGLVersion > 1) {
  7316. this._caps.vertexArrayObject = true;
  7317. }
  7318. else {
  7319. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7320. if (vertexArrayObjectExtension != null) {
  7321. this._caps.vertexArrayObject = true;
  7322. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7323. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7324. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7325. }
  7326. else {
  7327. this._caps.vertexArrayObject = false;
  7328. }
  7329. }
  7330. // Instances count
  7331. if (this._webGLVersion > 1) {
  7332. this._caps.instancedArrays = true;
  7333. }
  7334. else {
  7335. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7336. if (instanceExtension != null) {
  7337. this._caps.instancedArrays = true;
  7338. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7339. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7340. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7341. }
  7342. else {
  7343. this._caps.instancedArrays = false;
  7344. }
  7345. }
  7346. // Intelligently add supported compressed formats in order to check for.
  7347. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7348. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7349. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7350. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7351. if (this._caps.astc)
  7352. this.texturesSupported.push('-astc.ktx');
  7353. if (this._caps.s3tc)
  7354. this.texturesSupported.push('-dxt.ktx');
  7355. if (this._caps.pvrtc)
  7356. this.texturesSupported.push('-pvrtc.ktx');
  7357. if (this._caps.etc2)
  7358. this.texturesSupported.push('-etc2.ktx');
  7359. if (this._caps.etc1)
  7360. this.texturesSupported.push('-etc1.ktx');
  7361. if (this._gl.getShaderPrecisionFormat) {
  7362. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7363. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7364. }
  7365. // Depth buffer
  7366. this.setDepthBuffer(true);
  7367. this.setDepthFunctionToLessOrEqual();
  7368. this.setDepthWrite(true);
  7369. // Fullscreen
  7370. this._onFullscreenChange = function () {
  7371. if (document.fullscreen !== undefined) {
  7372. _this.isFullscreen = document.fullscreen;
  7373. }
  7374. else if (document.mozFullScreen !== undefined) {
  7375. _this.isFullscreen = document.mozFullScreen;
  7376. }
  7377. else if (document.webkitIsFullScreen !== undefined) {
  7378. _this.isFullscreen = document.webkitIsFullScreen;
  7379. }
  7380. else if (document.msIsFullScreen !== undefined) {
  7381. _this.isFullscreen = document.msIsFullScreen;
  7382. }
  7383. // Pointer lock
  7384. if (_this.isFullscreen && _this._pointerLockRequested) {
  7385. canvas.requestPointerLock = canvas.requestPointerLock ||
  7386. canvas.msRequestPointerLock ||
  7387. canvas.mozRequestPointerLock ||
  7388. canvas.webkitRequestPointerLock;
  7389. if (canvas.requestPointerLock) {
  7390. canvas.requestPointerLock();
  7391. }
  7392. }
  7393. };
  7394. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7395. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7396. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7397. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7398. // Pointer lock
  7399. this._onPointerLockChange = function () {
  7400. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7401. document.webkitPointerLockElement === canvas ||
  7402. document.msPointerLockElement === canvas ||
  7403. document.pointerLockElement === canvas);
  7404. };
  7405. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7406. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7407. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7408. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7409. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7410. Engine.audioEngine = new BABYLON.AudioEngine();
  7411. }
  7412. //Load WebVR Devices
  7413. if (options.autoEnableWebVR) {
  7414. this.initWebVR();
  7415. }
  7416. //Detect if we are running on a faulty buggy OS.
  7417. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7418. //ua sniffing is the tool of the devil.
  7419. this._badOS = regexp.test(navigator.userAgent);
  7420. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7421. }
  7422. Object.defineProperty(Engine, "LastCreatedEngine", {
  7423. get: function () {
  7424. if (Engine.Instances.length === 0) {
  7425. return null;
  7426. }
  7427. return Engine.Instances[Engine.Instances.length - 1];
  7428. },
  7429. enumerable: true,
  7430. configurable: true
  7431. });
  7432. Object.defineProperty(Engine, "LastCreatedScene", {
  7433. get: function () {
  7434. var lastCreatedEngine = Engine.LastCreatedEngine;
  7435. if (!lastCreatedEngine) {
  7436. return null;
  7437. }
  7438. if (lastCreatedEngine.scenes.length === 0) {
  7439. return null;
  7440. }
  7441. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7442. },
  7443. enumerable: true,
  7444. configurable: true
  7445. });
  7446. /**
  7447. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7448. */
  7449. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7450. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7451. var engine = Engine.Instances[engineIndex];
  7452. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7453. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7454. }
  7455. }
  7456. };
  7457. Object.defineProperty(Engine, "NEVER", {
  7458. get: function () {
  7459. return Engine._NEVER;
  7460. },
  7461. enumerable: true,
  7462. configurable: true
  7463. });
  7464. Object.defineProperty(Engine, "ALWAYS", {
  7465. get: function () {
  7466. return Engine._ALWAYS;
  7467. },
  7468. enumerable: true,
  7469. configurable: true
  7470. });
  7471. Object.defineProperty(Engine, "LESS", {
  7472. get: function () {
  7473. return Engine._LESS;
  7474. },
  7475. enumerable: true,
  7476. configurable: true
  7477. });
  7478. Object.defineProperty(Engine, "EQUAL", {
  7479. get: function () {
  7480. return Engine._EQUAL;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(Engine, "LEQUAL", {
  7486. get: function () {
  7487. return Engine._LEQUAL;
  7488. },
  7489. enumerable: true,
  7490. configurable: true
  7491. });
  7492. Object.defineProperty(Engine, "GREATER", {
  7493. get: function () {
  7494. return Engine._GREATER;
  7495. },
  7496. enumerable: true,
  7497. configurable: true
  7498. });
  7499. Object.defineProperty(Engine, "GEQUAL", {
  7500. get: function () {
  7501. return Engine._GEQUAL;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(Engine, "NOTEQUAL", {
  7507. get: function () {
  7508. return Engine._NOTEQUAL;
  7509. },
  7510. enumerable: true,
  7511. configurable: true
  7512. });
  7513. Object.defineProperty(Engine, "KEEP", {
  7514. get: function () {
  7515. return Engine._KEEP;
  7516. },
  7517. enumerable: true,
  7518. configurable: true
  7519. });
  7520. Object.defineProperty(Engine, "REPLACE", {
  7521. get: function () {
  7522. return Engine._REPLACE;
  7523. },
  7524. enumerable: true,
  7525. configurable: true
  7526. });
  7527. Object.defineProperty(Engine, "INCR", {
  7528. get: function () {
  7529. return Engine._INCR;
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(Engine, "DECR", {
  7535. get: function () {
  7536. return Engine._DECR;
  7537. },
  7538. enumerable: true,
  7539. configurable: true
  7540. });
  7541. Object.defineProperty(Engine, "INVERT", {
  7542. get: function () {
  7543. return Engine._INVERT;
  7544. },
  7545. enumerable: true,
  7546. configurable: true
  7547. });
  7548. Object.defineProperty(Engine, "INCR_WRAP", {
  7549. get: function () {
  7550. return Engine._INCR_WRAP;
  7551. },
  7552. enumerable: true,
  7553. configurable: true
  7554. });
  7555. Object.defineProperty(Engine, "DECR_WRAP", {
  7556. get: function () {
  7557. return Engine._DECR_WRAP;
  7558. },
  7559. enumerable: true,
  7560. configurable: true
  7561. });
  7562. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7563. get: function () {
  7564. return Engine._ALPHA_DISABLE;
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7570. get: function () {
  7571. return Engine._ALPHA_ONEONE;
  7572. },
  7573. enumerable: true,
  7574. configurable: true
  7575. });
  7576. Object.defineProperty(Engine, "ALPHA_ADD", {
  7577. get: function () {
  7578. return Engine._ALPHA_ADD;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7584. get: function () {
  7585. return Engine._ALPHA_COMBINE;
  7586. },
  7587. enumerable: true,
  7588. configurable: true
  7589. });
  7590. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7591. get: function () {
  7592. return Engine._ALPHA_SUBTRACT;
  7593. },
  7594. enumerable: true,
  7595. configurable: true
  7596. });
  7597. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7598. get: function () {
  7599. return Engine._ALPHA_MULTIPLY;
  7600. },
  7601. enumerable: true,
  7602. configurable: true
  7603. });
  7604. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7605. get: function () {
  7606. return Engine._ALPHA_MAXIMIZED;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7612. get: function () {
  7613. return Engine._ALPHA_PREMULTIPLIED;
  7614. },
  7615. enumerable: true,
  7616. configurable: true
  7617. });
  7618. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7619. get: function () {
  7620. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7621. },
  7622. enumerable: true,
  7623. configurable: true
  7624. });
  7625. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7626. get: function () {
  7627. return Engine._ALPHA_INTERPOLATE;
  7628. },
  7629. enumerable: true,
  7630. configurable: true
  7631. });
  7632. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7633. get: function () {
  7634. return Engine._ALPHA_SCREENMODE;
  7635. },
  7636. enumerable: true,
  7637. configurable: true
  7638. });
  7639. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7640. get: function () {
  7641. return Engine._DELAYLOADSTATE_NONE;
  7642. },
  7643. enumerable: true,
  7644. configurable: true
  7645. });
  7646. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7647. get: function () {
  7648. return Engine._DELAYLOADSTATE_LOADED;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7654. get: function () {
  7655. return Engine._DELAYLOADSTATE_LOADING;
  7656. },
  7657. enumerable: true,
  7658. configurable: true
  7659. });
  7660. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7661. get: function () {
  7662. return Engine._DELAYLOADSTATE_NOTLOADED;
  7663. },
  7664. enumerable: true,
  7665. configurable: true
  7666. });
  7667. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7668. get: function () {
  7669. return Engine._TEXTUREFORMAT_ALPHA;
  7670. },
  7671. enumerable: true,
  7672. configurable: true
  7673. });
  7674. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7675. get: function () {
  7676. return Engine._TEXTUREFORMAT_LUMINANCE;
  7677. },
  7678. enumerable: true,
  7679. configurable: true
  7680. });
  7681. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7682. get: function () {
  7683. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7684. },
  7685. enumerable: true,
  7686. configurable: true
  7687. });
  7688. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7689. get: function () {
  7690. return Engine._TEXTUREFORMAT_RGB;
  7691. },
  7692. enumerable: true,
  7693. configurable: true
  7694. });
  7695. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7696. get: function () {
  7697. return Engine._TEXTUREFORMAT_RGBA;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7703. get: function () {
  7704. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7705. },
  7706. enumerable: true,
  7707. configurable: true
  7708. });
  7709. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7710. get: function () {
  7711. return Engine._TEXTURETYPE_FLOAT;
  7712. },
  7713. enumerable: true,
  7714. configurable: true
  7715. });
  7716. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7717. get: function () {
  7718. return Engine._TEXTURETYPE_HALF_FLOAT;
  7719. },
  7720. enumerable: true,
  7721. configurable: true
  7722. });
  7723. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7724. get: function () {
  7725. return Engine._SCALEMODE_FLOOR;
  7726. },
  7727. enumerable: true,
  7728. configurable: true
  7729. });
  7730. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7731. get: function () {
  7732. return Engine._SCALEMODE_NEAREST;
  7733. },
  7734. enumerable: true,
  7735. configurable: true
  7736. });
  7737. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7738. get: function () {
  7739. return Engine._SCALEMODE_CEILING;
  7740. },
  7741. enumerable: true,
  7742. configurable: true
  7743. });
  7744. Object.defineProperty(Engine, "Version", {
  7745. get: function () {
  7746. return "3.0-beta";
  7747. },
  7748. enumerable: true,
  7749. configurable: true
  7750. });
  7751. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7752. get: function () {
  7753. return this._texturesSupported;
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7759. get: function () {
  7760. return this._textureFormatInUse;
  7761. },
  7762. enumerable: true,
  7763. configurable: true
  7764. });
  7765. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7766. // Empty texture
  7767. get: function () {
  7768. if (!this._emptyTexture) {
  7769. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7770. }
  7771. return this._emptyTexture;
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7777. get: function () {
  7778. if (!this._emptyCubeTexture) {
  7779. var faceData = new Uint8Array(4);
  7780. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7781. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7782. }
  7783. return this._emptyCubeTexture;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7789. get: function () {
  7790. return this._webGLVersion;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7796. /**
  7797. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7798. */
  7799. get: function () {
  7800. return this._isStencilEnable;
  7801. },
  7802. enumerable: true,
  7803. configurable: true
  7804. });
  7805. Engine.prototype._prepareWorkingCanvas = function () {
  7806. if (this._workingCanvas) {
  7807. return;
  7808. }
  7809. this._workingCanvas = document.createElement("canvas");
  7810. this._workingContext = this._workingCanvas.getContext("2d");
  7811. };
  7812. Engine.prototype.resetTextureCache = function () {
  7813. for (var index = 0; index < this._maxTextureChannels; index++) {
  7814. this._activeTexturesCache[index] = null;
  7815. }
  7816. };
  7817. Engine.prototype.getGlInfo = function () {
  7818. return {
  7819. vendor: this._glVendor,
  7820. renderer: this._glRenderer,
  7821. version: this._glVersion
  7822. };
  7823. };
  7824. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7825. if (useScreen === void 0) { useScreen = false; }
  7826. var viewport = camera.viewport;
  7827. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7828. };
  7829. Engine.prototype.getRenderWidth = function (useScreen) {
  7830. if (useScreen === void 0) { useScreen = false; }
  7831. if (!useScreen && this._currentRenderTarget) {
  7832. return this._currentRenderTarget._width;
  7833. }
  7834. return this._renderingCanvas.width;
  7835. };
  7836. Engine.prototype.getRenderHeight = function (useScreen) {
  7837. if (useScreen === void 0) { useScreen = false; }
  7838. if (!useScreen && this._currentRenderTarget) {
  7839. return this._currentRenderTarget._height;
  7840. }
  7841. return this._renderingCanvas.height;
  7842. };
  7843. Engine.prototype.getRenderingCanvas = function () {
  7844. return this._renderingCanvas;
  7845. };
  7846. Engine.prototype.getRenderingCanvasClientRect = function () {
  7847. return this._renderingCanvas.getBoundingClientRect();
  7848. };
  7849. Engine.prototype.setHardwareScalingLevel = function (level) {
  7850. this._hardwareScalingLevel = level;
  7851. this.resize();
  7852. };
  7853. Engine.prototype.getHardwareScalingLevel = function () {
  7854. return this._hardwareScalingLevel;
  7855. };
  7856. Engine.prototype.getLoadedTexturesCache = function () {
  7857. return this._loadedTexturesCache;
  7858. };
  7859. Engine.prototype.getCaps = function () {
  7860. return this._caps;
  7861. };
  7862. Object.defineProperty(Engine.prototype, "drawCalls", {
  7863. get: function () {
  7864. return this._drawCalls.current;
  7865. },
  7866. enumerable: true,
  7867. configurable: true
  7868. });
  7869. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7870. get: function () {
  7871. return this._drawCalls;
  7872. },
  7873. enumerable: true,
  7874. configurable: true
  7875. });
  7876. Engine.prototype.getDepthFunction = function () {
  7877. return this._depthCullingState.depthFunc;
  7878. };
  7879. Engine.prototype.setDepthFunction = function (depthFunc) {
  7880. this._depthCullingState.depthFunc = depthFunc;
  7881. };
  7882. Engine.prototype.setDepthFunctionToGreater = function () {
  7883. this._depthCullingState.depthFunc = this._gl.GREATER;
  7884. };
  7885. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7886. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7887. };
  7888. Engine.prototype.setDepthFunctionToLess = function () {
  7889. this._depthCullingState.depthFunc = this._gl.LESS;
  7890. };
  7891. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7892. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7893. };
  7894. Engine.prototype.getStencilBuffer = function () {
  7895. return this._stencilState.stencilTest;
  7896. };
  7897. Engine.prototype.setStencilBuffer = function (enable) {
  7898. this._stencilState.stencilTest = enable;
  7899. };
  7900. Engine.prototype.getStencilMask = function () {
  7901. return this._stencilState.stencilMask;
  7902. };
  7903. Engine.prototype.setStencilMask = function (mask) {
  7904. this._stencilState.stencilMask = mask;
  7905. };
  7906. Engine.prototype.getStencilFunction = function () {
  7907. return this._stencilState.stencilFunc;
  7908. };
  7909. Engine.prototype.getStencilFunctionReference = function () {
  7910. return this._stencilState.stencilFuncRef;
  7911. };
  7912. Engine.prototype.getStencilFunctionMask = function () {
  7913. return this._stencilState.stencilFuncMask;
  7914. };
  7915. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7916. this._stencilState.stencilFunc = stencilFunc;
  7917. };
  7918. Engine.prototype.setStencilFunctionReference = function (reference) {
  7919. this._stencilState.stencilFuncRef = reference;
  7920. };
  7921. Engine.prototype.setStencilFunctionMask = function (mask) {
  7922. this._stencilState.stencilFuncMask = mask;
  7923. };
  7924. Engine.prototype.getStencilOperationFail = function () {
  7925. return this._stencilState.stencilOpStencilFail;
  7926. };
  7927. Engine.prototype.getStencilOperationDepthFail = function () {
  7928. return this._stencilState.stencilOpDepthFail;
  7929. };
  7930. Engine.prototype.getStencilOperationPass = function () {
  7931. return this._stencilState.stencilOpStencilDepthPass;
  7932. };
  7933. Engine.prototype.setStencilOperationFail = function (operation) {
  7934. this._stencilState.stencilOpStencilFail = operation;
  7935. };
  7936. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7937. this._stencilState.stencilOpDepthFail = operation;
  7938. };
  7939. Engine.prototype.setStencilOperationPass = function (operation) {
  7940. this._stencilState.stencilOpStencilDepthPass = operation;
  7941. };
  7942. Engine.prototype.setDitheringState = function (value) {
  7943. if (value) {
  7944. this._gl.enable(this._gl.DITHER);
  7945. }
  7946. else {
  7947. this._gl.disable(this._gl.DITHER);
  7948. }
  7949. };
  7950. /**
  7951. * stop executing a render loop function and remove it from the execution array
  7952. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7953. */
  7954. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7955. if (!renderFunction) {
  7956. this._activeRenderLoops = [];
  7957. return;
  7958. }
  7959. var index = this._activeRenderLoops.indexOf(renderFunction);
  7960. if (index >= 0) {
  7961. this._activeRenderLoops.splice(index, 1);
  7962. }
  7963. };
  7964. Engine.prototype._renderLoop = function () {
  7965. var shouldRender = true;
  7966. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7967. shouldRender = false;
  7968. }
  7969. if (shouldRender) {
  7970. // Start new frame
  7971. this.beginFrame();
  7972. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7973. var renderFunction = this._activeRenderLoops[index];
  7974. renderFunction();
  7975. }
  7976. // Present
  7977. this.endFrame();
  7978. }
  7979. if (this._activeRenderLoops.length > 0) {
  7980. // Register new frame
  7981. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7982. }
  7983. else {
  7984. this._renderingQueueLaunched = false;
  7985. }
  7986. };
  7987. /**
  7988. * Register and execute a render loop. The engine can have more than one render function.
  7989. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7990. * @example
  7991. * engine.runRenderLoop(function () {
  7992. * scene.render()
  7993. * })
  7994. */
  7995. Engine.prototype.runRenderLoop = function (renderFunction) {
  7996. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7997. return;
  7998. }
  7999. this._activeRenderLoops.push(renderFunction);
  8000. if (!this._renderingQueueLaunched) {
  8001. this._renderingQueueLaunched = true;
  8002. this._bindedRenderFunction = this._renderLoop.bind(this);
  8003. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8004. }
  8005. };
  8006. /**
  8007. * Toggle full screen mode.
  8008. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8009. * @param {any} options - an options object to be sent to the requestFullscreen function
  8010. */
  8011. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8012. if (this.isFullscreen) {
  8013. BABYLON.Tools.ExitFullscreen();
  8014. }
  8015. else {
  8016. this._pointerLockRequested = requestPointerLock;
  8017. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8018. }
  8019. };
  8020. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8021. if (stencil === void 0) { stencil = false; }
  8022. this.applyStates();
  8023. var mode = 0;
  8024. if (backBuffer && color) {
  8025. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8026. mode |= this._gl.COLOR_BUFFER_BIT;
  8027. }
  8028. if (depth) {
  8029. this._gl.clearDepth(1.0);
  8030. mode |= this._gl.DEPTH_BUFFER_BIT;
  8031. }
  8032. if (stencil) {
  8033. this._gl.clearStencil(0);
  8034. mode |= this._gl.STENCIL_BUFFER_BIT;
  8035. }
  8036. this._gl.clear(mode);
  8037. };
  8038. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8039. var gl = this._gl;
  8040. // Save state
  8041. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8042. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8043. // Change state
  8044. gl.enable(gl.SCISSOR_TEST);
  8045. gl.scissor(x, y, width, height);
  8046. // Clear
  8047. this.clear(clearColor, true, true, true);
  8048. // Restore state
  8049. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8050. if (curScissor === true) {
  8051. gl.enable(gl.SCISSOR_TEST);
  8052. }
  8053. else {
  8054. gl.disable(gl.SCISSOR_TEST);
  8055. }
  8056. };
  8057. /**
  8058. * Set the WebGL's viewport
  8059. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8060. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8061. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8062. */
  8063. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8064. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8065. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8066. var x = viewport.x || 0;
  8067. var y = viewport.y || 0;
  8068. this._cachedViewport = viewport;
  8069. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8070. };
  8071. /**
  8072. * Directly set the WebGL Viewport
  8073. * The x, y, width & height are directly passed to the WebGL call
  8074. * @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.
  8075. */
  8076. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8077. var currentViewport = this._cachedViewport;
  8078. this._cachedViewport = null;
  8079. this._gl.viewport(x, y, width, height);
  8080. return currentViewport;
  8081. };
  8082. Engine.prototype.beginFrame = function () {
  8083. this._measureFps();
  8084. };
  8085. Engine.prototype.endFrame = function () {
  8086. //force a flush in case we are using a bad OS.
  8087. if (this._badOS) {
  8088. this.flushFramebuffer();
  8089. }
  8090. //submit frame to the vr device, if enabled
  8091. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8092. this._vrDisplayEnabled.submitFrame();
  8093. }
  8094. };
  8095. /**
  8096. * resize the view according to the canvas' size.
  8097. * @example
  8098. * window.addEventListener("resize", function () {
  8099. * engine.resize();
  8100. * });
  8101. */
  8102. Engine.prototype.resize = function () {
  8103. // We're not resizing the size of the canvas while in VR mode & presenting
  8104. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8105. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8106. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8107. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8108. }
  8109. };
  8110. /**
  8111. * force a specific size of the canvas
  8112. * @param {number} width - the new canvas' width
  8113. * @param {number} height - the new canvas' height
  8114. */
  8115. Engine.prototype.setSize = function (width, height) {
  8116. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8117. return;
  8118. }
  8119. this._renderingCanvas.width = width;
  8120. this._renderingCanvas.height = height;
  8121. for (var index = 0; index < this.scenes.length; index++) {
  8122. var scene = this.scenes[index];
  8123. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8124. var cam = scene.cameras[camIndex];
  8125. cam._currentRenderId = 0;
  8126. }
  8127. }
  8128. if (this.onResizeObservable.hasObservers) {
  8129. this.onResizeObservable.notifyObservers(this);
  8130. }
  8131. };
  8132. //WebVR functions
  8133. Engine.prototype.isVRDevicePresent = function (callback) {
  8134. this.getVRDevice(null, function (device) {
  8135. callback(device !== null);
  8136. });
  8137. };
  8138. Engine.prototype.getVRDevice = function (name, callback) {
  8139. if (!this.vrDisplaysPromise) {
  8140. callback(null);
  8141. return;
  8142. }
  8143. this.vrDisplaysPromise.then(function (devices) {
  8144. if (devices.length > 0) {
  8145. if (name) {
  8146. var found = devices.some(function (device) {
  8147. if (device.displayName === name) {
  8148. callback(device);
  8149. return true;
  8150. }
  8151. else {
  8152. return false;
  8153. }
  8154. });
  8155. if (!found) {
  8156. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8157. callback(devices[0]);
  8158. }
  8159. }
  8160. else {
  8161. //choose the first one
  8162. callback(devices[0]);
  8163. }
  8164. }
  8165. else {
  8166. BABYLON.Tools.Error("No WebVR devices found!");
  8167. callback(null);
  8168. }
  8169. });
  8170. };
  8171. Engine.prototype.initWebVR = function () {
  8172. if (!this.vrDisplaysPromise) {
  8173. this._getVRDisplays();
  8174. }
  8175. };
  8176. Engine.prototype.enableVR = function (vrDevice) {
  8177. this._vrDisplayEnabled = vrDevice;
  8178. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8179. };
  8180. Engine.prototype.disableVR = function () {
  8181. if (this._vrDisplayEnabled) {
  8182. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8183. }
  8184. };
  8185. Engine.prototype._getVRDisplays = function () {
  8186. var _this = this;
  8187. var getWebVRDevices = function (devices) {
  8188. var size = devices.length;
  8189. var i = 0;
  8190. _this._vrDisplays = devices.filter(function (device) {
  8191. return devices[i] instanceof VRDisplay;
  8192. });
  8193. return _this._vrDisplays;
  8194. };
  8195. //using a key due to typescript
  8196. if (navigator.getVRDisplays) {
  8197. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8198. }
  8199. };
  8200. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8201. this._currentRenderTarget = texture;
  8202. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8203. var gl = this._gl;
  8204. if (texture.isCube) {
  8205. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8206. }
  8207. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8208. this.wipeCaches();
  8209. };
  8210. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8211. if (this._currentFramebuffer !== framebuffer) {
  8212. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8213. this._currentFramebuffer = framebuffer;
  8214. }
  8215. };
  8216. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8217. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8218. this._currentRenderTarget = null;
  8219. // If MSAA, we need to bitblt back to main texture
  8220. var gl = this._gl;
  8221. if (texture._MSAAFramebuffer) {
  8222. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8223. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8224. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8225. }
  8226. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8227. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8228. gl.generateMipmap(gl.TEXTURE_2D);
  8229. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8230. }
  8231. if (onBeforeUnbind) {
  8232. if (texture._MSAAFramebuffer) {
  8233. // Bind the correct framebuffer
  8234. this.bindUnboundFramebuffer(texture._framebuffer);
  8235. }
  8236. onBeforeUnbind();
  8237. }
  8238. this.bindUnboundFramebuffer(null);
  8239. };
  8240. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8241. if (texture.generateMipMaps) {
  8242. var gl = this._gl;
  8243. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8244. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8245. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8246. }
  8247. };
  8248. Engine.prototype.flushFramebuffer = function () {
  8249. this._gl.flush();
  8250. };
  8251. Engine.prototype.restoreDefaultFramebuffer = function () {
  8252. this._currentRenderTarget = null;
  8253. this.bindUnboundFramebuffer(null);
  8254. this.setViewport(this._cachedViewport);
  8255. this.wipeCaches();
  8256. };
  8257. // UBOs
  8258. Engine.prototype.createUniformBuffer = function (elements) {
  8259. var ubo = this._gl.createBuffer();
  8260. this.bindUniformBuffer(ubo);
  8261. if (elements instanceof Float32Array) {
  8262. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8263. }
  8264. else {
  8265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8266. }
  8267. this.bindUniformBuffer(null);
  8268. ubo.references = 1;
  8269. return ubo;
  8270. };
  8271. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8272. var ubo = this._gl.createBuffer();
  8273. this.bindUniformBuffer(ubo);
  8274. if (elements instanceof Float32Array) {
  8275. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8276. }
  8277. else {
  8278. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8279. }
  8280. this.bindUniformBuffer(null);
  8281. ubo.references = 1;
  8282. return ubo;
  8283. };
  8284. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8285. this.bindUniformBuffer(uniformBuffer);
  8286. if (offset === undefined) {
  8287. offset = 0;
  8288. }
  8289. if (count === undefined) {
  8290. if (elements instanceof Float32Array) {
  8291. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8292. }
  8293. else {
  8294. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8295. }
  8296. }
  8297. else {
  8298. if (elements instanceof Float32Array) {
  8299. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8300. }
  8301. else {
  8302. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8303. }
  8304. }
  8305. this.bindUniformBuffer(null);
  8306. };
  8307. // VBOs
  8308. Engine.prototype._resetVertexBufferBinding = function () {
  8309. this.bindArrayBuffer(null);
  8310. this._cachedVertexBuffers = null;
  8311. };
  8312. Engine.prototype.createVertexBuffer = function (vertices) {
  8313. var vbo = this._gl.createBuffer();
  8314. this.bindArrayBuffer(vbo);
  8315. if (vertices instanceof Float32Array) {
  8316. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8317. }
  8318. else {
  8319. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8320. }
  8321. this._resetVertexBufferBinding();
  8322. vbo.references = 1;
  8323. return vbo;
  8324. };
  8325. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8326. var vbo = this._gl.createBuffer();
  8327. this.bindArrayBuffer(vbo);
  8328. if (vertices instanceof Float32Array) {
  8329. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8330. }
  8331. else {
  8332. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8333. }
  8334. this._resetVertexBufferBinding();
  8335. vbo.references = 1;
  8336. return vbo;
  8337. };
  8338. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8339. this.bindArrayBuffer(vertexBuffer);
  8340. if (offset === undefined) {
  8341. offset = 0;
  8342. }
  8343. if (count === undefined) {
  8344. if (vertices instanceof Float32Array) {
  8345. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8346. }
  8347. else {
  8348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8349. }
  8350. }
  8351. else {
  8352. if (vertices instanceof Float32Array) {
  8353. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8354. }
  8355. else {
  8356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8357. }
  8358. }
  8359. this._resetVertexBufferBinding();
  8360. };
  8361. Engine.prototype._resetIndexBufferBinding = function () {
  8362. this.bindIndexBuffer(null);
  8363. this._cachedIndexBuffer = null;
  8364. };
  8365. Engine.prototype.createIndexBuffer = function (indices) {
  8366. var vbo = this._gl.createBuffer();
  8367. this.bindIndexBuffer(vbo);
  8368. // Check for 32 bits indices
  8369. var arrayBuffer;
  8370. var need32Bits = false;
  8371. if (indices instanceof Uint16Array) {
  8372. arrayBuffer = indices;
  8373. }
  8374. else {
  8375. //check 32 bit support
  8376. if (this._caps.uintIndices) {
  8377. if (indices instanceof Uint32Array) {
  8378. arrayBuffer = indices;
  8379. need32Bits = true;
  8380. }
  8381. else {
  8382. //number[] or Int32Array, check if 32 bit is necessary
  8383. for (var index = 0; index < indices.length; index++) {
  8384. if (indices[index] > 65535) {
  8385. need32Bits = true;
  8386. break;
  8387. }
  8388. }
  8389. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8390. }
  8391. }
  8392. else {
  8393. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8394. arrayBuffer = new Uint16Array(indices);
  8395. }
  8396. }
  8397. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8398. this._resetIndexBufferBinding();
  8399. vbo.references = 1;
  8400. vbo.is32Bits = need32Bits;
  8401. return vbo;
  8402. };
  8403. Engine.prototype.bindArrayBuffer = function (buffer) {
  8404. if (!this._vaoRecordInProgress) {
  8405. this._unBindVertexArrayObject();
  8406. }
  8407. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8408. };
  8409. Engine.prototype.bindUniformBuffer = function (buffer) {
  8410. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8411. };
  8412. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8413. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8414. };
  8415. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8416. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8417. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8418. };
  8419. ;
  8420. Engine.prototype.bindIndexBuffer = function (buffer) {
  8421. if (!this._vaoRecordInProgress) {
  8422. this._unBindVertexArrayObject();
  8423. }
  8424. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8425. };
  8426. Engine.prototype.bindBuffer = function (buffer, target) {
  8427. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8428. this._gl.bindBuffer(target, buffer);
  8429. this._currentBoundBuffer[target] = buffer;
  8430. }
  8431. };
  8432. Engine.prototype.updateArrayBuffer = function (data) {
  8433. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8434. };
  8435. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8436. var pointer = this._currentBufferPointers[indx];
  8437. var changed = false;
  8438. if (!pointer) {
  8439. changed = true;
  8440. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8441. }
  8442. else {
  8443. if (pointer.buffer !== buffer) {
  8444. pointer.buffer = buffer;
  8445. changed = true;
  8446. }
  8447. if (pointer.size !== size) {
  8448. pointer.size = size;
  8449. changed = true;
  8450. }
  8451. if (pointer.type !== type) {
  8452. pointer.type = type;
  8453. changed = true;
  8454. }
  8455. if (pointer.normalized !== normalized) {
  8456. pointer.normalized = normalized;
  8457. changed = true;
  8458. }
  8459. if (pointer.stride !== stride) {
  8460. pointer.stride = stride;
  8461. changed = true;
  8462. }
  8463. if (pointer.offset !== offset) {
  8464. pointer.offset = offset;
  8465. changed = true;
  8466. }
  8467. }
  8468. if (changed || this._vaoRecordInProgress) {
  8469. this.bindArrayBuffer(buffer);
  8470. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8471. }
  8472. };
  8473. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8474. if (indexBuffer == null) {
  8475. return;
  8476. }
  8477. if (this._cachedIndexBuffer !== indexBuffer) {
  8478. this._cachedIndexBuffer = indexBuffer;
  8479. this.bindIndexBuffer(indexBuffer);
  8480. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8481. }
  8482. };
  8483. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8484. var attributes = effect.getAttributesNames();
  8485. if (!this._vaoRecordInProgress) {
  8486. this._unBindVertexArrayObject();
  8487. }
  8488. this.unbindAllAttributes();
  8489. for (var index = 0; index < attributes.length; index++) {
  8490. var order = effect.getAttributeLocation(index);
  8491. if (order >= 0) {
  8492. var vertexBuffer = vertexBuffers[attributes[index]];
  8493. if (!vertexBuffer) {
  8494. continue;
  8495. }
  8496. this._gl.enableVertexAttribArray(order);
  8497. if (!this._vaoRecordInProgress) {
  8498. this._vertexAttribArraysEnabled[order] = true;
  8499. }
  8500. var buffer = vertexBuffer.getBuffer();
  8501. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8502. if (vertexBuffer.getIsInstanced()) {
  8503. this._gl.vertexAttribDivisor(order, 1);
  8504. if (!this._vaoRecordInProgress) {
  8505. this._currentInstanceLocations.push(order);
  8506. this._currentInstanceBuffers.push(buffer);
  8507. }
  8508. }
  8509. }
  8510. }
  8511. };
  8512. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8513. var vao = this._gl.createVertexArray();
  8514. this._vaoRecordInProgress = true;
  8515. this._gl.bindVertexArray(vao);
  8516. this._mustWipeVertexAttributes = true;
  8517. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8518. this.bindIndexBuffer(indexBuffer);
  8519. this._vaoRecordInProgress = false;
  8520. this._gl.bindVertexArray(null);
  8521. return vao;
  8522. };
  8523. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8524. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8525. this._cachedVertexArrayObject = vertexArrayObject;
  8526. this._gl.bindVertexArray(vertexArrayObject);
  8527. this._cachedVertexBuffers = null;
  8528. this._cachedIndexBuffer = null;
  8529. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8530. this._mustWipeVertexAttributes = true;
  8531. }
  8532. };
  8533. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8534. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8535. this._cachedVertexBuffers = vertexBuffer;
  8536. this._cachedEffectForVertexBuffers = effect;
  8537. var attributesCount = effect.getAttributesCount();
  8538. this._unBindVertexArrayObject();
  8539. this.unbindAllAttributes();
  8540. var offset = 0;
  8541. for (var index = 0; index < attributesCount; index++) {
  8542. if (index < vertexDeclaration.length) {
  8543. var order = effect.getAttributeLocation(index);
  8544. if (order >= 0) {
  8545. this._gl.enableVertexAttribArray(order);
  8546. this._vertexAttribArraysEnabled[order] = true;
  8547. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8548. }
  8549. offset += vertexDeclaration[index] * 4;
  8550. }
  8551. }
  8552. }
  8553. this._bindIndexBufferWithCache(indexBuffer);
  8554. };
  8555. Engine.prototype._unBindVertexArrayObject = function () {
  8556. if (!this._cachedVertexArrayObject) {
  8557. return;
  8558. }
  8559. this._cachedVertexArrayObject = null;
  8560. this._gl.bindVertexArray(null);
  8561. };
  8562. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8563. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8564. this._cachedVertexBuffers = vertexBuffers;
  8565. this._cachedEffectForVertexBuffers = effect;
  8566. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8567. }
  8568. this._bindIndexBufferWithCache(indexBuffer);
  8569. };
  8570. Engine.prototype.unbindInstanceAttributes = function () {
  8571. var boundBuffer;
  8572. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8573. var instancesBuffer = this._currentInstanceBuffers[i];
  8574. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8575. boundBuffer = instancesBuffer;
  8576. this.bindArrayBuffer(instancesBuffer);
  8577. }
  8578. var offsetLocation = this._currentInstanceLocations[i];
  8579. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8580. }
  8581. this._currentInstanceBuffers.length = 0;
  8582. this._currentInstanceLocations.length = 0;
  8583. };
  8584. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8585. this._gl.deleteVertexArray(vao);
  8586. };
  8587. Engine.prototype._releaseBuffer = function (buffer) {
  8588. buffer.references--;
  8589. if (buffer.references === 0) {
  8590. this._gl.deleteBuffer(buffer);
  8591. return true;
  8592. }
  8593. return false;
  8594. };
  8595. Engine.prototype.createInstancesBuffer = function (capacity) {
  8596. var buffer = this._gl.createBuffer();
  8597. buffer.capacity = capacity;
  8598. this.bindArrayBuffer(buffer);
  8599. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8600. return buffer;
  8601. };
  8602. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8603. this._gl.deleteBuffer(buffer);
  8604. };
  8605. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8606. this.bindArrayBuffer(instancesBuffer);
  8607. if (data) {
  8608. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8609. }
  8610. if (offsetLocations[0].index !== undefined) {
  8611. var stride = 0;
  8612. for (var i = 0; i < offsetLocations.length; i++) {
  8613. var ai = offsetLocations[i];
  8614. stride += ai.attributeSize * 4;
  8615. }
  8616. for (var i = 0; i < offsetLocations.length; i++) {
  8617. var ai = offsetLocations[i];
  8618. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8619. this._gl.enableVertexAttribArray(ai.index);
  8620. this._vertexAttribArraysEnabled[ai.index] = true;
  8621. }
  8622. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8623. this._gl.vertexAttribDivisor(ai.index, 1);
  8624. this._currentInstanceLocations.push(ai.index);
  8625. this._currentInstanceBuffers.push(instancesBuffer);
  8626. }
  8627. }
  8628. else {
  8629. for (var index = 0; index < 4; index++) {
  8630. var offsetLocation = offsetLocations[index];
  8631. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8632. this._gl.enableVertexAttribArray(offsetLocation);
  8633. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8634. }
  8635. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8636. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8637. this._currentInstanceLocations.push(offsetLocation);
  8638. this._currentInstanceBuffers.push(instancesBuffer);
  8639. }
  8640. }
  8641. };
  8642. Engine.prototype.applyStates = function () {
  8643. this._depthCullingState.apply(this._gl);
  8644. this._stencilState.apply(this._gl);
  8645. this._alphaState.apply(this._gl);
  8646. };
  8647. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8648. // Apply states
  8649. this.applyStates();
  8650. this._drawCalls.addCount(1, false);
  8651. // Render
  8652. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8653. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8654. if (instancesCount) {
  8655. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8656. return;
  8657. }
  8658. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8659. };
  8660. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8661. // Apply states
  8662. this.applyStates();
  8663. this._drawCalls.addCount(1, false);
  8664. if (instancesCount) {
  8665. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8666. return;
  8667. }
  8668. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8669. };
  8670. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8671. // Apply states
  8672. this.applyStates();
  8673. this._drawCalls.addCount(1, false);
  8674. if (instancesCount) {
  8675. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8676. return;
  8677. }
  8678. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8679. };
  8680. // Shaders
  8681. Engine.prototype._releaseEffect = function (effect) {
  8682. if (this._compiledEffects[effect._key]) {
  8683. delete this._compiledEffects[effect._key];
  8684. if (effect.getProgram()) {
  8685. this._gl.deleteProgram(effect.getProgram());
  8686. }
  8687. }
  8688. };
  8689. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8690. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8691. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8692. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8693. if (this._compiledEffects[name]) {
  8694. return this._compiledEffects[name];
  8695. }
  8696. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8697. effect._key = name;
  8698. this._compiledEffects[name] = effect;
  8699. return effect;
  8700. };
  8701. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8702. if (uniformsNames === void 0) { uniformsNames = []; }
  8703. if (samplers === void 0) { samplers = []; }
  8704. if (defines === void 0) { defines = ""; }
  8705. return this.createEffect({
  8706. vertex: "particles",
  8707. fragmentElement: fragmentName
  8708. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8709. };
  8710. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8711. context = context || this._gl;
  8712. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8713. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8714. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8715. var shaderProgram = context.createProgram();
  8716. context.attachShader(shaderProgram, vertexShader);
  8717. context.attachShader(shaderProgram, fragmentShader);
  8718. context.linkProgram(shaderProgram);
  8719. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8720. if (!linked) {
  8721. var error = context.getProgramInfoLog(shaderProgram);
  8722. if (error) {
  8723. throw new Error(error);
  8724. }
  8725. }
  8726. context.deleteShader(vertexShader);
  8727. context.deleteShader(fragmentShader);
  8728. return shaderProgram;
  8729. };
  8730. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8731. var results = [];
  8732. for (var index = 0; index < uniformsNames.length; index++) {
  8733. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8734. }
  8735. return results;
  8736. };
  8737. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8738. var results = [];
  8739. for (var index = 0; index < attributesNames.length; index++) {
  8740. try {
  8741. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8742. }
  8743. catch (e) {
  8744. results.push(-1);
  8745. }
  8746. }
  8747. return results;
  8748. };
  8749. Engine.prototype.enableEffect = function (effect) {
  8750. // Use program
  8751. this.setProgram(effect.getProgram());
  8752. this._currentEffect = effect;
  8753. if (effect.onBind) {
  8754. effect.onBind(effect);
  8755. }
  8756. };
  8757. Engine.prototype.setIntArray = function (uniform, array) {
  8758. if (!uniform)
  8759. return;
  8760. this._gl.uniform1iv(uniform, array);
  8761. };
  8762. Engine.prototype.setIntArray2 = function (uniform, array) {
  8763. if (!uniform || array.length % 2 !== 0)
  8764. return;
  8765. this._gl.uniform2iv(uniform, array);
  8766. };
  8767. Engine.prototype.setIntArray3 = function (uniform, array) {
  8768. if (!uniform || array.length % 3 !== 0)
  8769. return;
  8770. this._gl.uniform3iv(uniform, array);
  8771. };
  8772. Engine.prototype.setIntArray4 = function (uniform, array) {
  8773. if (!uniform || array.length % 4 !== 0)
  8774. return;
  8775. this._gl.uniform4iv(uniform, array);
  8776. };
  8777. Engine.prototype.setFloatArray = function (uniform, array) {
  8778. if (!uniform)
  8779. return;
  8780. this._gl.uniform1fv(uniform, array);
  8781. };
  8782. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8783. if (!uniform || array.length % 2 !== 0)
  8784. return;
  8785. this._gl.uniform2fv(uniform, array);
  8786. };
  8787. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8788. if (!uniform || array.length % 3 !== 0)
  8789. return;
  8790. this._gl.uniform3fv(uniform, array);
  8791. };
  8792. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8793. if (!uniform || array.length % 4 !== 0)
  8794. return;
  8795. this._gl.uniform4fv(uniform, array);
  8796. };
  8797. Engine.prototype.setArray = function (uniform, array) {
  8798. if (!uniform)
  8799. return;
  8800. this._gl.uniform1fv(uniform, array);
  8801. };
  8802. Engine.prototype.setArray2 = function (uniform, array) {
  8803. if (!uniform || array.length % 2 !== 0)
  8804. return;
  8805. this._gl.uniform2fv(uniform, array);
  8806. };
  8807. Engine.prototype.setArray3 = function (uniform, array) {
  8808. if (!uniform || array.length % 3 !== 0)
  8809. return;
  8810. this._gl.uniform3fv(uniform, array);
  8811. };
  8812. Engine.prototype.setArray4 = function (uniform, array) {
  8813. if (!uniform || array.length % 4 !== 0)
  8814. return;
  8815. this._gl.uniform4fv(uniform, array);
  8816. };
  8817. Engine.prototype.setMatrices = function (uniform, matrices) {
  8818. if (!uniform)
  8819. return;
  8820. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8821. };
  8822. Engine.prototype.setMatrix = function (uniform, matrix) {
  8823. if (!uniform)
  8824. return;
  8825. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8826. };
  8827. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8828. if (!uniform)
  8829. return;
  8830. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8831. };
  8832. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8833. if (!uniform)
  8834. return;
  8835. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8836. };
  8837. Engine.prototype.setFloat = function (uniform, value) {
  8838. if (!uniform)
  8839. return;
  8840. this._gl.uniform1f(uniform, value);
  8841. };
  8842. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8843. if (!uniform)
  8844. return;
  8845. this._gl.uniform2f(uniform, x, y);
  8846. };
  8847. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8848. if (!uniform)
  8849. return;
  8850. this._gl.uniform3f(uniform, x, y, z);
  8851. };
  8852. Engine.prototype.setBool = function (uniform, bool) {
  8853. if (!uniform)
  8854. return;
  8855. this._gl.uniform1i(uniform, bool);
  8856. };
  8857. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8858. if (!uniform)
  8859. return;
  8860. this._gl.uniform4f(uniform, x, y, z, w);
  8861. };
  8862. Engine.prototype.setColor3 = function (uniform, color3) {
  8863. if (!uniform)
  8864. return;
  8865. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8866. };
  8867. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8868. if (!uniform)
  8869. return;
  8870. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8871. };
  8872. // States
  8873. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8874. if (zOffset === void 0) { zOffset = 0; }
  8875. if (reverseSide === void 0) { reverseSide = false; }
  8876. // Culling
  8877. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8878. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8879. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8880. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8881. if (culling) {
  8882. this._depthCullingState.cullFace = cullFace;
  8883. this._depthCullingState.cull = true;
  8884. }
  8885. else {
  8886. this._depthCullingState.cull = false;
  8887. }
  8888. }
  8889. // Z offset
  8890. this._depthCullingState.zOffset = zOffset;
  8891. };
  8892. Engine.prototype.setDepthBuffer = function (enable) {
  8893. this._depthCullingState.depthTest = enable;
  8894. };
  8895. Engine.prototype.getDepthWrite = function () {
  8896. return this._depthCullingState.depthMask;
  8897. };
  8898. Engine.prototype.setDepthWrite = function (enable) {
  8899. this._depthCullingState.depthMask = enable;
  8900. };
  8901. Engine.prototype.setColorWrite = function (enable) {
  8902. this._gl.colorMask(enable, enable, enable, enable);
  8903. };
  8904. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8905. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8906. };
  8907. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8908. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8909. if (this._alphaMode === mode) {
  8910. return;
  8911. }
  8912. switch (mode) {
  8913. case Engine.ALPHA_DISABLE:
  8914. this._alphaState.alphaBlend = false;
  8915. break;
  8916. case Engine.ALPHA_PREMULTIPLIED:
  8917. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8918. this._alphaState.alphaBlend = true;
  8919. break;
  8920. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8921. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8922. this._alphaState.alphaBlend = true;
  8923. break;
  8924. case Engine.ALPHA_COMBINE:
  8925. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8926. this._alphaState.alphaBlend = true;
  8927. break;
  8928. case Engine.ALPHA_ONEONE:
  8929. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8930. this._alphaState.alphaBlend = true;
  8931. break;
  8932. case Engine.ALPHA_ADD:
  8933. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8934. this._alphaState.alphaBlend = true;
  8935. break;
  8936. case Engine.ALPHA_SUBTRACT:
  8937. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8938. this._alphaState.alphaBlend = true;
  8939. break;
  8940. case Engine.ALPHA_MULTIPLY:
  8941. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8942. this._alphaState.alphaBlend = true;
  8943. break;
  8944. case Engine.ALPHA_MAXIMIZED:
  8945. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8946. this._alphaState.alphaBlend = true;
  8947. break;
  8948. case Engine.ALPHA_INTERPOLATE:
  8949. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8950. this._alphaState.alphaBlend = true;
  8951. break;
  8952. case Engine.ALPHA_SCREENMODE:
  8953. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8954. this._alphaState.alphaBlend = true;
  8955. break;
  8956. }
  8957. if (!noDepthWriteChange) {
  8958. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8959. }
  8960. this._alphaMode = mode;
  8961. };
  8962. Engine.prototype.getAlphaMode = function () {
  8963. return this._alphaMode;
  8964. };
  8965. Engine.prototype.setAlphaTesting = function (enable) {
  8966. this._alphaTest = enable;
  8967. };
  8968. Engine.prototype.getAlphaTesting = function () {
  8969. return !!this._alphaTest;
  8970. };
  8971. // Textures
  8972. Engine.prototype.wipeCaches = function (bruteForce) {
  8973. if (this.preventCacheWipeBetweenFrames) {
  8974. return;
  8975. }
  8976. this.resetTextureCache();
  8977. this._currentEffect = null;
  8978. // 6/8/2017: deltakosh: Should not be required anymore.
  8979. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  8980. if (bruteForce) {
  8981. this._stencilState.reset();
  8982. this._depthCullingState.reset();
  8983. this.setDepthFunctionToLessOrEqual();
  8984. this._alphaState.reset();
  8985. }
  8986. this._cachedVertexBuffers = null;
  8987. this._cachedIndexBuffer = null;
  8988. this._cachedEffectForVertexBuffers = null;
  8989. this._unBindVertexArrayObject();
  8990. this.bindIndexBuffer(null);
  8991. this.bindArrayBuffer(null);
  8992. };
  8993. /**
  8994. * Set the compressed texture format to use, based on the formats you have, and the formats
  8995. * supported by the hardware / browser.
  8996. *
  8997. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8998. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8999. * to API arguments needed to compressed textures. This puts the burden on the container
  9000. * generator to house the arcane code for determining these for current & future formats.
  9001. *
  9002. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9003. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9004. *
  9005. * Note: The result of this call is not taken into account when a texture is base64.
  9006. *
  9007. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9008. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9009. *
  9010. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9011. * @returns The extension selected.
  9012. */
  9013. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9014. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9015. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9016. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9017. return this._textureFormatInUse = this._texturesSupported[i];
  9018. }
  9019. }
  9020. }
  9021. // actively set format to nothing, to allow this to be called more than once
  9022. // and possibly fail the 2nd time
  9023. return this._textureFormatInUse = null;
  9024. };
  9025. /**
  9026. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9027. * @param {string} urlArg- This contains one of the following:
  9028. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9029. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9030. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9031. *
  9032. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9033. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9034. * @param {Scene} scene- Needed for loading to the correct scene.
  9035. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9036. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9037. * @param {callback} onError- Optional callback to be called upon failure.
  9038. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9039. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9040. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9041. *
  9042. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9043. */
  9044. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9045. var _this = this;
  9046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9047. if (onLoad === void 0) { onLoad = null; }
  9048. if (onError === void 0) { onError = null; }
  9049. if (buffer === void 0) { buffer = null; }
  9050. var texture = fallBack ? fallBack : this._gl.createTexture();
  9051. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9052. var fromData = url.substr(0, 5) === "data:";
  9053. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9054. // establish the file extension, if possible
  9055. var lastDot = url.lastIndexOf('.');
  9056. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9057. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9058. if (isDDS) {
  9059. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9060. }
  9061. var isTGA = (extension === ".tga");
  9062. // determine if a ktx file should be substituted
  9063. var isKTX = false;
  9064. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9065. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9066. isKTX = true;
  9067. }
  9068. scene._addPendingData(texture);
  9069. texture.url = url;
  9070. texture.noMipmap = noMipmap;
  9071. texture.references = 1;
  9072. texture.samplingMode = samplingMode;
  9073. texture.onLoadedCallbacks = [];
  9074. if (onLoad) {
  9075. texture.onLoadedCallbacks.push(onLoad);
  9076. }
  9077. if (!fallBack)
  9078. this._loadedTexturesCache.push(texture);
  9079. var onerror = function () {
  9080. scene._removePendingData(texture);
  9081. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9082. if (isKTX) {
  9083. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9084. }
  9085. else if (onError) {
  9086. onError();
  9087. }
  9088. };
  9089. var callback;
  9090. // processing for non-image formats
  9091. if (isKTX || isTGA || isDDS) {
  9092. if (isKTX) {
  9093. callback = function (data) {
  9094. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9095. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9096. ktx.uploadLevels(_this._gl, !noMipmap);
  9097. }, samplingMode);
  9098. };
  9099. }
  9100. else if (isTGA) {
  9101. callback = function (arrayBuffer) {
  9102. var data = new Uint8Array(arrayBuffer);
  9103. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9104. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9105. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9106. }, samplingMode);
  9107. };
  9108. }
  9109. else if (isDDS) {
  9110. callback = function (data) {
  9111. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9112. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9113. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9114. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9115. }, samplingMode);
  9116. };
  9117. }
  9118. if (!buffer) {
  9119. BABYLON.Tools.LoadFile(url, function (data) {
  9120. callback(data);
  9121. }, null, scene.database, true, onerror);
  9122. }
  9123. else {
  9124. callback(buffer);
  9125. }
  9126. // image format processing
  9127. }
  9128. else {
  9129. var onload = function (img) {
  9130. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9131. var isPot = (img.width === potWidth && img.height === potHeight);
  9132. if (!isPot) {
  9133. _this._prepareWorkingCanvas();
  9134. _this._workingCanvas.width = potWidth;
  9135. _this._workingCanvas.height = potHeight;
  9136. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9137. _this._workingContext.imageSmoothingEnabled = false;
  9138. _this._workingContext.mozImageSmoothingEnabled = false;
  9139. _this._workingContext.oImageSmoothingEnabled = false;
  9140. _this._workingContext.webkitImageSmoothingEnabled = false;
  9141. _this._workingContext.msImageSmoothingEnabled = false;
  9142. }
  9143. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9144. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9145. _this._workingContext.imageSmoothingEnabled = true;
  9146. _this._workingContext.mozImageSmoothingEnabled = true;
  9147. _this._workingContext.oImageSmoothingEnabled = true;
  9148. _this._workingContext.webkitImageSmoothingEnabled = true;
  9149. _this._workingContext.msImageSmoothingEnabled = true;
  9150. }
  9151. }
  9152. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9153. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9154. }, samplingMode);
  9155. };
  9156. if (!fromData || isBase64)
  9157. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9158. else if (buffer instanceof Array || typeof buffer === "string")
  9159. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9160. else
  9161. onload(buffer);
  9162. }
  9163. return texture;
  9164. };
  9165. Engine.prototype._getInternalFormat = function (format) {
  9166. var internalFormat = this._gl.RGBA;
  9167. switch (format) {
  9168. case Engine.TEXTUREFORMAT_ALPHA:
  9169. internalFormat = this._gl.ALPHA;
  9170. break;
  9171. case Engine.TEXTUREFORMAT_LUMINANCE:
  9172. internalFormat = this._gl.LUMINANCE;
  9173. break;
  9174. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9175. internalFormat = this._gl.LUMINANCE_ALPHA;
  9176. break;
  9177. case Engine.TEXTUREFORMAT_RGB:
  9178. internalFormat = this._gl.RGB;
  9179. break;
  9180. case Engine.TEXTUREFORMAT_RGBA:
  9181. internalFormat = this._gl.RGBA;
  9182. break;
  9183. }
  9184. return internalFormat;
  9185. };
  9186. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9187. if (compression === void 0) { compression = null; }
  9188. var internalFormat = this._getInternalFormat(format);
  9189. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9190. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9191. if (texture._width % 4 !== 0) {
  9192. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9193. }
  9194. if (compression) {
  9195. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9196. }
  9197. else {
  9198. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9199. }
  9200. if (texture.generateMipMaps) {
  9201. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9202. }
  9203. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9204. this.resetTextureCache();
  9205. texture.isReady = true;
  9206. };
  9207. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9208. if (compression === void 0) { compression = null; }
  9209. var texture = this._gl.createTexture();
  9210. texture._baseWidth = width;
  9211. texture._baseHeight = height;
  9212. texture._width = width;
  9213. texture._height = height;
  9214. texture.references = 1;
  9215. this.updateRawTexture(texture, data, format, invertY, compression);
  9216. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9217. // Filters
  9218. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9219. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9220. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9221. if (generateMipMaps) {
  9222. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9223. }
  9224. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9225. texture.samplingMode = samplingMode;
  9226. this._loadedTexturesCache.push(texture);
  9227. return texture;
  9228. };
  9229. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9230. var texture = this._gl.createTexture();
  9231. texture._baseWidth = width;
  9232. texture._baseHeight = height;
  9233. if (generateMipMaps) {
  9234. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9235. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9236. }
  9237. this.resetTextureCache();
  9238. texture._width = width;
  9239. texture._height = height;
  9240. texture.isReady = false;
  9241. texture.generateMipMaps = generateMipMaps;
  9242. texture.references = 1;
  9243. texture.samplingMode = samplingMode;
  9244. this.updateTextureSamplingMode(samplingMode, texture);
  9245. this._loadedTexturesCache.push(texture);
  9246. return texture;
  9247. };
  9248. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9249. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9250. if (texture.isCube) {
  9251. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9252. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9253. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9254. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9255. }
  9256. else {
  9257. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9258. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9259. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9260. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9261. }
  9262. texture.samplingMode = samplingMode;
  9263. };
  9264. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9265. if (premulAlpha === void 0) { premulAlpha = false; }
  9266. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9267. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9268. if (premulAlpha) {
  9269. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9270. }
  9271. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9272. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9273. if (texture.generateMipMaps) {
  9274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9275. }
  9276. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9277. if (premulAlpha) {
  9278. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9279. }
  9280. this.resetTextureCache();
  9281. texture.isReady = true;
  9282. };
  9283. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9284. if (texture._isDisabled) {
  9285. return;
  9286. }
  9287. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9288. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9289. try {
  9290. // Testing video texture support
  9291. if (this._videoTextureSupported === undefined) {
  9292. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9293. if (this._gl.getError() !== 0) {
  9294. this._videoTextureSupported = false;
  9295. }
  9296. else {
  9297. this._videoTextureSupported = true;
  9298. }
  9299. }
  9300. // Copy video through the current working canvas if video texture is not supported
  9301. if (!this._videoTextureSupported) {
  9302. if (!texture._workingCanvas) {
  9303. texture._workingCanvas = document.createElement("canvas");
  9304. texture._workingContext = texture._workingCanvas.getContext("2d");
  9305. texture._workingCanvas.width = texture._width;
  9306. texture._workingCanvas.height = texture._height;
  9307. }
  9308. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9309. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9310. }
  9311. else {
  9312. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9313. }
  9314. if (texture.generateMipMaps) {
  9315. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9316. }
  9317. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9318. this.resetTextureCache();
  9319. texture.isReady = true;
  9320. }
  9321. catch (ex) {
  9322. // Something unexpected
  9323. // Let's disable the texture
  9324. texture._isDisabled = true;
  9325. }
  9326. };
  9327. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9328. // old version had a "generateMipMaps" arg instead of options.
  9329. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9330. // in the same way, generateDepthBuffer is defaulted to true
  9331. var generateMipMaps = false;
  9332. var generateDepthBuffer = true;
  9333. var generateStencilBuffer = false;
  9334. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9335. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9336. if (options !== undefined) {
  9337. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9338. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9339. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9340. type = options.type === undefined ? type : options.type;
  9341. if (options.samplingMode !== undefined) {
  9342. samplingMode = options.samplingMode;
  9343. }
  9344. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9345. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9346. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9347. }
  9348. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9349. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9350. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9351. }
  9352. }
  9353. var gl = this._gl;
  9354. var texture = gl.createTexture();
  9355. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9356. var width = size.width || size;
  9357. var height = size.height || size;
  9358. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9359. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9360. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9361. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9362. }
  9363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9367. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9368. // Create the framebuffer
  9369. var framebuffer = gl.createFramebuffer();
  9370. this.bindUnboundFramebuffer(framebuffer);
  9371. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9372. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9373. if (generateMipMaps) {
  9374. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9375. }
  9376. // Unbind
  9377. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9378. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9379. this.bindUnboundFramebuffer(null);
  9380. texture._framebuffer = framebuffer;
  9381. texture._baseWidth = width;
  9382. texture._baseHeight = height;
  9383. texture._width = width;
  9384. texture._height = height;
  9385. texture.isReady = true;
  9386. texture.samples = 1;
  9387. texture.generateMipMaps = generateMipMaps;
  9388. texture.references = 1;
  9389. texture.samplingMode = samplingMode;
  9390. texture.type = type;
  9391. texture._generateDepthBuffer = generateDepthBuffer;
  9392. texture._generateStencilBuffer = generateStencilBuffer;
  9393. this.resetTextureCache();
  9394. this._loadedTexturesCache.push(texture);
  9395. return texture;
  9396. };
  9397. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9398. var generateMipMaps = false;
  9399. var generateDepthBuffer = true;
  9400. var generateStencilBuffer = false;
  9401. var generateDepthTexture = false;
  9402. var textureCount = 1;
  9403. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9404. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9405. var types = [], samplingModes = [];
  9406. if (options !== undefined) {
  9407. generateMipMaps = options.generateMipMaps;
  9408. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9409. generateStencilBuffer = options.generateStencilBuffer;
  9410. generateDepthTexture = options.generateDepthTexture;
  9411. textureCount = options.textureCount || 1;
  9412. if (options.types) {
  9413. types = options.types;
  9414. }
  9415. if (options.samplingModes) {
  9416. samplingModes = options.samplingModes;
  9417. }
  9418. }
  9419. var gl = this._gl;
  9420. // Create the framebuffer
  9421. var framebuffer = gl.createFramebuffer();
  9422. this.bindUnboundFramebuffer(framebuffer);
  9423. var colorRenderbuffer = gl.createRenderbuffer();
  9424. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9425. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9426. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9427. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9428. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9429. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  9430. var width = size.width || size;
  9431. var height = size.height || size;
  9432. var textures = [];
  9433. var attachments = [];
  9434. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9435. for (var i = 0; i < textureCount; i++) {
  9436. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9437. var type = types[i] || defaultType;
  9438. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9439. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9440. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9441. }
  9442. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9443. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9444. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9445. }
  9446. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9447. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9448. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9449. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9450. }
  9451. var texture = gl.createTexture();
  9452. var attachment = gl["COLOR_ATTACHMENT" + i];
  9453. textures.push(texture);
  9454. attachments.push(attachment);
  9455. gl.activeTexture(gl["TEXTURE" + i]);
  9456. gl.bindTexture(gl.TEXTURE_2D, texture);
  9457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9461. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9462. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9463. if (generateMipMaps) {
  9464. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9465. }
  9466. // Unbind
  9467. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9468. texture._framebuffer = framebuffer;
  9469. texture._depthStencilBuffer = depthStencilBuffer;
  9470. texture._baseWidth = width;
  9471. texture._baseHeight = height;
  9472. texture._width = width;
  9473. texture._height = height;
  9474. texture.isReady = true;
  9475. texture.samples = 1;
  9476. texture.generateMipMaps = generateMipMaps;
  9477. texture.references = 1;
  9478. texture.samplingMode = samplingMode;
  9479. texture.type = type;
  9480. texture._generateDepthBuffer = generateDepthBuffer;
  9481. texture._generateStencilBuffer = generateStencilBuffer;
  9482. this._loadedTexturesCache.push(texture);
  9483. }
  9484. if (generateDepthTexture) {
  9485. // Depth texture
  9486. var depthTexture = gl.createTexture();
  9487. gl.activeTexture(gl.TEXTURE0);
  9488. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9490. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9491. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9492. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9493. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9494. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9495. depthTexture._framebuffer = framebuffer;
  9496. depthTexture._baseWidth = width;
  9497. depthTexture._baseHeight = height;
  9498. depthTexture._width = width;
  9499. depthTexture._height = height;
  9500. depthTexture.isReady = true;
  9501. depthTexture.samples = 1;
  9502. depthTexture.generateMipMaps = generateMipMaps;
  9503. depthTexture.references = 1;
  9504. depthTexture.samplingMode = gl.NEAREST;
  9505. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9506. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9507. textures.push(depthTexture);
  9508. this._loadedTexturesCache.push(depthTexture);
  9509. }
  9510. gl.drawBuffers(attachments);
  9511. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9512. this.bindUnboundFramebuffer(null);
  9513. this.resetTextureCache();
  9514. return textures;
  9515. };
  9516. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9517. if (samples === void 0) { samples = 1; }
  9518. var depthStencilBuffer = null;
  9519. var gl = this._gl;
  9520. // Create the depth/stencil buffer
  9521. if (generateStencilBuffer) {
  9522. depthStencilBuffer = gl.createRenderbuffer();
  9523. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9524. if (samples > 1) {
  9525. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9526. }
  9527. else {
  9528. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9529. }
  9530. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9531. }
  9532. else if (generateDepthBuffer) {
  9533. depthStencilBuffer = gl.createRenderbuffer();
  9534. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9535. if (samples > 1) {
  9536. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9537. }
  9538. else {
  9539. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9540. }
  9541. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9542. }
  9543. return depthStencilBuffer;
  9544. };
  9545. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9546. if (this.webGLVersion < 2) {
  9547. return 1;
  9548. }
  9549. if (texture.samples === samples) {
  9550. return samples;
  9551. }
  9552. var gl = this._gl;
  9553. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9554. // Dispose previous render buffers
  9555. if (texture._depthStencilBuffer) {
  9556. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9557. }
  9558. if (texture._MSAAFramebuffer) {
  9559. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9560. }
  9561. if (texture._MSAARenderBuffer) {
  9562. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9563. }
  9564. if (samples > 1) {
  9565. texture._MSAAFramebuffer = gl.createFramebuffer();
  9566. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9567. var colorRenderbuffer = gl.createRenderbuffer();
  9568. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9569. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9570. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9571. texture._MSAARenderBuffer = colorRenderbuffer;
  9572. }
  9573. else {
  9574. this.bindUnboundFramebuffer(texture._framebuffer);
  9575. }
  9576. texture.samples = samples;
  9577. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9578. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9579. this.bindUnboundFramebuffer(null);
  9580. return samples;
  9581. };
  9582. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9583. var gl = this._gl;
  9584. var texture = gl.createTexture();
  9585. var generateMipMaps = true;
  9586. var generateDepthBuffer = true;
  9587. var generateStencilBuffer = false;
  9588. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9589. if (options !== undefined) {
  9590. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9591. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9592. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9593. if (options.samplingMode !== undefined) {
  9594. samplingMode = options.samplingMode;
  9595. }
  9596. }
  9597. texture.isCube = true;
  9598. texture.references = 1;
  9599. texture.generateMipMaps = generateMipMaps;
  9600. texture.references = 1;
  9601. texture.samples = 1;
  9602. texture.samplingMode = samplingMode;
  9603. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9604. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9605. for (var face = 0; face < 6; face++) {
  9606. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9607. }
  9608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9612. // Create the framebuffer
  9613. var framebuffer = gl.createFramebuffer();
  9614. this.bindUnboundFramebuffer(framebuffer);
  9615. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9616. // Mipmaps
  9617. if (texture.generateMipMaps) {
  9618. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9619. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9620. }
  9621. // Unbind
  9622. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9623. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9624. this.bindUnboundFramebuffer(null);
  9625. texture._framebuffer = framebuffer;
  9626. texture._width = size;
  9627. texture._height = size;
  9628. texture.isReady = true;
  9629. this.resetTextureCache();
  9630. this._loadedTexturesCache.push(texture);
  9631. return texture;
  9632. };
  9633. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9634. var _this = this;
  9635. if (onLoad === void 0) { onLoad = null; }
  9636. if (onError === void 0) { onError = null; }
  9637. var gl = this._gl;
  9638. var texture = gl.createTexture();
  9639. texture.isCube = true;
  9640. texture.url = rootUrl;
  9641. texture.references = 1;
  9642. texture.onLoadedCallbacks = [];
  9643. var isKTX = false;
  9644. var lastDot = rootUrl.lastIndexOf('.');
  9645. var extension = rootUrl.substring(lastDot).toLowerCase();
  9646. if (this._textureFormatInUse) {
  9647. extension = this._textureFormatInUse;
  9648. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9649. isKTX = true;
  9650. }
  9651. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9652. if (isDDS) {
  9653. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9654. }
  9655. if (isKTX) {
  9656. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9657. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9658. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9659. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9660. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9661. ktx.uploadLevels(_this._gl, !noMipmap);
  9662. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9663. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9666. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9667. _this.resetTextureCache();
  9668. texture._width = ktx.pixelWidth;
  9669. texture._height = ktx.pixelHeight;
  9670. texture.isReady = true;
  9671. }, null, null, true, onError);
  9672. }
  9673. else if (isDDS) {
  9674. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9675. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9676. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9678. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9679. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9680. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9681. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9682. }
  9683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9687. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9688. _this.resetTextureCache();
  9689. texture._width = info.width;
  9690. texture._height = info.height;
  9691. texture.isReady = true;
  9692. }, null, null, true, onError);
  9693. }
  9694. else {
  9695. cascadeLoad(rootUrl, scene, function (imgs) {
  9696. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9697. var height = width;
  9698. _this._prepareWorkingCanvas();
  9699. _this._workingCanvas.width = width;
  9700. _this._workingCanvas.height = height;
  9701. var faces = [
  9702. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9703. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9704. ];
  9705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9706. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9707. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9708. for (var index = 0; index < faces.length; index++) {
  9709. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9710. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9711. }
  9712. if (!noMipmap) {
  9713. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9714. }
  9715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9719. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9720. _this.resetTextureCache();
  9721. texture._width = width;
  9722. texture._height = height;
  9723. texture.isReady = true;
  9724. texture.onLoadedCallbacks.forEach(function (callback) {
  9725. callback();
  9726. });
  9727. if (onLoad) {
  9728. onLoad();
  9729. }
  9730. }, files, onError);
  9731. }
  9732. this._loadedTexturesCache.push(texture);
  9733. return texture;
  9734. };
  9735. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9736. texture._width = width;
  9737. texture._height = height;
  9738. texture._size = width * height;
  9739. texture._baseWidth = width;
  9740. texture._baseHeight = height;
  9741. };
  9742. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9743. if (compression === void 0) { compression = null; }
  9744. if (level === void 0) { level = 0; }
  9745. var gl = this._gl;
  9746. var textureType = this._getWebGLTextureType(type);
  9747. var internalFormat = this._getInternalFormat(format);
  9748. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9749. var needConversion = false;
  9750. if (internalFormat === gl.RGB) {
  9751. internalFormat = gl.RGBA;
  9752. needConversion = true;
  9753. }
  9754. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9755. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9756. if (texture._width % 4 !== 0) {
  9757. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9758. }
  9759. var facesIndex = [
  9760. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9761. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9762. ];
  9763. // Data are known to be in +X +Y +Z -X -Y -Z
  9764. for (var index = 0; index < facesIndex.length; index++) {
  9765. var faceData = data[index];
  9766. if (compression) {
  9767. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9768. }
  9769. else {
  9770. if (needConversion) {
  9771. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9772. }
  9773. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9774. }
  9775. }
  9776. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9777. if (isPot && texture.generateMipMaps && level === 0) {
  9778. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9779. }
  9780. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9781. this.resetTextureCache();
  9782. texture.isReady = true;
  9783. };
  9784. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9785. if (compression === void 0) { compression = null; }
  9786. var gl = this._gl;
  9787. var texture = gl.createTexture();
  9788. texture.isCube = true;
  9789. texture.references = 1;
  9790. var textureType = this._getWebGLTextureType(type);
  9791. var internalFormat = this._getInternalFormat(format);
  9792. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9793. var needConversion = false;
  9794. if (internalFormat === gl.RGB) {
  9795. internalFormat = gl.RGBA;
  9796. needConversion = true;
  9797. }
  9798. var width = size;
  9799. var height = width;
  9800. texture._width = width;
  9801. texture._height = height;
  9802. // Double check on POT to generate Mips.
  9803. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9804. if (!isPot) {
  9805. generateMipMaps = false;
  9806. }
  9807. texture.generateMipMaps = generateMipMaps;
  9808. // Upload data if needed. The texture won t be ready until then.
  9809. if (data) {
  9810. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9811. }
  9812. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9813. // Filters
  9814. if (data && generateMipMaps) {
  9815. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9816. }
  9817. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9820. }
  9821. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9824. }
  9825. else {
  9826. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9829. }
  9830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9833. this._loadedTexturesCache.push(texture);
  9834. return texture;
  9835. };
  9836. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9837. var _this = this;
  9838. if (onLoad === void 0) { onLoad = null; }
  9839. if (onError === void 0) { onError = null; }
  9840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9841. if (invertY === void 0) { invertY = false; }
  9842. var gl = this._gl;
  9843. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9844. scene._addPendingData(texture);
  9845. texture.url = url;
  9846. var onerror = function () {
  9847. scene._removePendingData(texture);
  9848. if (onError) {
  9849. onError();
  9850. }
  9851. };
  9852. var internalCallback = function (data) {
  9853. var rgbeDataArrays = callback(data);
  9854. var facesIndex = [
  9855. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9856. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9857. ];
  9858. var width = texture._width;
  9859. var height = texture._height;
  9860. if (mipmmapGenerator) {
  9861. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9862. // I ll remove ASAP.
  9863. var textureType = _this._getWebGLTextureType(type);
  9864. var internalFormat = _this._getInternalFormat(format);
  9865. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9866. var needConversion = false;
  9867. if (internalFormat === gl.RGB) {
  9868. internalFormat = gl.RGBA;
  9869. needConversion = true;
  9870. }
  9871. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9872. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9873. var arrayTemp = [];
  9874. // Data are known to be in +X +Y +Z -X -Y -Z
  9875. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9876. arrayTemp.push(rgbeDataArrays[0]); // +X
  9877. arrayTemp.push(rgbeDataArrays[3]); // -X
  9878. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9879. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9880. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9881. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9882. var mipData = mipmmapGenerator(arrayTemp);
  9883. // mipData is order in +X -X +Y -Y +Z -Z
  9884. var mipFaces = [0, 2, 4, 1, 3, 5];
  9885. for (var level = 0; level < mipData.length; level++) {
  9886. var mipSize = width >> level;
  9887. for (var mipIndex in mipFaces) {
  9888. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9889. if (needConversion) {
  9890. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9891. }
  9892. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9893. }
  9894. }
  9895. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9896. }
  9897. else {
  9898. texture.generateMipMaps = !noMipmap;
  9899. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9900. }
  9901. texture.isReady = true;
  9902. _this.resetTextureCache();
  9903. scene._removePendingData(texture);
  9904. if (onLoad) {
  9905. onLoad();
  9906. }
  9907. };
  9908. BABYLON.Tools.LoadFile(url, function (data) {
  9909. internalCallback(data);
  9910. }, onerror, scene.database, true);
  9911. return texture;
  9912. };
  9913. ;
  9914. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9915. // Create new RGBA data container.
  9916. var rgbaData;
  9917. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9918. rgbaData = new Float32Array(width * height * 4);
  9919. }
  9920. else {
  9921. rgbaData = new Uint32Array(width * height * 4);
  9922. }
  9923. // Convert each pixel.
  9924. for (var x = 0; x < width; x++) {
  9925. for (var y = 0; y < height; y++) {
  9926. var index = (y * width + x) * 3;
  9927. var newIndex = (y * width + x) * 4;
  9928. // Map Old Value to new value.
  9929. rgbaData[newIndex + 0] = rgbData[index + 0];
  9930. rgbaData[newIndex + 1] = rgbData[index + 1];
  9931. rgbaData[newIndex + 2] = rgbData[index + 2];
  9932. // Add fully opaque alpha channel.
  9933. rgbaData[newIndex + 3] = 1;
  9934. }
  9935. }
  9936. return rgbaData;
  9937. };
  9938. Engine.prototype._releaseTexture = function (texture) {
  9939. var gl = this._gl;
  9940. if (texture._framebuffer) {
  9941. gl.deleteFramebuffer(texture._framebuffer);
  9942. }
  9943. if (texture._depthStencilBuffer) {
  9944. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9945. }
  9946. if (texture._MSAAFramebuffer) {
  9947. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9948. }
  9949. if (texture._MSAARenderBuffer) {
  9950. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9951. }
  9952. gl.deleteTexture(texture);
  9953. // Unbind channels
  9954. this.unbindAllTextures();
  9955. var index = this._loadedTexturesCache.indexOf(texture);
  9956. if (index !== -1) {
  9957. this._loadedTexturesCache.splice(index, 1);
  9958. }
  9959. };
  9960. Engine.prototype.setProgram = function (program) {
  9961. if (this._currentProgram !== program) {
  9962. this._gl.useProgram(program);
  9963. this._currentProgram = program;
  9964. }
  9965. };
  9966. Engine.prototype.bindSamplers = function (effect) {
  9967. this.setProgram(effect.getProgram());
  9968. var samplers = effect.getSamplers();
  9969. for (var index = 0; index < samplers.length; index++) {
  9970. var uniform = effect.getUniform(samplers[index]);
  9971. this._gl.uniform1i(uniform, index);
  9972. }
  9973. this._currentEffect = null;
  9974. };
  9975. Engine.prototype.activateTexture = function (texture) {
  9976. if (this._activeTexture !== texture) {
  9977. this._gl.activeTexture(texture);
  9978. this._activeTexture = texture;
  9979. }
  9980. };
  9981. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9982. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9983. this._gl.bindTexture(target, texture);
  9984. this._activeTexturesCache[this._activeTexture] = texture;
  9985. }
  9986. };
  9987. Engine.prototype._bindTexture = function (channel, texture) {
  9988. if (channel < 0) {
  9989. return;
  9990. }
  9991. this.activateTexture(this._gl.TEXTURE0 + channel);
  9992. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9993. };
  9994. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9995. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9996. };
  9997. Engine.prototype.unbindAllTextures = function () {
  9998. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9999. this.activateTexture(this._gl["TEXTURE" + channel]);
  10000. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10001. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10002. }
  10003. };
  10004. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10005. if (channel < 0) {
  10006. return;
  10007. }
  10008. this._gl.uniform1i(uniform, channel);
  10009. this._setTexture(channel, texture);
  10010. };
  10011. Engine.prototype._setTexture = function (channel, texture) {
  10012. // Not ready?
  10013. if (!texture) {
  10014. if (this._activeTexturesCache[channel] != null) {
  10015. this.activateTexture(this._gl["TEXTURE" + channel]);
  10016. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10017. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10018. }
  10019. return;
  10020. }
  10021. // Video
  10022. var alreadyActivated = false;
  10023. if (texture.video) {
  10024. this.activateTexture(this._gl["TEXTURE" + channel]);
  10025. alreadyActivated = true;
  10026. texture.update();
  10027. }
  10028. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10029. texture.delayLoad();
  10030. return;
  10031. }
  10032. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10033. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10034. if (this._activeTexturesCache[channel] === internalTexture) {
  10035. return;
  10036. }
  10037. if (!alreadyActivated) {
  10038. this.activateTexture(this._gl["TEXTURE" + channel]);
  10039. }
  10040. if (internalTexture.isCube) {
  10041. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10042. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10043. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10044. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10045. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10046. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10047. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10048. }
  10049. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10050. }
  10051. else {
  10052. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10053. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10054. internalTexture._cachedWrapU = texture.wrapU;
  10055. switch (texture.wrapU) {
  10056. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10057. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10058. break;
  10059. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10060. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10061. break;
  10062. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10063. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10064. break;
  10065. }
  10066. }
  10067. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10068. internalTexture._cachedWrapV = texture.wrapV;
  10069. switch (texture.wrapV) {
  10070. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10071. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10072. break;
  10073. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10074. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10075. break;
  10076. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10077. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10078. break;
  10079. }
  10080. }
  10081. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10082. }
  10083. };
  10084. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10085. if (channel < 0) {
  10086. return;
  10087. }
  10088. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10089. this._textureUnits = new Int32Array(textures.length);
  10090. }
  10091. for (var i = 0; i < textures.length; i++) {
  10092. this._textureUnits[i] = channel + i;
  10093. }
  10094. this._gl.uniform1iv(uniform, this._textureUnits);
  10095. for (var index = 0; index < textures.length; index++) {
  10096. this._setTexture(channel + index, textures[index]);
  10097. }
  10098. };
  10099. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10100. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10101. var value = texture.anisotropicFilteringLevel;
  10102. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10103. value = 1;
  10104. }
  10105. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10106. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10107. texture._cachedAnisotropicFilteringLevel = value;
  10108. }
  10109. };
  10110. Engine.prototype.readPixels = function (x, y, width, height) {
  10111. var data = new Uint8Array(height * width * 4);
  10112. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10113. return data;
  10114. };
  10115. /**
  10116. * Add an externaly attached data from its key.
  10117. * This method call will fail and return false, if such key already exists.
  10118. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10119. * @param key the unique key that identifies the data
  10120. * @param data the data object to associate to the key for this Engine instance
  10121. * @return true if no such key were already present and the data was added successfully, false otherwise
  10122. */
  10123. Engine.prototype.addExternalData = function (key, data) {
  10124. if (!this._externalData) {
  10125. this._externalData = new BABYLON.StringDictionary();
  10126. }
  10127. return this._externalData.add(key, data);
  10128. };
  10129. /**
  10130. * Get an externaly attached data from its key
  10131. * @param key the unique key that identifies the data
  10132. * @return the associated data, if present (can be null), or undefined if not present
  10133. */
  10134. Engine.prototype.getExternalData = function (key) {
  10135. if (!this._externalData) {
  10136. this._externalData = new BABYLON.StringDictionary();
  10137. }
  10138. return this._externalData.get(key);
  10139. };
  10140. /**
  10141. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10142. * @param key the unique key that identifies the data
  10143. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10144. * @return the associated data, can be null if the factory returned null.
  10145. */
  10146. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10147. if (!this._externalData) {
  10148. this._externalData = new BABYLON.StringDictionary();
  10149. }
  10150. return this._externalData.getOrAddWithFactory(key, factory);
  10151. };
  10152. /**
  10153. * Remove an externaly attached data from the Engine instance
  10154. * @param key the unique key that identifies the data
  10155. * @return true if the data was successfully removed, false if it doesn't exist
  10156. */
  10157. Engine.prototype.removeExternalData = function (key) {
  10158. if (!this._externalData) {
  10159. this._externalData = new BABYLON.StringDictionary();
  10160. }
  10161. return this._externalData.remove(key);
  10162. };
  10163. Engine.prototype.releaseInternalTexture = function (texture) {
  10164. if (!texture) {
  10165. return;
  10166. }
  10167. texture.references--;
  10168. // Final reference ?
  10169. if (texture.references === 0) {
  10170. var texturesCache = this.getLoadedTexturesCache();
  10171. var index = texturesCache.indexOf(texture);
  10172. if (index > -1) {
  10173. texturesCache.splice(index, 1);
  10174. }
  10175. this._releaseTexture(texture);
  10176. }
  10177. };
  10178. Engine.prototype.unbindAllAttributes = function () {
  10179. if (this._mustWipeVertexAttributes) {
  10180. this._mustWipeVertexAttributes = false;
  10181. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10182. this._gl.disableVertexAttribArray(i);
  10183. this._vertexAttribArraysEnabled[i] = false;
  10184. this._currentBufferPointers[i] = null;
  10185. }
  10186. return;
  10187. }
  10188. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10189. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10190. continue;
  10191. }
  10192. this._gl.disableVertexAttribArray(i);
  10193. this._vertexAttribArraysEnabled[i] = false;
  10194. this._currentBufferPointers[i] = null;
  10195. }
  10196. };
  10197. Engine.prototype.releaseEffects = function () {
  10198. for (var name in this._compiledEffects) {
  10199. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10200. }
  10201. this._compiledEffects = {};
  10202. };
  10203. // Dispose
  10204. Engine.prototype.dispose = function () {
  10205. this.hideLoadingUI();
  10206. this.stopRenderLoop();
  10207. // Empty texture
  10208. if (this._emptyTexture) {
  10209. this._releaseTexture(this._emptyTexture);
  10210. this._emptyTexture = null;
  10211. }
  10212. if (this._emptyCubeTexture) {
  10213. this._releaseTexture(this._emptyCubeTexture);
  10214. this._emptyCubeTexture = null;
  10215. }
  10216. // Release scenes
  10217. while (this.scenes.length) {
  10218. this.scenes[0].dispose();
  10219. }
  10220. // Release audio engine
  10221. if (Engine.audioEngine) {
  10222. Engine.audioEngine.dispose();
  10223. }
  10224. // Release effects
  10225. this.releaseEffects();
  10226. // Unbind
  10227. this.unbindAllAttributes();
  10228. this._gl = null;
  10229. //WebVR
  10230. this.disableVR();
  10231. // Events
  10232. window.removeEventListener("blur", this._onBlur);
  10233. window.removeEventListener("focus", this._onFocus);
  10234. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10235. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10236. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10237. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10238. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10239. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10240. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10241. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10242. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10243. // Remove from Instances
  10244. var index = Engine.Instances.indexOf(this);
  10245. if (index >= 0) {
  10246. Engine.Instances.splice(index, 1);
  10247. }
  10248. };
  10249. // Loading screen
  10250. Engine.prototype.displayLoadingUI = function () {
  10251. var loadingScreen = this.loadingScreen;
  10252. if (loadingScreen) {
  10253. loadingScreen.displayLoadingUI();
  10254. }
  10255. };
  10256. Engine.prototype.hideLoadingUI = function () {
  10257. var loadingScreen = this.loadingScreen;
  10258. if (loadingScreen) {
  10259. loadingScreen.hideLoadingUI();
  10260. }
  10261. };
  10262. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10263. get: function () {
  10264. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10265. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10266. return this._loadingScreen;
  10267. },
  10268. set: function (loadingScreen) {
  10269. this._loadingScreen = loadingScreen;
  10270. },
  10271. enumerable: true,
  10272. configurable: true
  10273. });
  10274. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10275. set: function (text) {
  10276. this.loadingScreen.loadingUIText = text;
  10277. },
  10278. enumerable: true,
  10279. configurable: true
  10280. });
  10281. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10282. set: function (color) {
  10283. this.loadingScreen.loadingUIBackgroundColor = color;
  10284. },
  10285. enumerable: true,
  10286. configurable: true
  10287. });
  10288. Engine.prototype.attachContextLostEvent = function (callback) {
  10289. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10290. };
  10291. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10292. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10293. };
  10294. Engine.prototype.getVertexShaderSource = function (program) {
  10295. var shaders = this._gl.getAttachedShaders(program);
  10296. return this._gl.getShaderSource(shaders[0]);
  10297. };
  10298. Engine.prototype.getFragmentShaderSource = function (program) {
  10299. var shaders = this._gl.getAttachedShaders(program);
  10300. return this._gl.getShaderSource(shaders[1]);
  10301. };
  10302. // FPS
  10303. Engine.prototype.getFps = function () {
  10304. return this.fps;
  10305. };
  10306. Engine.prototype.getDeltaTime = function () {
  10307. return this.deltaTime;
  10308. };
  10309. Engine.prototype._measureFps = function () {
  10310. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10311. var length = this.previousFramesDuration.length;
  10312. if (length >= 2) {
  10313. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10314. }
  10315. if (length >= this.fpsRange) {
  10316. if (length > this.fpsRange) {
  10317. this.previousFramesDuration.splice(0, 1);
  10318. length = this.previousFramesDuration.length;
  10319. }
  10320. var sum = 0;
  10321. for (var id = 0; id < length - 1; id++) {
  10322. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10323. }
  10324. this.fps = 1000.0 / (sum / (length - 1));
  10325. }
  10326. };
  10327. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10328. if (this._webGLVersion > 1) {
  10329. return this._caps.colorBufferFloat;
  10330. }
  10331. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10332. };
  10333. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10334. if (this._webGLVersion > 1) {
  10335. return this._caps.colorBufferFloat;
  10336. }
  10337. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10338. };
  10339. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10340. Engine.prototype._canRenderToFramebuffer = function (type) {
  10341. var gl = this._gl;
  10342. //clear existing errors
  10343. while (gl.getError() !== gl.NO_ERROR) { }
  10344. var successful = true;
  10345. var texture = gl.createTexture();
  10346. gl.bindTexture(gl.TEXTURE_2D, texture);
  10347. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10350. var fb = gl.createFramebuffer();
  10351. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10352. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10353. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10354. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10355. successful = successful && (gl.getError() === gl.NO_ERROR);
  10356. //try render by clearing frame buffer's color buffer
  10357. if (successful) {
  10358. gl.clear(gl.COLOR_BUFFER_BIT);
  10359. successful = successful && (gl.getError() === gl.NO_ERROR);
  10360. }
  10361. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10362. if (successful) {
  10363. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10364. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10365. var readFormat = gl.RGBA;
  10366. var readType = gl.UNSIGNED_BYTE;
  10367. var buffer = new Uint8Array(4);
  10368. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10369. successful = successful && (gl.getError() === gl.NO_ERROR);
  10370. }
  10371. //clean up
  10372. gl.deleteTexture(texture);
  10373. gl.deleteFramebuffer(fb);
  10374. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10375. //clear accumulated errors
  10376. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10377. return successful;
  10378. };
  10379. Engine.prototype._getWebGLTextureType = function (type) {
  10380. if (type === Engine.TEXTURETYPE_FLOAT) {
  10381. return this._gl.FLOAT;
  10382. }
  10383. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10384. // Add Half Float Constant.
  10385. return Engine.HALF_FLOAT_OES;
  10386. }
  10387. return this._gl.UNSIGNED_BYTE;
  10388. };
  10389. ;
  10390. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10391. if (this._webGLVersion === 1) {
  10392. return this._gl.RGBA;
  10393. }
  10394. if (type === Engine.TEXTURETYPE_FLOAT) {
  10395. return Engine.RGBA32F;
  10396. }
  10397. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10398. return Engine.RGBA16F;
  10399. }
  10400. return this._gl.RGBA;
  10401. };
  10402. ;
  10403. // Statics
  10404. Engine.isSupported = function () {
  10405. try {
  10406. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10407. if (navigator.isCocoonJS) {
  10408. return true;
  10409. }
  10410. var tempcanvas = document.createElement("canvas");
  10411. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10412. return gl != null && !!window.WebGLRenderingContext;
  10413. }
  10414. catch (e) {
  10415. return false;
  10416. }
  10417. };
  10418. return Engine;
  10419. }());
  10420. Engine.Instances = new Array();
  10421. // Const statics
  10422. Engine._ALPHA_DISABLE = 0;
  10423. Engine._ALPHA_ADD = 1;
  10424. Engine._ALPHA_COMBINE = 2;
  10425. Engine._ALPHA_SUBTRACT = 3;
  10426. Engine._ALPHA_MULTIPLY = 4;
  10427. Engine._ALPHA_MAXIMIZED = 5;
  10428. Engine._ALPHA_ONEONE = 6;
  10429. Engine._ALPHA_PREMULTIPLIED = 7;
  10430. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10431. Engine._ALPHA_INTERPOLATE = 9;
  10432. Engine._ALPHA_SCREENMODE = 10;
  10433. Engine._DELAYLOADSTATE_NONE = 0;
  10434. Engine._DELAYLOADSTATE_LOADED = 1;
  10435. Engine._DELAYLOADSTATE_LOADING = 2;
  10436. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10437. Engine._TEXTUREFORMAT_ALPHA = 0;
  10438. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10439. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10440. Engine._TEXTUREFORMAT_RGB = 4;
  10441. Engine._TEXTUREFORMAT_RGBA = 5;
  10442. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10443. Engine._TEXTURETYPE_FLOAT = 1;
  10444. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10445. // Depht or Stencil test Constants.
  10446. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10447. 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.
  10448. 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.
  10449. 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.
  10450. 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.
  10451. 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.
  10452. 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.
  10453. 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.
  10454. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10455. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10456. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10457. // Stencil Actions Constants.
  10458. Engine._KEEP = 0x1E00;
  10459. Engine._REPLACE = 0x1E01;
  10460. Engine._INCR = 0x1E02;
  10461. Engine._DECR = 0x1E03;
  10462. Engine._INVERT = 0x150A;
  10463. Engine._INCR_WRAP = 0x8507;
  10464. Engine._DECR_WRAP = 0x8508;
  10465. // Texture rescaling mode
  10466. Engine._SCALEMODE_FLOOR = 1;
  10467. Engine._SCALEMODE_NEAREST = 2;
  10468. Engine._SCALEMODE_CEILING = 3;
  10469. // Updatable statics so stick with vars here
  10470. Engine.CollisionsEpsilon = 0.001;
  10471. Engine.CodeRepository = "src/";
  10472. Engine.ShadersRepository = "src/Shaders/";
  10473. BABYLON.Engine = Engine;
  10474. })(BABYLON || (BABYLON = {}));
  10475. //# sourceMappingURL=babylon.engine.js.map
  10476. /// <reference path="Tools\babylon.decorators.ts" />
  10477. var BABYLON;
  10478. (function (BABYLON) {
  10479. /**
  10480. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10481. */
  10482. var Node = (function () {
  10483. /**
  10484. * @constructor
  10485. * @param {string} name - the name and id to be given to this node
  10486. * @param {BABYLON.Scene} the scene this node will be added to
  10487. */
  10488. function Node(name, scene) {
  10489. this.state = "";
  10490. this.metadata = null;
  10491. this.doNotSerialize = false;
  10492. this.animations = new Array();
  10493. this._ranges = {};
  10494. this._childrenFlag = -1;
  10495. this._isEnabled = true;
  10496. this._isReady = true;
  10497. this._currentRenderId = -1;
  10498. this._parentRenderId = -1;
  10499. /**
  10500. * An event triggered when the mesh is disposed.
  10501. * @type {BABYLON.Observable}
  10502. */
  10503. this.onDisposeObservable = new BABYLON.Observable();
  10504. this.name = name;
  10505. this.id = name;
  10506. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10507. this._initCache();
  10508. }
  10509. Object.defineProperty(Node.prototype, "parent", {
  10510. get: function () {
  10511. return this._parentNode;
  10512. },
  10513. set: function (parent) {
  10514. if (this._parentNode === parent) {
  10515. return;
  10516. }
  10517. if (this._parentNode) {
  10518. var index = this._parentNode._children.indexOf(this);
  10519. if (index !== -1) {
  10520. this._parentNode._children.splice(index, 1);
  10521. }
  10522. }
  10523. this._parentNode = parent;
  10524. if (this._parentNode) {
  10525. if (!this._parentNode._children) {
  10526. this._parentNode._children = new Array();
  10527. }
  10528. this._parentNode._children.push(this);
  10529. }
  10530. },
  10531. enumerable: true,
  10532. configurable: true
  10533. });
  10534. Node.prototype.getClassName = function () {
  10535. return "Node";
  10536. };
  10537. Object.defineProperty(Node.prototype, "onDispose", {
  10538. set: function (callback) {
  10539. if (this._onDisposeObserver) {
  10540. this.onDisposeObservable.remove(this._onDisposeObserver);
  10541. }
  10542. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10543. },
  10544. enumerable: true,
  10545. configurable: true
  10546. });
  10547. Node.prototype.getScene = function () {
  10548. return this._scene;
  10549. };
  10550. Node.prototype.getEngine = function () {
  10551. return this._scene.getEngine();
  10552. };
  10553. // override it in derived class
  10554. Node.prototype.getWorldMatrix = function () {
  10555. return BABYLON.Matrix.Identity();
  10556. };
  10557. // override it in derived class if you add new variables to the cache
  10558. // and call the parent class method
  10559. Node.prototype._initCache = function () {
  10560. this._cache = {};
  10561. this._cache.parent = undefined;
  10562. };
  10563. Node.prototype.updateCache = function (force) {
  10564. if (!force && this.isSynchronized())
  10565. return;
  10566. this._cache.parent = this.parent;
  10567. this._updateCache();
  10568. };
  10569. // override it in derived class if you add new variables to the cache
  10570. // and call the parent class method if !ignoreParentClass
  10571. Node.prototype._updateCache = function (ignoreParentClass) {
  10572. };
  10573. // override it in derived class if you add new variables to the cache
  10574. Node.prototype._isSynchronized = function () {
  10575. return true;
  10576. };
  10577. Node.prototype._markSyncedWithParent = function () {
  10578. this._parentRenderId = this.parent._currentRenderId;
  10579. };
  10580. Node.prototype.isSynchronizedWithParent = function () {
  10581. if (!this.parent) {
  10582. return true;
  10583. }
  10584. if (this._parentRenderId !== this.parent._currentRenderId) {
  10585. return false;
  10586. }
  10587. return this.parent.isSynchronized();
  10588. };
  10589. Node.prototype.isSynchronized = function (updateCache) {
  10590. var check = this.hasNewParent();
  10591. check = check || !this.isSynchronizedWithParent();
  10592. check = check || !this._isSynchronized();
  10593. if (updateCache)
  10594. this.updateCache(true);
  10595. return !check;
  10596. };
  10597. Node.prototype.hasNewParent = function (update) {
  10598. if (this._cache.parent === this.parent)
  10599. return false;
  10600. if (update)
  10601. this._cache.parent = this.parent;
  10602. return true;
  10603. };
  10604. /**
  10605. * Is this node ready to be used/rendered
  10606. * @return {boolean} is it ready
  10607. */
  10608. Node.prototype.isReady = function () {
  10609. return this._isReady;
  10610. };
  10611. /**
  10612. * Is this node enabled.
  10613. * If the node has a parent and is enabled, the parent will be inspected as well.
  10614. * @return {boolean} whether this node (and its parent) is enabled.
  10615. * @see setEnabled
  10616. */
  10617. Node.prototype.isEnabled = function () {
  10618. if (!this._isEnabled) {
  10619. return false;
  10620. }
  10621. if (this.parent) {
  10622. return this.parent.isEnabled();
  10623. }
  10624. return true;
  10625. };
  10626. /**
  10627. * Set the enabled state of this node.
  10628. * @param {boolean} value - the new enabled state
  10629. * @see isEnabled
  10630. */
  10631. Node.prototype.setEnabled = function (value) {
  10632. this._isEnabled = value;
  10633. };
  10634. /**
  10635. * Is this node a descendant of the given node.
  10636. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10637. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10638. * @see parent
  10639. */
  10640. Node.prototype.isDescendantOf = function (ancestor) {
  10641. if (this.parent) {
  10642. if (this.parent === ancestor) {
  10643. return true;
  10644. }
  10645. return this.parent.isDescendantOf(ancestor);
  10646. }
  10647. return false;
  10648. };
  10649. /**
  10650. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10651. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10652. * @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.
  10653. * @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.
  10654. */
  10655. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10656. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10657. if (!this._children) {
  10658. return;
  10659. }
  10660. for (var index = 0; index < this._children.length; index++) {
  10661. var item = this._children[index];
  10662. if (!predicate || predicate(item)) {
  10663. results.push(item);
  10664. }
  10665. if (!directDescendantsOnly) {
  10666. item._getDescendants(results, false, predicate);
  10667. }
  10668. }
  10669. };
  10670. /**
  10671. * Will return all nodes that have this node as ascendant.
  10672. * @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.
  10673. * @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.
  10674. * @return {BABYLON.Node[]} all children nodes of all types.
  10675. */
  10676. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10677. var results = [];
  10678. this._getDescendants(results, directDescendantsOnly, predicate);
  10679. return results;
  10680. };
  10681. /**
  10682. * Get all child-meshes of this node.
  10683. */
  10684. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10685. var results = [];
  10686. this._getDescendants(results, directDecendantsOnly, function (node) {
  10687. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10688. });
  10689. return results;
  10690. };
  10691. /**
  10692. * Get all direct children of this node.
  10693. */
  10694. Node.prototype.getChildren = function (predicate) {
  10695. return this.getDescendants(true, predicate);
  10696. };
  10697. Node.prototype._setReady = function (state) {
  10698. if (state === this._isReady) {
  10699. return;
  10700. }
  10701. if (!state) {
  10702. this._isReady = false;
  10703. return;
  10704. }
  10705. this._isReady = true;
  10706. if (this.onReady) {
  10707. this.onReady(this);
  10708. }
  10709. };
  10710. Node.prototype.getAnimationByName = function (name) {
  10711. for (var i = 0; i < this.animations.length; i++) {
  10712. var animation = this.animations[i];
  10713. if (animation.name === name) {
  10714. return animation;
  10715. }
  10716. }
  10717. return null;
  10718. };
  10719. Node.prototype.createAnimationRange = function (name, from, to) {
  10720. // check name not already in use
  10721. if (!this._ranges[name]) {
  10722. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10723. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10724. if (this.animations[i]) {
  10725. this.animations[i].createRange(name, from, to);
  10726. }
  10727. }
  10728. }
  10729. };
  10730. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10731. if (deleteFrames === void 0) { deleteFrames = true; }
  10732. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10733. if (this.animations[i]) {
  10734. this.animations[i].deleteRange(name, deleteFrames);
  10735. }
  10736. }
  10737. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10738. };
  10739. Node.prototype.getAnimationRange = function (name) {
  10740. return this._ranges[name];
  10741. };
  10742. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10743. var range = this.getAnimationRange(name);
  10744. if (!range) {
  10745. return null;
  10746. }
  10747. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10748. };
  10749. Node.prototype.serializeAnimationRanges = function () {
  10750. var serializationRanges = [];
  10751. for (var name in this._ranges) {
  10752. var range = {};
  10753. range.name = name;
  10754. range.from = this._ranges[name].from;
  10755. range.to = this._ranges[name].to;
  10756. serializationRanges.push(range);
  10757. }
  10758. return serializationRanges;
  10759. };
  10760. Node.prototype.dispose = function () {
  10761. this.parent = null;
  10762. // Callback
  10763. this.onDisposeObservable.notifyObservers(this);
  10764. this.onDisposeObservable.clear();
  10765. };
  10766. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10767. if (parsedNode.ranges) {
  10768. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10769. var data = parsedNode.ranges[index];
  10770. node.createAnimationRange(data.name, data.from, data.to);
  10771. }
  10772. }
  10773. };
  10774. return Node;
  10775. }());
  10776. __decorate([
  10777. BABYLON.serialize()
  10778. ], Node.prototype, "name", void 0);
  10779. __decorate([
  10780. BABYLON.serialize()
  10781. ], Node.prototype, "id", void 0);
  10782. __decorate([
  10783. BABYLON.serialize()
  10784. ], Node.prototype, "uniqueId", void 0);
  10785. __decorate([
  10786. BABYLON.serialize()
  10787. ], Node.prototype, "state", void 0);
  10788. __decorate([
  10789. BABYLON.serialize()
  10790. ], Node.prototype, "metadata", void 0);
  10791. BABYLON.Node = Node;
  10792. })(BABYLON || (BABYLON = {}));
  10793. //# sourceMappingURL=babylon.node.js.map
  10794. var BABYLON;
  10795. (function (BABYLON) {
  10796. var BoundingSphere = (function () {
  10797. function BoundingSphere(minimum, maximum) {
  10798. this.minimum = minimum;
  10799. this.maximum = maximum;
  10800. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10801. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10802. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10803. this.radius = distance * 0.5;
  10804. this.centerWorld = BABYLON.Vector3.Zero();
  10805. this._update(BABYLON.Matrix.Identity());
  10806. }
  10807. // Methods
  10808. BoundingSphere.prototype._update = function (world) {
  10809. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10810. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10811. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10812. };
  10813. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10814. for (var i = 0; i < 6; i++) {
  10815. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10816. return false;
  10817. }
  10818. return true;
  10819. };
  10820. BoundingSphere.prototype.intersectsPoint = function (point) {
  10821. var x = this.centerWorld.x - point.x;
  10822. var y = this.centerWorld.y - point.y;
  10823. var z = this.centerWorld.z - point.z;
  10824. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10825. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10826. return false;
  10827. return true;
  10828. };
  10829. // Statics
  10830. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10831. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10832. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10833. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10834. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10835. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10836. return false;
  10837. return true;
  10838. };
  10839. return BoundingSphere;
  10840. }());
  10841. BABYLON.BoundingSphere = BoundingSphere;
  10842. })(BABYLON || (BABYLON = {}));
  10843. //# sourceMappingURL=babylon.boundingSphere.js.map
  10844. var BABYLON;
  10845. (function (BABYLON) {
  10846. var BoundingBox = (function () {
  10847. function BoundingBox(minimum, maximum) {
  10848. this.minimum = minimum;
  10849. this.maximum = maximum;
  10850. this.vectors = new Array();
  10851. this.vectorsWorld = new Array();
  10852. // Bounding vectors
  10853. this.vectors.push(this.minimum.clone());
  10854. this.vectors.push(this.maximum.clone());
  10855. this.vectors.push(this.minimum.clone());
  10856. this.vectors[2].x = this.maximum.x;
  10857. this.vectors.push(this.minimum.clone());
  10858. this.vectors[3].y = this.maximum.y;
  10859. this.vectors.push(this.minimum.clone());
  10860. this.vectors[4].z = this.maximum.z;
  10861. this.vectors.push(this.maximum.clone());
  10862. this.vectors[5].z = this.minimum.z;
  10863. this.vectors.push(this.maximum.clone());
  10864. this.vectors[6].x = this.minimum.x;
  10865. this.vectors.push(this.maximum.clone());
  10866. this.vectors[7].y = this.minimum.y;
  10867. // OBB
  10868. this.center = this.maximum.add(this.minimum).scale(0.5);
  10869. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10870. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10871. // World
  10872. for (var index = 0; index < this.vectors.length; index++) {
  10873. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10874. }
  10875. this.minimumWorld = BABYLON.Vector3.Zero();
  10876. this.maximumWorld = BABYLON.Vector3.Zero();
  10877. this.centerWorld = BABYLON.Vector3.Zero();
  10878. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10879. this._update(BABYLON.Matrix.Identity());
  10880. }
  10881. // Methods
  10882. BoundingBox.prototype.getWorldMatrix = function () {
  10883. return this._worldMatrix;
  10884. };
  10885. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10886. this._worldMatrix.copyFrom(matrix);
  10887. return this;
  10888. };
  10889. BoundingBox.prototype._update = function (world) {
  10890. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10891. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10892. for (var index = 0; index < this.vectors.length; index++) {
  10893. var v = this.vectorsWorld[index];
  10894. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10895. if (v.x < this.minimumWorld.x)
  10896. this.minimumWorld.x = v.x;
  10897. if (v.y < this.minimumWorld.y)
  10898. this.minimumWorld.y = v.y;
  10899. if (v.z < this.minimumWorld.z)
  10900. this.minimumWorld.z = v.z;
  10901. if (v.x > this.maximumWorld.x)
  10902. this.maximumWorld.x = v.x;
  10903. if (v.y > this.maximumWorld.y)
  10904. this.maximumWorld.y = v.y;
  10905. if (v.z > this.maximumWorld.z)
  10906. this.maximumWorld.z = v.z;
  10907. }
  10908. // Extend
  10909. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10910. this.extendSizeWorld.scaleInPlace(0.5);
  10911. // OBB
  10912. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10913. this.centerWorld.scaleInPlace(0.5);
  10914. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10915. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10916. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10917. this._worldMatrix = world;
  10918. };
  10919. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10920. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10921. };
  10922. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10923. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10924. };
  10925. BoundingBox.prototype.intersectsPoint = function (point) {
  10926. var delta = -BABYLON.Epsilon;
  10927. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10928. return false;
  10929. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10930. return false;
  10931. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10932. return false;
  10933. return true;
  10934. };
  10935. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10936. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10937. };
  10938. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10939. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10940. return false;
  10941. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10942. return false;
  10943. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10944. return false;
  10945. return true;
  10946. };
  10947. // Statics
  10948. BoundingBox.Intersects = function (box0, box1) {
  10949. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10950. return false;
  10951. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10952. return false;
  10953. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10954. return false;
  10955. return true;
  10956. };
  10957. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10958. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10959. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10960. return (num <= (sphereRadius * sphereRadius));
  10961. };
  10962. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10963. for (var p = 0; p < 6; p++) {
  10964. for (var i = 0; i < 8; i++) {
  10965. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10966. return false;
  10967. }
  10968. }
  10969. }
  10970. return true;
  10971. };
  10972. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10973. for (var p = 0; p < 6; p++) {
  10974. var inCount = 8;
  10975. for (var i = 0; i < 8; i++) {
  10976. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10977. --inCount;
  10978. }
  10979. else {
  10980. break;
  10981. }
  10982. }
  10983. if (inCount === 0)
  10984. return false;
  10985. }
  10986. return true;
  10987. };
  10988. return BoundingBox;
  10989. }());
  10990. BABYLON.BoundingBox = BoundingBox;
  10991. })(BABYLON || (BABYLON = {}));
  10992. //# sourceMappingURL=babylon.boundingBox.js.map
  10993. var BABYLON;
  10994. (function (BABYLON) {
  10995. var computeBoxExtents = function (axis, box) {
  10996. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10997. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10998. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10999. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11000. var r = r0 + r1 + r2;
  11001. return {
  11002. min: p - r,
  11003. max: p + r
  11004. };
  11005. };
  11006. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11007. var axisOverlap = function (axis, box0, box1) {
  11008. var result0 = computeBoxExtents(axis, box0);
  11009. var result1 = computeBoxExtents(axis, box1);
  11010. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11011. };
  11012. var BoundingInfo = (function () {
  11013. function BoundingInfo(minimum, maximum) {
  11014. this.minimum = minimum;
  11015. this.maximum = maximum;
  11016. this._isLocked = false;
  11017. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11018. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11019. }
  11020. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11021. get: function () {
  11022. return this._isLocked;
  11023. },
  11024. set: function (value) {
  11025. this._isLocked = value;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. // Methods
  11031. BoundingInfo.prototype.update = function (world) {
  11032. if (this._isLocked) {
  11033. return;
  11034. }
  11035. this.boundingBox._update(world);
  11036. this.boundingSphere._update(world);
  11037. };
  11038. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11039. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11040. return false;
  11041. return this.boundingBox.isInFrustum(frustumPlanes);
  11042. };
  11043. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11044. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11045. };
  11046. BoundingInfo.prototype._checkCollision = function (collider) {
  11047. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11048. };
  11049. BoundingInfo.prototype.intersectsPoint = function (point) {
  11050. if (!this.boundingSphere.centerWorld) {
  11051. return false;
  11052. }
  11053. if (!this.boundingSphere.intersectsPoint(point)) {
  11054. return false;
  11055. }
  11056. if (!this.boundingBox.intersectsPoint(point)) {
  11057. return false;
  11058. }
  11059. return true;
  11060. };
  11061. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11062. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11063. return false;
  11064. }
  11065. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11066. return false;
  11067. }
  11068. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11069. return false;
  11070. }
  11071. if (!precise) {
  11072. return true;
  11073. }
  11074. var box0 = this.boundingBox;
  11075. var box1 = boundingInfo.boundingBox;
  11076. if (!axisOverlap(box0.directions[0], box0, box1))
  11077. return false;
  11078. if (!axisOverlap(box0.directions[1], box0, box1))
  11079. return false;
  11080. if (!axisOverlap(box0.directions[2], box0, box1))
  11081. return false;
  11082. if (!axisOverlap(box1.directions[0], box0, box1))
  11083. return false;
  11084. if (!axisOverlap(box1.directions[1], box0, box1))
  11085. return false;
  11086. if (!axisOverlap(box1.directions[2], box0, box1))
  11087. return false;
  11088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11089. return false;
  11090. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11091. return false;
  11092. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11093. return false;
  11094. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11095. return false;
  11096. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11097. return false;
  11098. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11099. return false;
  11100. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11101. return false;
  11102. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11103. return false;
  11104. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11105. return false;
  11106. return true;
  11107. };
  11108. return BoundingInfo;
  11109. }());
  11110. BABYLON.BoundingInfo = BoundingInfo;
  11111. })(BABYLON || (BABYLON = {}));
  11112. //# sourceMappingURL=babylon.boundingInfo.js.map
  11113. var BABYLON;
  11114. (function (BABYLON) {
  11115. var AbstractMesh = (function (_super) {
  11116. __extends(AbstractMesh, _super);
  11117. // Constructor
  11118. function AbstractMesh(name, scene) {
  11119. var _this = _super.call(this, name, scene) || this;
  11120. _this._facetNb = 0; // facet number
  11121. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11122. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11123. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11124. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11125. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11126. _this._subDiv = {
  11127. max: 1,
  11128. X: 1,
  11129. Y: 1,
  11130. Z: 1
  11131. };
  11132. // Events
  11133. /**
  11134. * An event triggered when this mesh collides with another one
  11135. * @type {BABYLON.Observable}
  11136. */
  11137. _this.onCollideObservable = new BABYLON.Observable();
  11138. /**
  11139. * An event triggered when the collision's position changes
  11140. * @type {BABYLON.Observable}
  11141. */
  11142. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11143. /**
  11144. * An event triggered after the world matrix is updated
  11145. * @type {BABYLON.Observable}
  11146. */
  11147. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11148. // Properties
  11149. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11150. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11151. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11152. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11153. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11154. _this.visibility = 1.0;
  11155. _this.alphaIndex = Number.MAX_VALUE;
  11156. _this.infiniteDistance = false;
  11157. _this.isVisible = true;
  11158. _this.isPickable = true;
  11159. _this.showBoundingBox = false;
  11160. _this.showSubMeshesBoundingBox = false;
  11161. _this.isBlocker = false;
  11162. _this.renderingGroupId = 0;
  11163. _this._receiveShadows = false;
  11164. _this.renderOutline = false;
  11165. _this.outlineColor = BABYLON.Color3.Red();
  11166. _this.outlineWidth = 0.02;
  11167. _this.renderOverlay = false;
  11168. _this.overlayColor = BABYLON.Color3.Red();
  11169. _this.overlayAlpha = 0.5;
  11170. _this._hasVertexAlpha = false;
  11171. _this._useVertexColors = true;
  11172. _this._computeBonesUsingShaders = true;
  11173. _this._numBoneInfluencers = 4;
  11174. _this._applyFog = true;
  11175. _this.scalingDeterminant = 1;
  11176. _this.useOctreeForRenderingSelection = true;
  11177. _this.useOctreeForPicking = true;
  11178. _this.useOctreeForCollisions = true;
  11179. _this.layerMask = 0x0FFFFFFF;
  11180. /**
  11181. * True if the mesh must be rendered in any case.
  11182. */
  11183. _this.alwaysSelectAsActiveMesh = false;
  11184. // Collisions
  11185. _this._checkCollisions = false;
  11186. _this._collisionMask = -1;
  11187. _this._collisionGroup = -1;
  11188. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11189. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11190. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11191. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11192. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11193. // Edges
  11194. _this.edgesWidth = 1;
  11195. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11196. // Cache
  11197. _this._localWorld = BABYLON.Matrix.Zero();
  11198. _this._worldMatrix = BABYLON.Matrix.Zero();
  11199. _this._absolutePosition = BABYLON.Vector3.Zero();
  11200. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11201. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11202. _this._isDirty = false;
  11203. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11204. _this._isDisposed = false;
  11205. _this._renderId = 0;
  11206. _this._intersectionsInProgress = new Array();
  11207. _this._isWorldMatrixFrozen = false;
  11208. _this._unIndexed = false;
  11209. _this._lightSources = new Array();
  11210. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11211. if (collidedMesh === void 0) { collidedMesh = null; }
  11212. //TODO move this to the collision coordinator!
  11213. if (_this.getScene().workerCollisions)
  11214. newPosition.multiplyInPlace(_this._collider.radius);
  11215. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11216. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11217. _this.position.addInPlace(_this._diffPositionForCollisions);
  11218. }
  11219. if (collidedMesh) {
  11220. _this.onCollideObservable.notifyObservers(collidedMesh);
  11221. }
  11222. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11223. };
  11224. _this.getScene().addMesh(_this);
  11225. _this._resyncLightSources();
  11226. return _this;
  11227. }
  11228. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11229. get: function () {
  11230. return AbstractMesh._BILLBOARDMODE_NONE;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11236. get: function () {
  11237. return AbstractMesh._BILLBOARDMODE_X;
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11243. get: function () {
  11244. return AbstractMesh._BILLBOARDMODE_Y;
  11245. },
  11246. enumerable: true,
  11247. configurable: true
  11248. });
  11249. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11250. get: function () {
  11251. return AbstractMesh._BILLBOARDMODE_Z;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11257. get: function () {
  11258. return AbstractMesh._BILLBOARDMODE_ALL;
  11259. },
  11260. enumerable: true,
  11261. configurable: true
  11262. });
  11263. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11264. /**
  11265. * Read-only : the number of facets in the mesh
  11266. */
  11267. get: function () {
  11268. return this._facetNb;
  11269. },
  11270. enumerable: true,
  11271. configurable: true
  11272. });
  11273. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11274. /**
  11275. * The number (integer) of subdivisions per axis in the partioning space
  11276. */
  11277. get: function () {
  11278. return this._partitioningSubdivisions;
  11279. },
  11280. set: function (nb) {
  11281. this._partitioningSubdivisions = nb;
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11287. /**
  11288. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11289. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11290. */
  11291. get: function () {
  11292. return this._partitioningBBoxRatio;
  11293. },
  11294. set: function (ratio) {
  11295. this._partitioningBBoxRatio = ratio;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11301. /**
  11302. * Read-only boolean : is the feature facetData enabled ?
  11303. */
  11304. get: function () {
  11305. return this._facetDataEnabled;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11311. set: function (callback) {
  11312. if (this._onCollideObserver) {
  11313. this.onCollideObservable.remove(this._onCollideObserver);
  11314. }
  11315. this._onCollideObserver = this.onCollideObservable.add(callback);
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11321. set: function (callback) {
  11322. if (this._onCollisionPositionChangeObserver) {
  11323. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11324. }
  11325. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. Object.defineProperty(AbstractMesh.prototype, "material", {
  11331. get: function () {
  11332. return this._material;
  11333. },
  11334. set: function (value) {
  11335. if (this._material === value) {
  11336. return;
  11337. }
  11338. this._material = value;
  11339. if (!this.subMeshes) {
  11340. return;
  11341. }
  11342. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11343. var subMesh = _a[_i];
  11344. subMesh.setEffect(null);
  11345. }
  11346. },
  11347. enumerable: true,
  11348. configurable: true
  11349. });
  11350. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11351. get: function () {
  11352. return this._receiveShadows;
  11353. },
  11354. set: function (value) {
  11355. if (this._receiveShadows === value) {
  11356. return;
  11357. }
  11358. this._receiveShadows = value;
  11359. this._markSubMeshesAsLightDirty();
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11365. get: function () {
  11366. return this._hasVertexAlpha;
  11367. },
  11368. set: function (value) {
  11369. if (this._hasVertexAlpha === value) {
  11370. return;
  11371. }
  11372. this._hasVertexAlpha = value;
  11373. this._markSubMeshesAsAttributesDirty();
  11374. },
  11375. enumerable: true,
  11376. configurable: true
  11377. });
  11378. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11379. get: function () {
  11380. return this._useVertexColors;
  11381. },
  11382. set: function (value) {
  11383. if (this._useVertexColors === value) {
  11384. return;
  11385. }
  11386. this._useVertexColors = value;
  11387. this._markSubMeshesAsAttributesDirty();
  11388. },
  11389. enumerable: true,
  11390. configurable: true
  11391. });
  11392. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11393. get: function () {
  11394. return this._computeBonesUsingShaders;
  11395. },
  11396. set: function (value) {
  11397. if (this._computeBonesUsingShaders === value) {
  11398. return;
  11399. }
  11400. this._computeBonesUsingShaders = value;
  11401. this._markSubMeshesAsAttributesDirty();
  11402. },
  11403. enumerable: true,
  11404. configurable: true
  11405. });
  11406. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11407. get: function () {
  11408. return this._numBoneInfluencers;
  11409. },
  11410. set: function (value) {
  11411. if (this._numBoneInfluencers === value) {
  11412. return;
  11413. }
  11414. this._numBoneInfluencers = value;
  11415. this._markSubMeshesAsAttributesDirty();
  11416. },
  11417. enumerable: true,
  11418. configurable: true
  11419. });
  11420. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11421. get: function () {
  11422. return this._applyFog;
  11423. },
  11424. set: function (value) {
  11425. if (this._applyFog === value) {
  11426. return;
  11427. }
  11428. this._applyFog = value;
  11429. this._markSubMeshesAsMiscDirty();
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11435. get: function () {
  11436. return this._collisionMask;
  11437. },
  11438. set: function (mask) {
  11439. this._collisionMask = !isNaN(mask) ? mask : -1;
  11440. },
  11441. enumerable: true,
  11442. configurable: true
  11443. });
  11444. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11445. get: function () {
  11446. return this._collisionGroup;
  11447. },
  11448. set: function (mask) {
  11449. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11455. get: function () {
  11456. return null;
  11457. },
  11458. enumerable: true,
  11459. configurable: true
  11460. });
  11461. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11462. get: function () {
  11463. return this._skeleton;
  11464. },
  11465. set: function (value) {
  11466. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11467. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11468. }
  11469. if (value && value.needInitialSkinMatrix) {
  11470. value._registerMeshWithPoseMatrix(this);
  11471. }
  11472. this._skeleton = value;
  11473. if (!this._skeleton) {
  11474. this._bonesTransformMatrices = null;
  11475. }
  11476. this._markSubMeshesAsAttributesDirty();
  11477. },
  11478. enumerable: true,
  11479. configurable: true
  11480. });
  11481. /**
  11482. * Returns the string "AbstractMesh"
  11483. */
  11484. AbstractMesh.prototype.getClassName = function () {
  11485. return "AbstractMesh";
  11486. };
  11487. /**
  11488. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11489. */
  11490. AbstractMesh.prototype.toString = function (fullDetails) {
  11491. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11492. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11493. if (this._skeleton) {
  11494. ret += ", skeleton: " + this._skeleton.name;
  11495. }
  11496. if (fullDetails) {
  11497. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11498. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11499. }
  11500. return ret;
  11501. };
  11502. AbstractMesh.prototype._resyncLightSources = function () {
  11503. this._lightSources.length = 0;
  11504. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11505. var light = _a[_i];
  11506. if (!light.isEnabled()) {
  11507. continue;
  11508. }
  11509. if (light.canAffectMesh(this)) {
  11510. this._lightSources.push(light);
  11511. }
  11512. }
  11513. this._markSubMeshesAsLightDirty();
  11514. };
  11515. AbstractMesh.prototype._resyncLighSource = function (light) {
  11516. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11517. var index = this._lightSources.indexOf(light);
  11518. if (index === -1) {
  11519. if (!isIn) {
  11520. return;
  11521. }
  11522. this._lightSources.push(light);
  11523. }
  11524. else {
  11525. if (isIn) {
  11526. return;
  11527. }
  11528. this._lightSources.splice(index, 1);
  11529. }
  11530. this._markSubMeshesAsLightDirty();
  11531. };
  11532. AbstractMesh.prototype._removeLightSource = function (light) {
  11533. var index = this._lightSources.indexOf(light);
  11534. if (index === -1) {
  11535. return;
  11536. }
  11537. this._lightSources.splice(index, 1);
  11538. };
  11539. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11540. if (!this.subMeshes) {
  11541. return;
  11542. }
  11543. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11544. var subMesh = _a[_i];
  11545. if (subMesh._materialDefines) {
  11546. func(subMesh._materialDefines);
  11547. }
  11548. }
  11549. };
  11550. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11551. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11552. };
  11553. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11554. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11555. };
  11556. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11557. if (!this.subMeshes) {
  11558. return;
  11559. }
  11560. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11561. var subMesh = _a[_i];
  11562. var material = subMesh.getMaterial();
  11563. if (material) {
  11564. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11565. }
  11566. }
  11567. };
  11568. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11569. /**
  11570. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11571. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11572. * Default : (0.0, 0.0, 0.0)
  11573. */
  11574. get: function () {
  11575. return this._rotation;
  11576. },
  11577. set: function (newRotation) {
  11578. this._rotation = newRotation;
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11584. /**
  11585. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11586. * Default : (1.0, 1.0, 1.0)
  11587. */
  11588. get: function () {
  11589. return this._scaling;
  11590. },
  11591. set: function (newScaling) {
  11592. this._scaling = newScaling;
  11593. if (this.physicsImpostor) {
  11594. this.physicsImpostor.forceUpdate();
  11595. }
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11601. /**
  11602. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11603. * It's null by default.
  11604. * 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)
  11605. */
  11606. get: function () {
  11607. return this._rotationQuaternion;
  11608. },
  11609. set: function (quaternion) {
  11610. this._rotationQuaternion = quaternion;
  11611. //reset the rotation vector.
  11612. if (quaternion && this.rotation.length()) {
  11613. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11614. }
  11615. },
  11616. enumerable: true,
  11617. configurable: true
  11618. });
  11619. // Methods
  11620. /**
  11621. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11622. * Returns the AbstractMesh.
  11623. */
  11624. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11625. this._poseMatrix.copyFrom(matrix);
  11626. return this;
  11627. };
  11628. /**
  11629. * Returns the mesh Pose matrix.
  11630. * Returned object : Matrix
  11631. */
  11632. AbstractMesh.prototype.getPoseMatrix = function () {
  11633. return this._poseMatrix;
  11634. };
  11635. /**
  11636. * Disables the mesh edger rendering mode.
  11637. * Returns the AbstractMesh.
  11638. */
  11639. AbstractMesh.prototype.disableEdgesRendering = function () {
  11640. if (this._edgesRenderer !== undefined) {
  11641. this._edgesRenderer.dispose();
  11642. this._edgesRenderer = undefined;
  11643. }
  11644. return this;
  11645. };
  11646. /**
  11647. * Enables the edge rendering mode on the mesh.
  11648. * This mode makes the mesh edges visible.
  11649. * Returns the AbstractMesh.
  11650. */
  11651. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11652. if (epsilon === void 0) { epsilon = 0.95; }
  11653. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11654. this.disableEdgesRendering();
  11655. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11656. return this;
  11657. };
  11658. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11659. /**
  11660. * Returns true if the mesh is blocked. Used by the class Mesh.
  11661. * Returns the boolean `false` by default.
  11662. */
  11663. get: function () {
  11664. return false;
  11665. },
  11666. enumerable: true,
  11667. configurable: true
  11668. });
  11669. /**
  11670. * Returns the mesh itself by default, used by the class Mesh.
  11671. * Returned type : AbstractMesh
  11672. */
  11673. AbstractMesh.prototype.getLOD = function (camera) {
  11674. return this;
  11675. };
  11676. /**
  11677. * Returns 0 by default, used by the class Mesh.
  11678. * Returns an integer.
  11679. */
  11680. AbstractMesh.prototype.getTotalVertices = function () {
  11681. return 0;
  11682. };
  11683. /**
  11684. * Returns null by default, used by the class Mesh.
  11685. * Returned type : integer array
  11686. */
  11687. AbstractMesh.prototype.getIndices = function () {
  11688. return null;
  11689. };
  11690. /**
  11691. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11692. * Returned type : float array or Float32Array
  11693. */
  11694. AbstractMesh.prototype.getVerticesData = function (kind) {
  11695. return null;
  11696. };
  11697. /**
  11698. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11699. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11700. * The `data` are either a numeric array either a Float32Array.
  11701. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11702. * 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).
  11703. * Note that a new underlying VertexBuffer object is created each call.
  11704. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11705. *
  11706. * Possible `kind` values :
  11707. * - BABYLON.VertexBuffer.PositionKind
  11708. * - BABYLON.VertexBuffer.UVKind
  11709. * - BABYLON.VertexBuffer.UV2Kind
  11710. * - BABYLON.VertexBuffer.UV3Kind
  11711. * - BABYLON.VertexBuffer.UV4Kind
  11712. * - BABYLON.VertexBuffer.UV5Kind
  11713. * - BABYLON.VertexBuffer.UV6Kind
  11714. * - BABYLON.VertexBuffer.ColorKind
  11715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11719. *
  11720. * Returns the Mesh.
  11721. */
  11722. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11723. return null;
  11724. };
  11725. /**
  11726. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11727. * If the mesh has no geometry, it is simply returned as it is.
  11728. * The `data` are either a numeric array either a Float32Array.
  11729. * No new underlying VertexBuffer object is created.
  11730. * 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.
  11731. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11732. *
  11733. * Possible `kind` values :
  11734. * - BABYLON.VertexBuffer.PositionKind
  11735. * - BABYLON.VertexBuffer.UVKind
  11736. * - BABYLON.VertexBuffer.UV2Kind
  11737. * - BABYLON.VertexBuffer.UV3Kind
  11738. * - BABYLON.VertexBuffer.UV4Kind
  11739. * - BABYLON.VertexBuffer.UV5Kind
  11740. * - BABYLON.VertexBuffer.UV6Kind
  11741. * - BABYLON.VertexBuffer.ColorKind
  11742. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11743. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11744. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11745. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11746. *
  11747. * Returns the Mesh.
  11748. */
  11749. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11750. return null;
  11751. };
  11752. /**
  11753. * Sets the mesh indices.
  11754. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11755. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11756. * This method creates a new index buffer each call.
  11757. * Returns the Mesh.
  11758. */
  11759. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11760. return null;
  11761. };
  11762. /** Returns false by default, used by the class Mesh.
  11763. * Returns a boolean
  11764. */
  11765. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11766. return false;
  11767. };
  11768. /**
  11769. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11770. * Returns a BoundingInfo
  11771. */
  11772. AbstractMesh.prototype.getBoundingInfo = function () {
  11773. if (this._masterMesh) {
  11774. return this._masterMesh.getBoundingInfo();
  11775. }
  11776. if (!this._boundingInfo) {
  11777. this._updateBoundingInfo();
  11778. }
  11779. return this._boundingInfo;
  11780. };
  11781. /**
  11782. * Sets a mesh new object BoundingInfo.
  11783. * Returns the AbstractMesh.
  11784. */
  11785. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11786. this._boundingInfo = boundingInfo;
  11787. return this;
  11788. };
  11789. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11790. get: function () {
  11791. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. AbstractMesh.prototype._preActivate = function () {
  11797. };
  11798. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11799. };
  11800. AbstractMesh.prototype._activate = function (renderId) {
  11801. this._renderId = renderId;
  11802. };
  11803. /**
  11804. * Returns the last update of the World matrix
  11805. * Returns a Matrix.
  11806. */
  11807. AbstractMesh.prototype.getWorldMatrix = function () {
  11808. if (this._masterMesh) {
  11809. return this._masterMesh.getWorldMatrix();
  11810. }
  11811. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11812. this.computeWorldMatrix();
  11813. }
  11814. return this._worldMatrix;
  11815. };
  11816. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11817. /**
  11818. * Returns directly the last state of the mesh World matrix.
  11819. * A Matrix is returned.
  11820. */
  11821. get: function () {
  11822. return this._worldMatrix;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11828. /**
  11829. * Returns the current mesh absolute position.
  11830. * Retuns a Vector3.
  11831. */
  11832. get: function () {
  11833. return this._absolutePosition;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. /**
  11839. * Prevents the World matrix to be computed any longer.
  11840. * Returns the AbstractMesh.
  11841. */
  11842. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11843. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11844. this.computeWorldMatrix(true);
  11845. this._isWorldMatrixFrozen = true;
  11846. return this;
  11847. };
  11848. /**
  11849. * Allows back the World matrix computation.
  11850. * Returns the AbstractMesh.
  11851. */
  11852. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11853. this._isWorldMatrixFrozen = false;
  11854. this.computeWorldMatrix(true);
  11855. return this;
  11856. };
  11857. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11858. /**
  11859. * True if the World matrix has been frozen.
  11860. * Returns a boolean.
  11861. */
  11862. get: function () {
  11863. return this._isWorldMatrixFrozen;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. /**
  11869. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11870. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11871. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11872. * The passed axis is also normalized.
  11873. * Returns the AbstractMesh.
  11874. */
  11875. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11876. axis.normalize();
  11877. if (!this.rotationQuaternion) {
  11878. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11879. this.rotation = BABYLON.Vector3.Zero();
  11880. }
  11881. var rotationQuaternion;
  11882. if (!space || space === BABYLON.Space.LOCAL) {
  11883. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11884. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11885. }
  11886. else {
  11887. if (this.parent) {
  11888. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11889. invertParentWorldMatrix.invert();
  11890. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11891. }
  11892. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11893. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11894. }
  11895. return this;
  11896. };
  11897. /**
  11898. * Translates the mesh along the axis vector for the passed distance in the given space.
  11899. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11900. * Returns the AbstractMesh.
  11901. */
  11902. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11903. var displacementVector = axis.scale(distance);
  11904. if (!space || space === BABYLON.Space.LOCAL) {
  11905. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11906. this.setPositionWithLocalVector(tempV3);
  11907. }
  11908. else {
  11909. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11910. }
  11911. return this;
  11912. };
  11913. /**
  11914. * Adds a rotation step to the mesh current rotation.
  11915. * x, y, z are Euler angles expressed in radians.
  11916. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11917. * This means this rotation is made in the mesh local space only.
  11918. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11919. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11920. * ```javascript
  11921. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11922. * ```
  11923. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11924. * 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.
  11925. * Returns the AbstractMesh.
  11926. */
  11927. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11928. var rotationQuaternion;
  11929. if (this.rotationQuaternion) {
  11930. rotationQuaternion = this.rotationQuaternion;
  11931. }
  11932. else {
  11933. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11934. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11935. }
  11936. var accumulation = BABYLON.Tmp.Quaternion[0];
  11937. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11938. rotationQuaternion.multiplyInPlace(accumulation);
  11939. if (!this.rotationQuaternion) {
  11940. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11941. }
  11942. return this;
  11943. };
  11944. /**
  11945. * Retuns the mesh absolute position in the World.
  11946. * Returns a Vector3.
  11947. */
  11948. AbstractMesh.prototype.getAbsolutePosition = function () {
  11949. this.computeWorldMatrix();
  11950. return this._absolutePosition;
  11951. };
  11952. /**
  11953. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11954. * Returns the AbstractMesh.
  11955. */
  11956. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11957. if (!absolutePosition) {
  11958. return;
  11959. }
  11960. var absolutePositionX;
  11961. var absolutePositionY;
  11962. var absolutePositionZ;
  11963. if (absolutePosition.x === undefined) {
  11964. if (arguments.length < 3) {
  11965. return;
  11966. }
  11967. absolutePositionX = arguments[0];
  11968. absolutePositionY = arguments[1];
  11969. absolutePositionZ = arguments[2];
  11970. }
  11971. else {
  11972. absolutePositionX = absolutePosition.x;
  11973. absolutePositionY = absolutePosition.y;
  11974. absolutePositionZ = absolutePosition.z;
  11975. }
  11976. if (this.parent) {
  11977. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11978. invertParentWorldMatrix.invert();
  11979. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11980. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11981. }
  11982. else {
  11983. this.position.x = absolutePositionX;
  11984. this.position.y = absolutePositionY;
  11985. this.position.z = absolutePositionZ;
  11986. }
  11987. return this;
  11988. };
  11989. // ================================== Point of View Movement =================================
  11990. /**
  11991. * Perform relative position change from the point of view of behind the front of the mesh.
  11992. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11993. * Supports definition of mesh facing forward or backward.
  11994. * @param {number} amountRight
  11995. * @param {number} amountUp
  11996. * @param {number} amountForward
  11997. *
  11998. * Returns the AbstractMesh.
  11999. */
  12000. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12001. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12002. return this;
  12003. };
  12004. /**
  12005. * Calculate relative position change from the point of view of behind the front of the mesh.
  12006. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12007. * Supports definition of mesh facing forward or backward.
  12008. * @param {number} amountRight
  12009. * @param {number} amountUp
  12010. * @param {number} amountForward
  12011. *
  12012. * Returns a new Vector3.
  12013. */
  12014. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12015. var rotMatrix = new BABYLON.Matrix();
  12016. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12017. rotQuaternion.toRotationMatrix(rotMatrix);
  12018. var translationDelta = BABYLON.Vector3.Zero();
  12019. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12020. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12021. return translationDelta;
  12022. };
  12023. // ================================== Point of View Rotation =================================
  12024. /**
  12025. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12026. * Supports definition of mesh facing forward or backward.
  12027. * @param {number} flipBack
  12028. * @param {number} twirlClockwise
  12029. * @param {number} tiltRight
  12030. *
  12031. * Returns the AbstractMesh.
  12032. */
  12033. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12034. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12035. return this;
  12036. };
  12037. /**
  12038. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12039. * Supports definition of mesh facing forward or backward.
  12040. * @param {number} flipBack
  12041. * @param {number} twirlClockwise
  12042. * @param {number} tiltRight
  12043. *
  12044. * Returns a new Vector3.
  12045. */
  12046. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12047. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12048. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12049. };
  12050. /**
  12051. * Sets a new pivot matrix to the mesh.
  12052. * Returns the AbstractMesh.
  12053. */
  12054. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12055. this._pivotMatrix = matrix;
  12056. this._cache.pivotMatrixUpdated = true;
  12057. return this;
  12058. };
  12059. /**
  12060. * Returns the mesh pivot matrix.
  12061. * Default : Identity.
  12062. * A Matrix is returned.
  12063. */
  12064. AbstractMesh.prototype.getPivotMatrix = function () {
  12065. return this._pivotMatrix;
  12066. };
  12067. AbstractMesh.prototype._isSynchronized = function () {
  12068. if (this._isDirty) {
  12069. return false;
  12070. }
  12071. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12072. return false;
  12073. if (this._cache.pivotMatrixUpdated) {
  12074. return false;
  12075. }
  12076. if (this.infiniteDistance) {
  12077. return false;
  12078. }
  12079. if (!this._cache.position.equals(this.position))
  12080. return false;
  12081. if (this.rotationQuaternion) {
  12082. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12083. return false;
  12084. }
  12085. if (!this._cache.rotation.equals(this.rotation))
  12086. return false;
  12087. if (!this._cache.scaling.equals(this.scaling))
  12088. return false;
  12089. return true;
  12090. };
  12091. AbstractMesh.prototype._initCache = function () {
  12092. _super.prototype._initCache.call(this);
  12093. this._cache.localMatrixUpdated = false;
  12094. this._cache.position = BABYLON.Vector3.Zero();
  12095. this._cache.scaling = BABYLON.Vector3.Zero();
  12096. this._cache.rotation = BABYLON.Vector3.Zero();
  12097. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12098. this._cache.billboardMode = -1;
  12099. };
  12100. AbstractMesh.prototype.markAsDirty = function (property) {
  12101. if (property === "rotation") {
  12102. this.rotationQuaternion = null;
  12103. }
  12104. this._currentRenderId = Number.MAX_VALUE;
  12105. this._isDirty = true;
  12106. return this;
  12107. };
  12108. /**
  12109. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12110. * Returns the AbstractMesh.
  12111. */
  12112. AbstractMesh.prototype._updateBoundingInfo = function () {
  12113. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12114. this._boundingInfo.update(this.worldMatrixFromCache);
  12115. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12116. return this;
  12117. };
  12118. /**
  12119. * Update a mesh's children BoundingInfo objects only.
  12120. * Returns the AbstractMesh.
  12121. */
  12122. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12123. if (!this.subMeshes) {
  12124. return;
  12125. }
  12126. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12127. var subMesh = this.subMeshes[subIndex];
  12128. if (!subMesh.IsGlobal) {
  12129. subMesh.updateBoundingInfo(matrix);
  12130. }
  12131. }
  12132. return this;
  12133. };
  12134. /**
  12135. * Computes the mesh World matrix and returns it.
  12136. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12137. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12138. * If the parameter `force`is set to `true`, the actual computation is done.
  12139. * Returns the mesh World Matrix.
  12140. */
  12141. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12142. if (this._isWorldMatrixFrozen) {
  12143. return this._worldMatrix;
  12144. }
  12145. if (!force && this.isSynchronized(true)) {
  12146. this._currentRenderId = this.getScene().getRenderId();
  12147. return this._worldMatrix;
  12148. }
  12149. this._cache.position.copyFrom(this.position);
  12150. this._cache.scaling.copyFrom(this.scaling);
  12151. this._cache.pivotMatrixUpdated = false;
  12152. this._cache.billboardMode = this.billboardMode;
  12153. this._currentRenderId = this.getScene().getRenderId();
  12154. this._isDirty = false;
  12155. // Scaling
  12156. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12157. // Rotation
  12158. //rotate, if quaternion is set and rotation was used
  12159. if (this.rotationQuaternion) {
  12160. var len = this.rotation.length();
  12161. if (len) {
  12162. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12163. this.rotation.copyFromFloats(0, 0, 0);
  12164. }
  12165. }
  12166. if (this.rotationQuaternion) {
  12167. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12168. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12169. }
  12170. else {
  12171. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12172. this._cache.rotation.copyFrom(this.rotation);
  12173. }
  12174. // Translation
  12175. if (this.infiniteDistance && !this.parent) {
  12176. var camera = this.getScene().activeCamera;
  12177. if (camera) {
  12178. var cameraWorldMatrix = camera.getWorldMatrix();
  12179. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12180. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12181. }
  12182. }
  12183. else {
  12184. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12185. }
  12186. // Composing transformations
  12187. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12188. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12189. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12190. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12191. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12192. // Need to decompose each rotation here
  12193. var currentPosition = BABYLON.Tmp.Vector3[3];
  12194. if (this.parent && this.parent.getWorldMatrix) {
  12195. if (this._meshToBoneReferal) {
  12196. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12197. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12198. }
  12199. else {
  12200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12201. }
  12202. }
  12203. else {
  12204. currentPosition.copyFrom(this.position);
  12205. }
  12206. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12207. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12208. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12209. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12210. }
  12211. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12212. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12213. }
  12214. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12215. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12216. }
  12217. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12218. }
  12219. else {
  12220. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12221. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12222. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12223. }
  12224. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12225. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12226. }
  12227. // Local world
  12228. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12229. // Parent
  12230. if (this.parent && this.parent.getWorldMatrix) {
  12231. this._markSyncedWithParent();
  12232. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12233. if (this._meshToBoneReferal) {
  12234. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12235. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12236. }
  12237. else {
  12238. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12239. }
  12240. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12241. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12242. this._worldMatrix.copyFrom(this._localWorld);
  12243. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12244. }
  12245. else {
  12246. if (this._meshToBoneReferal) {
  12247. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12248. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12249. }
  12250. else {
  12251. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12252. }
  12253. }
  12254. }
  12255. else {
  12256. this._worldMatrix.copyFrom(this._localWorld);
  12257. }
  12258. // Bounding info
  12259. this._updateBoundingInfo();
  12260. // Absolute position
  12261. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12262. // Callbacks
  12263. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12264. if (!this._poseMatrix) {
  12265. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12266. }
  12267. return this._worldMatrix;
  12268. };
  12269. /**
  12270. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12271. * @param func: callback function to add
  12272. *
  12273. * Returns the AbstractMesh.
  12274. */
  12275. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12276. this.onAfterWorldMatrixUpdateObservable.add(func);
  12277. return this;
  12278. };
  12279. /**
  12280. * Removes a registered callback function.
  12281. * Returns the AbstractMesh.
  12282. */
  12283. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12284. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12285. return this;
  12286. };
  12287. /**
  12288. * Sets the mesh position in its local space.
  12289. * Returns the AbstractMesh.
  12290. */
  12291. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12292. this.computeWorldMatrix();
  12293. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12294. return this;
  12295. };
  12296. /**
  12297. * Returns the mesh position in the local space from the current World matrix values.
  12298. * Returns a new Vector3.
  12299. */
  12300. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12301. this.computeWorldMatrix();
  12302. var invLocalWorldMatrix = this._localWorld.clone();
  12303. invLocalWorldMatrix.invert();
  12304. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12305. };
  12306. /**
  12307. * Translates the mesh along the passed Vector3 in its local space.
  12308. * Returns the AbstractMesh.
  12309. */
  12310. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12311. this.computeWorldMatrix(true);
  12312. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12313. return this;
  12314. };
  12315. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12316. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12317. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12318. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12319. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12320. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12321. /// <returns>Mesh oriented towards targetMesh</returns>
  12322. if (yawCor === void 0) { yawCor = 0; }
  12323. if (pitchCor === void 0) { pitchCor = 0; }
  12324. if (rollCor === void 0) { rollCor = 0; }
  12325. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12326. var dv = AbstractMesh._lookAtVectorCache;
  12327. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12328. targetPoint.subtractToRef(pos, dv);
  12329. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12330. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12331. var pitch = Math.atan2(dv.y, len);
  12332. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12333. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12334. return this;
  12335. };
  12336. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12337. this._meshToBoneReferal = affectedMesh;
  12338. this.parent = bone;
  12339. if (bone.getWorldMatrix().determinant() < 0) {
  12340. this.scalingDeterminant *= -1;
  12341. }
  12342. return this;
  12343. };
  12344. AbstractMesh.prototype.detachFromBone = function () {
  12345. if (this.parent.getWorldMatrix().determinant() < 0) {
  12346. this.scalingDeterminant *= -1;
  12347. }
  12348. this._meshToBoneReferal = null;
  12349. this.parent = null;
  12350. return this;
  12351. };
  12352. /**
  12353. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12354. * A mesh is in the frustum if its bounding box intersects the frustum.
  12355. * Boolean returned.
  12356. */
  12357. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12358. return this._boundingInfo.isInFrustum(frustumPlanes);
  12359. };
  12360. /**
  12361. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12362. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12363. * Boolean returned.
  12364. */
  12365. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12366. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12367. ;
  12368. };
  12369. /**
  12370. * True if the mesh intersects another mesh or a SolidParticle object.
  12371. * 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)
  12372. * Returns a boolean.
  12373. */
  12374. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12375. if (!this._boundingInfo || !mesh._boundingInfo) {
  12376. return false;
  12377. }
  12378. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12379. };
  12380. /**
  12381. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12382. * Returns a boolean.
  12383. */
  12384. AbstractMesh.prototype.intersectsPoint = function (point) {
  12385. if (!this._boundingInfo) {
  12386. return false;
  12387. }
  12388. return this._boundingInfo.intersectsPoint(point);
  12389. };
  12390. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12391. return this.physicsImpostor;
  12392. };
  12393. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12394. if (!camera) {
  12395. camera = this.getScene().activeCamera;
  12396. }
  12397. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12398. };
  12399. /**
  12400. * Returns the distance from the mesh to the active camera.
  12401. * Returns a float.
  12402. */
  12403. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12404. if (!camera) {
  12405. camera = this.getScene().activeCamera;
  12406. }
  12407. return this.absolutePosition.subtract(camera.position).length();
  12408. };
  12409. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12410. if (!this.physicsImpostor) {
  12411. return;
  12412. }
  12413. this.physicsImpostor.applyImpulse(force, contactPoint);
  12414. return this;
  12415. };
  12416. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12417. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12418. return;
  12419. }
  12420. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12421. mainPivot: pivot1,
  12422. connectedPivot: pivot2,
  12423. nativeParams: options
  12424. });
  12425. return this;
  12426. };
  12427. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12428. // Collisions
  12429. /**
  12430. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12431. * Default `false`.
  12432. */
  12433. get: function () {
  12434. return this._checkCollisions;
  12435. },
  12436. set: function (collisionEnabled) {
  12437. this._checkCollisions = collisionEnabled;
  12438. if (this.getScene().workerCollisions) {
  12439. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12440. }
  12441. },
  12442. enumerable: true,
  12443. configurable: true
  12444. });
  12445. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12446. var globalPosition = this.getAbsolutePosition();
  12447. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12448. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12449. if (!this._collider) {
  12450. this._collider = new BABYLON.Collider();
  12451. }
  12452. this._collider.radius = this.ellipsoid;
  12453. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12454. return this;
  12455. };
  12456. // Submeshes octree
  12457. /**
  12458. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12459. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12460. * Returns an Octree of submeshes.
  12461. */
  12462. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12463. if (maxCapacity === void 0) { maxCapacity = 64; }
  12464. if (maxDepth === void 0) { maxDepth = 2; }
  12465. if (!this._submeshesOctree) {
  12466. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12467. }
  12468. this.computeWorldMatrix(true);
  12469. // Update octree
  12470. var bbox = this.getBoundingInfo().boundingBox;
  12471. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12472. return this._submeshesOctree;
  12473. };
  12474. // Collisions
  12475. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12476. this._generatePointsArray();
  12477. // Transformation
  12478. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12479. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12480. subMesh._lastColliderWorldVertices = [];
  12481. subMesh._trianglePlanes = [];
  12482. var start = subMesh.verticesStart;
  12483. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12484. for (var i = start; i < end; i++) {
  12485. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12486. }
  12487. }
  12488. // Collide
  12489. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12490. if (collider.collisionFound) {
  12491. collider.collidedMesh = this;
  12492. }
  12493. return this;
  12494. };
  12495. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12496. var subMeshes;
  12497. var len;
  12498. // Octrees
  12499. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12500. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12501. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12502. len = intersections.length;
  12503. subMeshes = intersections.data;
  12504. }
  12505. else {
  12506. subMeshes = this.subMeshes;
  12507. len = subMeshes.length;
  12508. }
  12509. for (var index = 0; index < len; index++) {
  12510. var subMesh = subMeshes[index];
  12511. // Bounding test
  12512. if (len > 1 && !subMesh._checkCollision(collider))
  12513. continue;
  12514. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12515. }
  12516. return this;
  12517. };
  12518. AbstractMesh.prototype._checkCollision = function (collider) {
  12519. // Bounding box test
  12520. if (!this._boundingInfo._checkCollision(collider))
  12521. return this;
  12522. // Transformation matrix
  12523. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12524. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12525. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12526. return this;
  12527. };
  12528. // Picking
  12529. AbstractMesh.prototype._generatePointsArray = function () {
  12530. return false;
  12531. };
  12532. /**
  12533. * Checks if the passed Ray intersects with the mesh.
  12534. * Returns an object PickingInfo.
  12535. */
  12536. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12537. var pickingInfo = new BABYLON.PickingInfo();
  12538. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12539. return pickingInfo;
  12540. }
  12541. if (!this._generatePointsArray()) {
  12542. return pickingInfo;
  12543. }
  12544. var intersectInfo = null;
  12545. // Octrees
  12546. var subMeshes;
  12547. var len;
  12548. if (this._submeshesOctree && this.useOctreeForPicking) {
  12549. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12550. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12551. len = intersections.length;
  12552. subMeshes = intersections.data;
  12553. }
  12554. else {
  12555. subMeshes = this.subMeshes;
  12556. len = subMeshes.length;
  12557. }
  12558. for (var index = 0; index < len; index++) {
  12559. var subMesh = subMeshes[index];
  12560. // Bounding test
  12561. if (len > 1 && !subMesh.canIntersects(ray))
  12562. continue;
  12563. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12564. if (currentIntersectInfo) {
  12565. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12566. intersectInfo = currentIntersectInfo;
  12567. intersectInfo.subMeshId = index;
  12568. if (fastCheck) {
  12569. break;
  12570. }
  12571. }
  12572. }
  12573. }
  12574. if (intersectInfo) {
  12575. // Get picked point
  12576. var world = this.getWorldMatrix();
  12577. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12578. var direction = ray.direction.clone();
  12579. direction = direction.scale(intersectInfo.distance);
  12580. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12581. var pickedPoint = worldOrigin.add(worldDirection);
  12582. // Return result
  12583. pickingInfo.hit = true;
  12584. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12585. pickingInfo.pickedPoint = pickedPoint;
  12586. pickingInfo.pickedMesh = this;
  12587. pickingInfo.bu = intersectInfo.bu;
  12588. pickingInfo.bv = intersectInfo.bv;
  12589. pickingInfo.faceId = intersectInfo.faceId;
  12590. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12591. return pickingInfo;
  12592. }
  12593. return pickingInfo;
  12594. };
  12595. /**
  12596. * Clones the mesh, used by the class Mesh.
  12597. * Just returns `null` for an AbstractMesh.
  12598. */
  12599. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12600. return null;
  12601. };
  12602. /**
  12603. * Disposes all the mesh submeshes.
  12604. * Returns the AbstractMesh.
  12605. */
  12606. AbstractMesh.prototype.releaseSubMeshes = function () {
  12607. if (this.subMeshes) {
  12608. while (this.subMeshes.length) {
  12609. this.subMeshes[0].dispose();
  12610. }
  12611. }
  12612. else {
  12613. this.subMeshes = new Array();
  12614. }
  12615. return this;
  12616. };
  12617. /**
  12618. * Disposes the AbstractMesh.
  12619. * Some internal references are kept for further use.
  12620. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12621. * Returns nothing.
  12622. */
  12623. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12624. var _this = this;
  12625. var index;
  12626. // Action manager
  12627. if (this.actionManager) {
  12628. this.actionManager.dispose();
  12629. this.actionManager = null;
  12630. }
  12631. // Skeleton
  12632. this.skeleton = null;
  12633. // Animations
  12634. this.getScene().stopAnimation(this);
  12635. // Physics
  12636. if (this.physicsImpostor) {
  12637. this.physicsImpostor.dispose();
  12638. }
  12639. // Intersections in progress
  12640. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12641. var other = this._intersectionsInProgress[index];
  12642. var pos = other._intersectionsInProgress.indexOf(this);
  12643. other._intersectionsInProgress.splice(pos, 1);
  12644. }
  12645. this._intersectionsInProgress = [];
  12646. // Lights
  12647. var lights = this.getScene().lights;
  12648. lights.forEach(function (light) {
  12649. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12650. if (meshIndex !== -1) {
  12651. light.includedOnlyMeshes.splice(meshIndex, 1);
  12652. }
  12653. meshIndex = light.excludedMeshes.indexOf(_this);
  12654. if (meshIndex !== -1) {
  12655. light.excludedMeshes.splice(meshIndex, 1);
  12656. }
  12657. // Shadow generators
  12658. var generator = light.getShadowGenerator();
  12659. if (generator) {
  12660. var shadowMap = generator.getShadowMap();
  12661. meshIndex = shadowMap.renderList.indexOf(_this);
  12662. if (meshIndex !== -1) {
  12663. shadowMap.renderList.splice(meshIndex, 1);
  12664. }
  12665. }
  12666. });
  12667. // Edges
  12668. if (this._edgesRenderer) {
  12669. this._edgesRenderer.dispose();
  12670. this._edgesRenderer = null;
  12671. }
  12672. // SubMeshes
  12673. if (this.getClassName() !== "InstancedMesh") {
  12674. this.releaseSubMeshes();
  12675. }
  12676. // Octree
  12677. var sceneOctree = this.getScene().selectionOctree;
  12678. if (sceneOctree) {
  12679. var index = sceneOctree.dynamicContent.indexOf(this);
  12680. if (index !== -1) {
  12681. sceneOctree.dynamicContent.splice(index, 1);
  12682. }
  12683. }
  12684. // Engine
  12685. this.getScene().getEngine().wipeCaches();
  12686. // Remove from scene
  12687. this.getScene().removeMesh(this);
  12688. if (!doNotRecurse) {
  12689. // Particles
  12690. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12691. if (this.getScene().particleSystems[index].emitter === this) {
  12692. this.getScene().particleSystems[index].dispose();
  12693. index--;
  12694. }
  12695. }
  12696. // Children
  12697. var objects = this.getDescendants(true);
  12698. for (index = 0; index < objects.length; index++) {
  12699. objects[index].dispose();
  12700. }
  12701. }
  12702. else {
  12703. var childMeshes = this.getChildMeshes(true);
  12704. for (index = 0; index < childMeshes.length; index++) {
  12705. var child = childMeshes[index];
  12706. child.parent = null;
  12707. child.computeWorldMatrix(true);
  12708. }
  12709. }
  12710. // facet data
  12711. if (this._facetDataEnabled) {
  12712. this.disableFacetData();
  12713. }
  12714. this.onAfterWorldMatrixUpdateObservable.clear();
  12715. this.onCollideObservable.clear();
  12716. this.onCollisionPositionChangeObservable.clear();
  12717. this._isDisposed = true;
  12718. _super.prototype.dispose.call(this);
  12719. };
  12720. /**
  12721. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12722. * This Vector3 is expressed in the World space.
  12723. */
  12724. AbstractMesh.prototype.getDirection = function (localAxis) {
  12725. var result = BABYLON.Vector3.Zero();
  12726. this.getDirectionToRef(localAxis, result);
  12727. return result;
  12728. };
  12729. /**
  12730. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12731. * localAxis is expressed in the mesh local space.
  12732. * result is computed in the Wordl space from the mesh World matrix.
  12733. * Returns the AbstractMesh.
  12734. */
  12735. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12736. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12737. return this;
  12738. };
  12739. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12741. if (this.getScene().getRenderId() == 0) {
  12742. this.computeWorldMatrix(true);
  12743. }
  12744. var wm = this.getWorldMatrix();
  12745. if (space == BABYLON.Space.WORLD) {
  12746. var tmat = BABYLON.Tmp.Matrix[0];
  12747. wm.invertToRef(tmat);
  12748. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12749. }
  12750. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12751. this._pivotMatrix.m[12] = -point.x;
  12752. this._pivotMatrix.m[13] = -point.y;
  12753. this._pivotMatrix.m[14] = -point.z;
  12754. this._cache.pivotMatrixUpdated = true;
  12755. return this;
  12756. };
  12757. /**
  12758. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12759. */
  12760. AbstractMesh.prototype.getPivotPoint = function () {
  12761. var point = BABYLON.Vector3.Zero();
  12762. this.getPivotPointToRef(point);
  12763. return point;
  12764. };
  12765. /**
  12766. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12767. * Returns the AbstractMesh.
  12768. */
  12769. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12770. result.x = -this._pivotMatrix.m[12];
  12771. result.y = -this._pivotMatrix.m[13];
  12772. result.z = -this._pivotMatrix.m[14];
  12773. return this;
  12774. };
  12775. /**
  12776. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12777. */
  12778. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12779. var point = BABYLON.Vector3.Zero();
  12780. this.getAbsolutePivotPointToRef(point);
  12781. return point;
  12782. };
  12783. /**
  12784. * Defines the passed mesh as the parent of the current mesh.
  12785. * Returns the AbstractMesh.
  12786. */
  12787. AbstractMesh.prototype.setParent = function (mesh) {
  12788. var child = this;
  12789. var parent = mesh;
  12790. if (mesh == null) {
  12791. var rotation = BABYLON.Tmp.Quaternion[0];
  12792. var position = BABYLON.Tmp.Vector3[0];
  12793. var scale = BABYLON.Tmp.Vector3[1];
  12794. child.getWorldMatrix().decompose(scale, rotation, position);
  12795. if (child.rotationQuaternion) {
  12796. child.rotationQuaternion.copyFrom(rotation);
  12797. }
  12798. else {
  12799. rotation.toEulerAnglesToRef(child.rotation);
  12800. }
  12801. child.position.x = position.x;
  12802. child.position.y = position.y;
  12803. child.position.z = position.z;
  12804. }
  12805. else {
  12806. var rotation = BABYLON.Tmp.Quaternion[0];
  12807. var position = BABYLON.Tmp.Vector3[0];
  12808. var scale = BABYLON.Tmp.Vector3[1];
  12809. var m1 = BABYLON.Tmp.Matrix[0];
  12810. var m2 = BABYLON.Tmp.Matrix[1];
  12811. parent.getWorldMatrix().decompose(scale, rotation, position);
  12812. rotation.toRotationMatrix(m1);
  12813. m2.setTranslation(position);
  12814. m2.multiplyToRef(m1, m1);
  12815. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12816. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12817. m.decompose(scale, rotation, position);
  12818. if (child.rotationQuaternion) {
  12819. child.rotationQuaternion.copyFrom(rotation);
  12820. }
  12821. else {
  12822. rotation.toEulerAnglesToRef(child.rotation);
  12823. }
  12824. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12825. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12826. m.decompose(scale, rotation, position);
  12827. child.position.x = position.x;
  12828. child.position.y = position.y;
  12829. child.position.z = position.z;
  12830. }
  12831. child.parent = parent;
  12832. return this;
  12833. };
  12834. /**
  12835. * Adds the passed mesh as a child to the current mesh.
  12836. * Returns the AbstractMesh.
  12837. */
  12838. AbstractMesh.prototype.addChild = function (mesh) {
  12839. mesh.setParent(this);
  12840. return this;
  12841. };
  12842. /**
  12843. * Removes the passed mesh from the current mesh children list.
  12844. * Returns the AbstractMesh.
  12845. */
  12846. AbstractMesh.prototype.removeChild = function (mesh) {
  12847. mesh.setParent(null);
  12848. return this;
  12849. };
  12850. /**
  12851. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12852. * Returns the AbstractMesh.
  12853. */
  12854. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12855. result.x = this._pivotMatrix.m[12];
  12856. result.y = this._pivotMatrix.m[13];
  12857. result.z = this._pivotMatrix.m[14];
  12858. this.getPivotPointToRef(result);
  12859. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12860. return this;
  12861. };
  12862. // Facet data
  12863. /**
  12864. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12865. * Returns the AbstractMesh.
  12866. */
  12867. AbstractMesh.prototype._initFacetData = function () {
  12868. if (!this._facetNormals) {
  12869. this._facetNormals = new Array();
  12870. }
  12871. if (!this._facetPositions) {
  12872. this._facetPositions = new Array();
  12873. }
  12874. if (!this._facetPartitioning) {
  12875. this._facetPartitioning = new Array();
  12876. }
  12877. this._facetNb = this.getIndices().length / 3;
  12878. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12879. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12880. for (var f = 0; f < this._facetNb; f++) {
  12881. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12882. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12883. }
  12884. this._facetDataEnabled = true;
  12885. return this;
  12886. };
  12887. /**
  12888. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12889. * This method can be called within the render loop.
  12890. * 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.
  12891. * Returns the AbstractMesh.
  12892. */
  12893. AbstractMesh.prototype.updateFacetData = function () {
  12894. if (!this._facetDataEnabled) {
  12895. this._initFacetData();
  12896. }
  12897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12898. var indices = this.getIndices();
  12899. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12900. var bInfo = this.getBoundingInfo();
  12901. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12902. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12903. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12904. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12905. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12906. this._subDiv.max = this._partitioningSubdivisions;
  12907. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12908. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12909. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12910. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12911. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12912. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12913. // set the parameters for ComputeNormals()
  12914. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12915. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12916. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12917. this._facetParameters.bInfo = bInfo;
  12918. this._facetParameters.bbSize = this._bbSize;
  12919. this._facetParameters.subDiv = this._subDiv;
  12920. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12921. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12922. return this;
  12923. };
  12924. /**
  12925. * Returns the facetLocalNormals array.
  12926. * The normals are expressed in the mesh local space.
  12927. */
  12928. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12929. if (!this._facetNormals) {
  12930. this.updateFacetData();
  12931. }
  12932. return this._facetNormals;
  12933. };
  12934. /**
  12935. * Returns the facetLocalPositions array.
  12936. * The facet positions are expressed in the mesh local space.
  12937. */
  12938. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12939. if (!this._facetPositions) {
  12940. this.updateFacetData();
  12941. }
  12942. return this._facetPositions;
  12943. };
  12944. /**
  12945. * Returns the facetLocalPartioning array.
  12946. */
  12947. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12948. if (!this._facetPartitioning) {
  12949. this.updateFacetData();
  12950. }
  12951. return this._facetPartitioning;
  12952. };
  12953. /**
  12954. * Returns the i-th facet position in the world system.
  12955. * This method allocates a new Vector3 per call.
  12956. */
  12957. AbstractMesh.prototype.getFacetPosition = function (i) {
  12958. var pos = BABYLON.Vector3.Zero();
  12959. this.getFacetPositionToRef(i, pos);
  12960. return pos;
  12961. };
  12962. /**
  12963. * Sets the reference Vector3 with the i-th facet position in the world system.
  12964. * Returns the AbstractMesh.
  12965. */
  12966. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12967. var localPos = (this.getFacetLocalPositions())[i];
  12968. var world = this.getWorldMatrix();
  12969. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12970. return this;
  12971. };
  12972. /**
  12973. * Returns the i-th facet normal in the world system.
  12974. * This method allocates a new Vector3 per call.
  12975. */
  12976. AbstractMesh.prototype.getFacetNormal = function (i) {
  12977. var norm = BABYLON.Vector3.Zero();
  12978. this.getFacetNormalToRef(i, norm);
  12979. return norm;
  12980. };
  12981. /**
  12982. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12983. * Returns the AbstractMesh.
  12984. */
  12985. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12986. var localNorm = (this.getFacetLocalNormals())[i];
  12987. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12988. return this;
  12989. };
  12990. /**
  12991. * 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).
  12992. */
  12993. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12994. var bInfo = this.getBoundingInfo();
  12995. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12996. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12997. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12998. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12999. return null;
  13000. }
  13001. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13002. };
  13003. /**
  13004. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13005. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13006. * 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.
  13007. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13008. * 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.
  13009. */
  13010. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13011. if (checkFace === void 0) { checkFace = false; }
  13012. if (facing === void 0) { facing = true; }
  13013. var world = this.getWorldMatrix();
  13014. var invMat = BABYLON.Tmp.Matrix[5];
  13015. world.invertToRef(invMat);
  13016. var invVect = BABYLON.Tmp.Vector3[8];
  13017. var closest = null;
  13018. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13019. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13020. if (projected) {
  13021. // tranform the local computed projected vector to world coordinates
  13022. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13023. }
  13024. return closest;
  13025. };
  13026. /**
  13027. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13028. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13029. * 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.
  13030. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13031. * 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.
  13032. */
  13033. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13034. if (checkFace === void 0) { checkFace = false; }
  13035. if (facing === void 0) { facing = true; }
  13036. var closest = null;
  13037. var tmpx = 0.0;
  13038. var tmpy = 0.0;
  13039. var tmpz = 0.0;
  13040. var d = 0.0; // tmp dot facet normal * facet position
  13041. var t0 = 0.0;
  13042. var projx = 0.0;
  13043. var projy = 0.0;
  13044. var projz = 0.0;
  13045. // Get all the facets in the same partitioning block than (x, y, z)
  13046. var facetPositions = this.getFacetLocalPositions();
  13047. var facetNormals = this.getFacetLocalNormals();
  13048. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13049. if (!facetsInBlock) {
  13050. return null;
  13051. }
  13052. // Get the closest facet to (x, y, z)
  13053. var shortest = Number.MAX_VALUE; // init distance vars
  13054. var tmpDistance = shortest;
  13055. var fib; // current facet in the block
  13056. var norm; // current facet normal
  13057. var p0; // current facet barycenter position
  13058. // loop on all the facets in the current partitioning block
  13059. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13060. fib = facetsInBlock[idx];
  13061. norm = facetNormals[fib];
  13062. p0 = facetPositions[fib];
  13063. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13064. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13065. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13066. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13067. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13068. projx = x + norm.x * t0;
  13069. projy = y + norm.y * t0;
  13070. projz = z + norm.z * t0;
  13071. tmpx = projx - x;
  13072. tmpy = projy - y;
  13073. tmpz = projz - z;
  13074. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13075. if (tmpDistance < shortest) {
  13076. shortest = tmpDistance;
  13077. closest = fib;
  13078. if (projected) {
  13079. projected.x = projx;
  13080. projected.y = projy;
  13081. projected.z = projz;
  13082. }
  13083. }
  13084. }
  13085. }
  13086. return closest;
  13087. };
  13088. /**
  13089. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13090. */
  13091. AbstractMesh.prototype.getFacetDataParameters = function () {
  13092. return this._facetParameters;
  13093. };
  13094. /**
  13095. * Disables the feature FacetData and frees the related memory.
  13096. * Returns the AbstractMesh.
  13097. */
  13098. AbstractMesh.prototype.disableFacetData = function () {
  13099. if (this._facetDataEnabled) {
  13100. this._facetDataEnabled = false;
  13101. this._facetPositions = null;
  13102. this._facetNormals = null;
  13103. this._facetPartitioning = null;
  13104. this._facetParameters = null;
  13105. }
  13106. return this;
  13107. };
  13108. /**
  13109. * Creates new normals data for the mesh.
  13110. * @param updatable.
  13111. */
  13112. AbstractMesh.prototype.createNormals = function (updatable) {
  13113. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13114. var indices = this.getIndices();
  13115. var normals;
  13116. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13117. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13118. }
  13119. else {
  13120. normals = [];
  13121. }
  13122. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13123. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13124. };
  13125. return AbstractMesh;
  13126. }(BABYLON.Node));
  13127. // Statics
  13128. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13129. AbstractMesh._BILLBOARDMODE_X = 1;
  13130. AbstractMesh._BILLBOARDMODE_Y = 2;
  13131. AbstractMesh._BILLBOARDMODE_Z = 4;
  13132. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13133. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13134. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13135. BABYLON.AbstractMesh = AbstractMesh;
  13136. })(BABYLON || (BABYLON = {}));
  13137. //# sourceMappingURL=babylon.abstractMesh.js.map
  13138. var BABYLON;
  13139. (function (BABYLON) {
  13140. var Light = (function (_super) {
  13141. __extends(Light, _super);
  13142. /**
  13143. * Creates a Light object in the scene.
  13144. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13145. */
  13146. function Light(name, scene) {
  13147. var _this = _super.call(this, name, scene) || this;
  13148. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13149. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13150. _this.intensity = 1.0;
  13151. _this.range = Number.MAX_VALUE;
  13152. /**
  13153. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13154. * of light.
  13155. */
  13156. _this._photometricScale = 1.0;
  13157. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13158. _this._radius = 0.00001;
  13159. _this.renderPriority = 0;
  13160. /**
  13161. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13162. * the current shadow generator.
  13163. */
  13164. _this.shadowEnabled = true;
  13165. _this._excludeWithLayerMask = 0;
  13166. _this._includeOnlyWithLayerMask = 0;
  13167. _this._lightmapMode = 0;
  13168. _this._excludedMeshesIds = new Array();
  13169. _this._includedOnlyMeshesIds = new Array();
  13170. _this.getScene().addLight(_this);
  13171. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13172. _this._buildUniformLayout();
  13173. _this.includedOnlyMeshes = new Array();
  13174. _this.excludedMeshes = new Array();
  13175. _this._resyncMeshes();
  13176. return _this;
  13177. }
  13178. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13179. /**
  13180. * If every light affecting the material is in this lightmapMode,
  13181. * material.lightmapTexture adds or multiplies
  13182. * (depends on material.useLightmapAsShadowmap)
  13183. * after every other light calculations.
  13184. */
  13185. get: function () {
  13186. return Light._LIGHTMAP_DEFAULT;
  13187. },
  13188. enumerable: true,
  13189. configurable: true
  13190. });
  13191. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13192. /**
  13193. * material.lightmapTexture as only diffuse lighting from this light
  13194. * adds pnly specular lighting from this light
  13195. * adds dynamic shadows
  13196. */
  13197. get: function () {
  13198. return Light._LIGHTMAP_SPECULAR;
  13199. },
  13200. enumerable: true,
  13201. configurable: true
  13202. });
  13203. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13204. /**
  13205. * material.lightmapTexture as only lighting
  13206. * no light calculation from this light
  13207. * only adds dynamic shadows from this light
  13208. */
  13209. get: function () {
  13210. return Light._LIGHTMAP_SHADOWSONLY;
  13211. },
  13212. enumerable: true,
  13213. configurable: true
  13214. });
  13215. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13216. /**
  13217. * Each light type uses the default quantity according to its type:
  13218. * point/spot lights use luminous intensity
  13219. * directional lights use illuminance
  13220. */
  13221. get: function () {
  13222. return Light._INTENSITYMODE_AUTOMATIC;
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13228. /**
  13229. * lumen (lm)
  13230. */
  13231. get: function () {
  13232. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13238. /**
  13239. * candela (lm/sr)
  13240. */
  13241. get: function () {
  13242. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13243. },
  13244. enumerable: true,
  13245. configurable: true
  13246. });
  13247. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13248. /**
  13249. * lux (lm/m^2)
  13250. */
  13251. get: function () {
  13252. return Light._INTENSITYMODE_ILLUMINANCE;
  13253. },
  13254. enumerable: true,
  13255. configurable: true
  13256. });
  13257. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13258. /**
  13259. * nit (cd/m^2)
  13260. */
  13261. get: function () {
  13262. return Light._INTENSITYMODE_LUMINANCE;
  13263. },
  13264. enumerable: true,
  13265. configurable: true
  13266. });
  13267. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13268. /**
  13269. * Light type const id of the point light.
  13270. */
  13271. get: function () {
  13272. return Light._LIGHTTYPEID_POINTLIGHT;
  13273. },
  13274. enumerable: true,
  13275. configurable: true
  13276. });
  13277. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13278. /**
  13279. * Light type const id of the directional light.
  13280. */
  13281. get: function () {
  13282. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13283. },
  13284. enumerable: true,
  13285. configurable: true
  13286. });
  13287. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13288. /**
  13289. * Light type const id of the spot light.
  13290. */
  13291. get: function () {
  13292. return Light._LIGHTTYPEID_SPOTLIGHT;
  13293. },
  13294. enumerable: true,
  13295. configurable: true
  13296. });
  13297. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13298. /**
  13299. * Light type const id of the hemispheric light.
  13300. */
  13301. get: function () {
  13302. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. Object.defineProperty(Light.prototype, "intensityMode", {
  13308. /**
  13309. * Gets the photometric scale used to interpret the intensity.
  13310. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13311. */
  13312. get: function () {
  13313. return this._intensityMode;
  13314. },
  13315. /**
  13316. * Sets the photometric scale used to interpret the intensity.
  13317. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13318. */
  13319. set: function (value) {
  13320. this._intensityMode = value;
  13321. this._computePhotometricScale();
  13322. },
  13323. enumerable: true,
  13324. configurable: true
  13325. });
  13326. ;
  13327. ;
  13328. Object.defineProperty(Light.prototype, "radius", {
  13329. /**
  13330. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13331. */
  13332. get: function () {
  13333. return this._radius;
  13334. },
  13335. /**
  13336. * sets the light radius used by PBR Materials to simulate soft area lights.
  13337. */
  13338. set: function (value) {
  13339. this._radius = value;
  13340. this._computePhotometricScale();
  13341. },
  13342. enumerable: true,
  13343. configurable: true
  13344. });
  13345. ;
  13346. ;
  13347. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13348. get: function () {
  13349. return this._includedOnlyMeshes;
  13350. },
  13351. set: function (value) {
  13352. this._includedOnlyMeshes = value;
  13353. this._hookArrayForIncludedOnly(value);
  13354. },
  13355. enumerable: true,
  13356. configurable: true
  13357. });
  13358. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13359. get: function () {
  13360. return this._excludedMeshes;
  13361. },
  13362. set: function (value) {
  13363. this._excludedMeshes = value;
  13364. this._hookArrayForExcluded(value);
  13365. },
  13366. enumerable: true,
  13367. configurable: true
  13368. });
  13369. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13370. get: function () {
  13371. return this._excludeWithLayerMask;
  13372. },
  13373. set: function (value) {
  13374. this._excludeWithLayerMask = value;
  13375. this._resyncMeshes();
  13376. },
  13377. enumerable: true,
  13378. configurable: true
  13379. });
  13380. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13381. get: function () {
  13382. return this._includeOnlyWithLayerMask;
  13383. },
  13384. set: function (value) {
  13385. this._includeOnlyWithLayerMask = value;
  13386. this._resyncMeshes();
  13387. },
  13388. enumerable: true,
  13389. configurable: true
  13390. });
  13391. Object.defineProperty(Light.prototype, "lightmapMode", {
  13392. get: function () {
  13393. return this._lightmapMode;
  13394. },
  13395. set: function (value) {
  13396. if (this._lightmapMode === value) {
  13397. return;
  13398. }
  13399. this._lightmapMode = value;
  13400. this._markMeshesAsLightDirty();
  13401. },
  13402. enumerable: true,
  13403. configurable: true
  13404. });
  13405. Light.prototype._buildUniformLayout = function () {
  13406. // Overridden
  13407. };
  13408. /**
  13409. * Returns the string "Light".
  13410. */
  13411. Light.prototype.getClassName = function () {
  13412. return "Light";
  13413. };
  13414. /**
  13415. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13416. */
  13417. Light.prototype.toString = function (fullDetails) {
  13418. var ret = "Name: " + this.name;
  13419. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13420. if (this.animations) {
  13421. for (var i = 0; i < this.animations.length; i++) {
  13422. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13423. }
  13424. }
  13425. if (fullDetails) {
  13426. }
  13427. return ret;
  13428. };
  13429. /**
  13430. * Set the enabled state of this node.
  13431. * @param {boolean} value - the new enabled state
  13432. * @see isEnabled
  13433. */
  13434. Light.prototype.setEnabled = function (value) {
  13435. _super.prototype.setEnabled.call(this, value);
  13436. this._resyncMeshes();
  13437. };
  13438. /**
  13439. * Returns the Light associated shadow generator.
  13440. */
  13441. Light.prototype.getShadowGenerator = function () {
  13442. return this._shadowGenerator;
  13443. };
  13444. /**
  13445. * Returns a Vector3, the absolute light position in the World.
  13446. */
  13447. Light.prototype.getAbsolutePosition = function () {
  13448. return BABYLON.Vector3.Zero();
  13449. };
  13450. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13451. };
  13452. Light.prototype._getWorldMatrix = function () {
  13453. return BABYLON.Matrix.Identity();
  13454. };
  13455. /**
  13456. * Boolean : True if the light will affect the passed mesh.
  13457. */
  13458. Light.prototype.canAffectMesh = function (mesh) {
  13459. if (!mesh) {
  13460. return true;
  13461. }
  13462. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13463. return false;
  13464. }
  13465. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13466. return false;
  13467. }
  13468. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13469. return false;
  13470. }
  13471. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13472. return false;
  13473. }
  13474. return true;
  13475. };
  13476. /**
  13477. * Returns the light World matrix.
  13478. */
  13479. Light.prototype.getWorldMatrix = function () {
  13480. this._currentRenderId = this.getScene().getRenderId();
  13481. var worldMatrix = this._getWorldMatrix();
  13482. if (this.parent && this.parent.getWorldMatrix) {
  13483. if (!this._parentedWorldMatrix) {
  13484. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13485. }
  13486. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13487. this._markSyncedWithParent();
  13488. return this._parentedWorldMatrix;
  13489. }
  13490. return worldMatrix;
  13491. };
  13492. /**
  13493. * Sort function to order lights for rendering.
  13494. * @param a First Light object to compare to second.
  13495. * @param b Second Light object to compare first.
  13496. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13497. */
  13498. Light.compareLightsPriority = function (a, b) {
  13499. //shadow-casting lights have priority over non-shadow-casting lights
  13500. //the renderPrioirty is a secondary sort criterion
  13501. if (a.shadowEnabled !== b.shadowEnabled) {
  13502. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13503. }
  13504. return b.renderPriority - a.renderPriority;
  13505. };
  13506. /**
  13507. * Disposes the light.
  13508. */
  13509. Light.prototype.dispose = function () {
  13510. if (this._shadowGenerator) {
  13511. this._shadowGenerator.dispose();
  13512. this._shadowGenerator = null;
  13513. }
  13514. // Animations
  13515. this.getScene().stopAnimation(this);
  13516. // Remove from meshes
  13517. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13518. var mesh = _a[_i];
  13519. mesh._removeLightSource(this);
  13520. }
  13521. this._uniformBuffer.dispose();
  13522. // Remove from scene
  13523. this.getScene().removeLight(this);
  13524. _super.prototype.dispose.call(this);
  13525. };
  13526. /**
  13527. * Returns the light type ID (integer).
  13528. */
  13529. Light.prototype.getTypeID = function () {
  13530. return 0;
  13531. };
  13532. /**
  13533. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13534. */
  13535. Light.prototype.getScaledIntensity = function () {
  13536. return this._photometricScale * this.intensity;
  13537. };
  13538. /**
  13539. * Returns a new Light object, named "name", from the current one.
  13540. */
  13541. Light.prototype.clone = function (name) {
  13542. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13543. };
  13544. /**
  13545. * Serializes the current light into a Serialization object.
  13546. * Returns the serialized object.
  13547. */
  13548. Light.prototype.serialize = function () {
  13549. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13550. // Type
  13551. serializationObject.type = this.getTypeID();
  13552. // Parent
  13553. if (this.parent) {
  13554. serializationObject.parentId = this.parent.id;
  13555. }
  13556. // Inclusion / exclusions
  13557. if (this.excludedMeshes.length > 0) {
  13558. serializationObject.excludedMeshesIds = [];
  13559. this.excludedMeshes.forEach(function (mesh) {
  13560. serializationObject.excludedMeshesIds.push(mesh.id);
  13561. });
  13562. }
  13563. if (this.includedOnlyMeshes.length > 0) {
  13564. serializationObject.includedOnlyMeshesIds = [];
  13565. this.includedOnlyMeshes.forEach(function (mesh) {
  13566. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13567. });
  13568. }
  13569. // Animations
  13570. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13571. serializationObject.ranges = this.serializeAnimationRanges();
  13572. return serializationObject;
  13573. };
  13574. /**
  13575. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13576. * This new light is named "name" and added to the passed scene.
  13577. */
  13578. Light.GetConstructorFromName = function (type, name, scene) {
  13579. switch (type) {
  13580. case 0:
  13581. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13582. case 1:
  13583. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13584. case 2:
  13585. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13586. case 3:
  13587. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13588. }
  13589. };
  13590. /**
  13591. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13592. */
  13593. Light.Parse = function (parsedLight, scene) {
  13594. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13595. // Inclusion / exclusions
  13596. if (parsedLight.excludedMeshesIds) {
  13597. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13598. }
  13599. if (parsedLight.includedOnlyMeshesIds) {
  13600. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13601. }
  13602. // Parent
  13603. if (parsedLight.parentId) {
  13604. light._waitingParentId = parsedLight.parentId;
  13605. }
  13606. // Animations
  13607. if (parsedLight.animations) {
  13608. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13609. var parsedAnimation = parsedLight.animations[animationIndex];
  13610. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13611. }
  13612. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13613. }
  13614. if (parsedLight.autoAnimate) {
  13615. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13616. }
  13617. return light;
  13618. };
  13619. Light.prototype._hookArrayForExcluded = function (array) {
  13620. var _this = this;
  13621. var oldPush = array.push;
  13622. array.push = function () {
  13623. var items = [];
  13624. for (var _i = 0; _i < arguments.length; _i++) {
  13625. items[_i] = arguments[_i];
  13626. }
  13627. var result = oldPush.apply(array, items);
  13628. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13629. var item = items_1[_a];
  13630. item._resyncLighSource(_this);
  13631. }
  13632. return result;
  13633. };
  13634. var oldSplice = array.splice;
  13635. array.splice = function (index, deleteCount) {
  13636. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13637. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13638. var item = deleted_1[_i];
  13639. item._resyncLighSource(_this);
  13640. }
  13641. return deleted;
  13642. };
  13643. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13644. var item = array_1[_i];
  13645. item._resyncLighSource(this);
  13646. }
  13647. };
  13648. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13649. var _this = this;
  13650. var oldPush = array.push;
  13651. array.push = function () {
  13652. var items = [];
  13653. for (var _i = 0; _i < arguments.length; _i++) {
  13654. items[_i] = arguments[_i];
  13655. }
  13656. var result = oldPush.apply(array, items);
  13657. _this._resyncMeshes();
  13658. return result;
  13659. };
  13660. var oldSplice = array.splice;
  13661. array.splice = function (index, deleteCount) {
  13662. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13663. _this._resyncMeshes();
  13664. return deleted;
  13665. };
  13666. this._resyncMeshes();
  13667. };
  13668. Light.prototype._resyncMeshes = function () {
  13669. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13670. var mesh = _a[_i];
  13671. mesh._resyncLighSource(this);
  13672. }
  13673. };
  13674. Light.prototype._markMeshesAsLightDirty = function () {
  13675. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13676. var mesh = _a[_i];
  13677. if (mesh._lightSources.indexOf(this) !== -1) {
  13678. mesh._markSubMeshesAsLightDirty();
  13679. }
  13680. }
  13681. };
  13682. /**
  13683. * Recomputes the cached photometric scale if needed.
  13684. */
  13685. Light.prototype._computePhotometricScale = function () {
  13686. this._photometricScale = this._getPhotometricScale();
  13687. this.getScene().resetCachedMaterial();
  13688. };
  13689. /**
  13690. * Returns the Photometric Scale according to the light type and intensity mode.
  13691. */
  13692. Light.prototype._getPhotometricScale = function () {
  13693. var photometricScale = 0.0;
  13694. var lightTypeID = this.getTypeID();
  13695. //get photometric mode
  13696. var photometricMode = this.intensityMode;
  13697. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13698. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13699. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13700. }
  13701. else {
  13702. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13703. }
  13704. }
  13705. //compute photometric scale
  13706. switch (lightTypeID) {
  13707. case Light.LIGHTTYPEID_POINTLIGHT:
  13708. case Light.LIGHTTYPEID_SPOTLIGHT:
  13709. switch (photometricMode) {
  13710. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13711. photometricScale = 1.0 / (4.0 * Math.PI);
  13712. break;
  13713. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13714. photometricScale = 1.0;
  13715. break;
  13716. case Light.INTENSITYMODE_LUMINANCE:
  13717. photometricScale = this.radius * this.radius;
  13718. break;
  13719. }
  13720. break;
  13721. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13722. switch (photometricMode) {
  13723. case Light.INTENSITYMODE_ILLUMINANCE:
  13724. photometricScale = 1.0;
  13725. break;
  13726. case Light.INTENSITYMODE_LUMINANCE:
  13727. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13728. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13729. var apexAngleRadians = this.radius;
  13730. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13731. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13732. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13733. photometricScale = solidAngle;
  13734. break;
  13735. }
  13736. break;
  13737. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13738. // No fall off in hemisperic light.
  13739. photometricScale = 1.0;
  13740. break;
  13741. }
  13742. return photometricScale;
  13743. };
  13744. Light.prototype._reorderLightsInScene = function () {
  13745. var scene = this.getScene();
  13746. if (this.renderPriority != 0) {
  13747. scene.requireLightSorting = true;
  13748. }
  13749. this.getScene().sortLightsByPriority();
  13750. };
  13751. return Light;
  13752. }(BABYLON.Node));
  13753. //lightmapMode Consts
  13754. Light._LIGHTMAP_DEFAULT = 0;
  13755. Light._LIGHTMAP_SPECULAR = 1;
  13756. Light._LIGHTMAP_SHADOWSONLY = 2;
  13757. // Intensity Mode Consts
  13758. Light._INTENSITYMODE_AUTOMATIC = 0;
  13759. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13760. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13761. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13762. Light._INTENSITYMODE_LUMINANCE = 4;
  13763. // Light types ids const.
  13764. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13765. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13766. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13767. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13768. __decorate([
  13769. BABYLON.serializeAsColor3()
  13770. ], Light.prototype, "diffuse", void 0);
  13771. __decorate([
  13772. BABYLON.serializeAsColor3()
  13773. ], Light.prototype, "specular", void 0);
  13774. __decorate([
  13775. BABYLON.serialize()
  13776. ], Light.prototype, "intensity", void 0);
  13777. __decorate([
  13778. BABYLON.serialize()
  13779. ], Light.prototype, "range", void 0);
  13780. __decorate([
  13781. BABYLON.serialize()
  13782. ], Light.prototype, "intensityMode", null);
  13783. __decorate([
  13784. BABYLON.serialize()
  13785. ], Light.prototype, "radius", null);
  13786. __decorate([
  13787. BABYLON.serialize()
  13788. ], Light.prototype, "_renderPriority", void 0);
  13789. __decorate([
  13790. BABYLON.expandToProperty("_reorderLightsInScene")
  13791. ], Light.prototype, "renderPriority", void 0);
  13792. __decorate([
  13793. BABYLON.serialize()
  13794. ], Light.prototype, "shadowEnabled", void 0);
  13795. __decorate([
  13796. BABYLON.serialize("excludeWithLayerMask")
  13797. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13798. __decorate([
  13799. BABYLON.serialize("includeOnlyWithLayerMask")
  13800. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13801. __decorate([
  13802. BABYLON.serialize("lightmapMode")
  13803. ], Light.prototype, "_lightmapMode", void 0);
  13804. BABYLON.Light = Light;
  13805. })(BABYLON || (BABYLON = {}));
  13806. //# sourceMappingURL=babylon.light.js.map
  13807. var BABYLON;
  13808. (function (BABYLON) {
  13809. var Camera = (function (_super) {
  13810. __extends(Camera, _super);
  13811. function Camera(name, position, scene) {
  13812. var _this = _super.call(this, name, scene) || this;
  13813. _this.upVector = BABYLON.Vector3.Up();
  13814. _this.orthoLeft = null;
  13815. _this.orthoRight = null;
  13816. _this.orthoBottom = null;
  13817. _this.orthoTop = null;
  13818. _this.fov = 0.8;
  13819. _this.minZ = 1.0;
  13820. _this.maxZ = 10000.0;
  13821. _this.inertia = 0.9;
  13822. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13823. _this.isIntermediate = false;
  13824. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13825. _this.layerMask = 0x0FFFFFFF;
  13826. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13827. // Camera rig members
  13828. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13829. _this._rigCameras = new Array();
  13830. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13831. // Cache
  13832. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13833. _this._projectionMatrix = new BABYLON.Matrix();
  13834. _this._doNotComputeProjectionMatrix = false;
  13835. _this._postProcesses = new Array();
  13836. _this._transformMatrix = BABYLON.Matrix.Zero();
  13837. _this._activeMeshes = new BABYLON.SmartArray(256);
  13838. _this._globalPosition = BABYLON.Vector3.Zero();
  13839. _this._refreshFrustumPlanes = true;
  13840. _this.getScene().addCamera(_this);
  13841. if (!_this.getScene().activeCamera) {
  13842. _this.getScene().activeCamera = _this;
  13843. }
  13844. _this.position = position;
  13845. return _this;
  13846. }
  13847. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13848. get: function () {
  13849. return Camera._PERSPECTIVE_CAMERA;
  13850. },
  13851. enumerable: true,
  13852. configurable: true
  13853. });
  13854. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13855. get: function () {
  13856. return Camera._ORTHOGRAPHIC_CAMERA;
  13857. },
  13858. enumerable: true,
  13859. configurable: true
  13860. });
  13861. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13862. get: function () {
  13863. return Camera._FOVMODE_VERTICAL_FIXED;
  13864. },
  13865. enumerable: true,
  13866. configurable: true
  13867. });
  13868. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13869. get: function () {
  13870. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13871. },
  13872. enumerable: true,
  13873. configurable: true
  13874. });
  13875. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13876. get: function () {
  13877. return Camera._RIG_MODE_NONE;
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13883. get: function () {
  13884. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13890. get: function () {
  13891. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13897. get: function () {
  13898. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13904. get: function () {
  13905. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13906. },
  13907. enumerable: true,
  13908. configurable: true
  13909. });
  13910. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13911. get: function () {
  13912. return Camera._RIG_MODE_VR;
  13913. },
  13914. enumerable: true,
  13915. configurable: true
  13916. });
  13917. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13918. get: function () {
  13919. return Camera._RIG_MODE_WEBVR;
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. Camera.prototype.getClassName = function () {
  13925. return "Camera";
  13926. };
  13927. /**
  13928. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13929. */
  13930. Camera.prototype.toString = function (fullDetails) {
  13931. var ret = "Name: " + this.name;
  13932. ret += ", type: " + this.getClassName();
  13933. if (this.animations) {
  13934. for (var i = 0; i < this.animations.length; i++) {
  13935. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13936. }
  13937. }
  13938. if (fullDetails) {
  13939. }
  13940. return ret;
  13941. };
  13942. Object.defineProperty(Camera.prototype, "globalPosition", {
  13943. get: function () {
  13944. return this._globalPosition;
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. Camera.prototype.getActiveMeshes = function () {
  13950. return this._activeMeshes;
  13951. };
  13952. Camera.prototype.isActiveMesh = function (mesh) {
  13953. return (this._activeMeshes.indexOf(mesh) !== -1);
  13954. };
  13955. //Cache
  13956. Camera.prototype._initCache = function () {
  13957. _super.prototype._initCache.call(this);
  13958. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13959. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13960. this._cache.mode = undefined;
  13961. this._cache.minZ = undefined;
  13962. this._cache.maxZ = undefined;
  13963. this._cache.fov = undefined;
  13964. this._cache.fovMode = undefined;
  13965. this._cache.aspectRatio = undefined;
  13966. this._cache.orthoLeft = undefined;
  13967. this._cache.orthoRight = undefined;
  13968. this._cache.orthoBottom = undefined;
  13969. this._cache.orthoTop = undefined;
  13970. this._cache.renderWidth = undefined;
  13971. this._cache.renderHeight = undefined;
  13972. };
  13973. Camera.prototype._updateCache = function (ignoreParentClass) {
  13974. if (!ignoreParentClass) {
  13975. _super.prototype._updateCache.call(this);
  13976. }
  13977. var engine = this.getEngine();
  13978. this._cache.position.copyFrom(this.position);
  13979. this._cache.upVector.copyFrom(this.upVector);
  13980. this._cache.mode = this.mode;
  13981. this._cache.minZ = this.minZ;
  13982. this._cache.maxZ = this.maxZ;
  13983. this._cache.fov = this.fov;
  13984. this._cache.fovMode = this.fovMode;
  13985. this._cache.aspectRatio = engine.getAspectRatio(this);
  13986. this._cache.orthoLeft = this.orthoLeft;
  13987. this._cache.orthoRight = this.orthoRight;
  13988. this._cache.orthoBottom = this.orthoBottom;
  13989. this._cache.orthoTop = this.orthoTop;
  13990. this._cache.renderWidth = engine.getRenderWidth();
  13991. this._cache.renderHeight = engine.getRenderHeight();
  13992. };
  13993. Camera.prototype._updateFromScene = function () {
  13994. this.updateCache();
  13995. this.update();
  13996. };
  13997. // Synchronized
  13998. Camera.prototype._isSynchronized = function () {
  13999. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14000. };
  14001. Camera.prototype._isSynchronizedViewMatrix = function () {
  14002. if (!_super.prototype._isSynchronized.call(this))
  14003. return false;
  14004. return this._cache.position.equals(this.position)
  14005. && this._cache.upVector.equals(this.upVector)
  14006. && this.isSynchronizedWithParent();
  14007. };
  14008. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14009. var check = this._cache.mode === this.mode
  14010. && this._cache.minZ === this.minZ
  14011. && this._cache.maxZ === this.maxZ;
  14012. if (!check) {
  14013. return false;
  14014. }
  14015. var engine = this.getEngine();
  14016. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14017. check = this._cache.fov === this.fov
  14018. && this._cache.fovMode === this.fovMode
  14019. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14020. }
  14021. else {
  14022. check = this._cache.orthoLeft === this.orthoLeft
  14023. && this._cache.orthoRight === this.orthoRight
  14024. && this._cache.orthoBottom === this.orthoBottom
  14025. && this._cache.orthoTop === this.orthoTop
  14026. && this._cache.renderWidth === engine.getRenderWidth()
  14027. && this._cache.renderHeight === engine.getRenderHeight();
  14028. }
  14029. return check;
  14030. };
  14031. // Controls
  14032. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14033. };
  14034. Camera.prototype.detachControl = function (element) {
  14035. };
  14036. Camera.prototype.update = function () {
  14037. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14038. this._updateRigCameras();
  14039. }
  14040. this._checkInputs();
  14041. };
  14042. Camera.prototype._checkInputs = function () {
  14043. };
  14044. Object.defineProperty(Camera.prototype, "rigCameras", {
  14045. get: function () {
  14046. return this._rigCameras;
  14047. },
  14048. enumerable: true,
  14049. configurable: true
  14050. });
  14051. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14052. get: function () {
  14053. return this._rigPostProcess;
  14054. },
  14055. enumerable: true,
  14056. configurable: true
  14057. });
  14058. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14059. // invalidate framebuffer
  14060. if (this._postProcesses.length > 0) {
  14061. this._postProcesses[0].markTextureDirty();
  14062. }
  14063. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14064. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14065. var cam = this._rigCameras[i];
  14066. var rigPostProcess = cam._rigPostProcess;
  14067. // for VR rig, there does not have to be a post process
  14068. if (rigPostProcess) {
  14069. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14070. if (isPass) {
  14071. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14072. cam.isIntermediate = this._postProcesses.length === 0;
  14073. }
  14074. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14075. rigPostProcess.markTextureDirty();
  14076. }
  14077. else {
  14078. cam._postProcesses = this._postProcesses.slice(0);
  14079. }
  14080. }
  14081. };
  14082. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14083. if (insertAt === void 0) { insertAt = null; }
  14084. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14085. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14086. return 0;
  14087. }
  14088. if (insertAt == null || insertAt < 0) {
  14089. this._postProcesses.push(postProcess);
  14090. }
  14091. else {
  14092. this._postProcesses.splice(insertAt, 0, postProcess);
  14093. }
  14094. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14095. return this._postProcesses.indexOf(postProcess);
  14096. };
  14097. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14098. if (atIndices === void 0) { atIndices = null; }
  14099. var result = [];
  14100. var i;
  14101. var index;
  14102. if (!atIndices) {
  14103. var idx = this._postProcesses.indexOf(postProcess);
  14104. if (idx !== -1) {
  14105. this._postProcesses.splice(idx, 1);
  14106. }
  14107. }
  14108. else {
  14109. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14110. // iterate descending, so can just splice as we go
  14111. for (i = atIndices.length - 1; i >= 0; i--) {
  14112. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14113. result.push(i);
  14114. continue;
  14115. }
  14116. index = atIndices[i];
  14117. this._postProcesses.splice(index, 1);
  14118. }
  14119. }
  14120. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14121. return result;
  14122. };
  14123. Camera.prototype.getWorldMatrix = function () {
  14124. if (!this._worldMatrix) {
  14125. this._worldMatrix = BABYLON.Matrix.Identity();
  14126. }
  14127. var viewMatrix = this.getViewMatrix();
  14128. viewMatrix.invertToRef(this._worldMatrix);
  14129. return this._worldMatrix;
  14130. };
  14131. Camera.prototype._getViewMatrix = function () {
  14132. return BABYLON.Matrix.Identity();
  14133. };
  14134. Camera.prototype.getViewMatrix = function (force) {
  14135. this._computedViewMatrix = this._computeViewMatrix(force);
  14136. if (!force && this._isSynchronizedViewMatrix()) {
  14137. return this._computedViewMatrix;
  14138. }
  14139. this._refreshFrustumPlanes = true;
  14140. if (!this.parent || !this.parent.getWorldMatrix) {
  14141. this._globalPosition.copyFrom(this.position);
  14142. }
  14143. else {
  14144. if (!this._worldMatrix) {
  14145. this._worldMatrix = BABYLON.Matrix.Identity();
  14146. }
  14147. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14148. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14149. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14150. this._computedViewMatrix.invert();
  14151. this._markSyncedWithParent();
  14152. }
  14153. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14154. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14155. }
  14156. this._currentRenderId = this.getScene().getRenderId();
  14157. return this._computedViewMatrix;
  14158. };
  14159. Camera.prototype._computeViewMatrix = function (force) {
  14160. if (!force && this._isSynchronizedViewMatrix()) {
  14161. return this._computedViewMatrix;
  14162. }
  14163. this._computedViewMatrix = this._getViewMatrix();
  14164. this._currentRenderId = this.getScene().getRenderId();
  14165. return this._computedViewMatrix;
  14166. };
  14167. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14168. this._doNotComputeProjectionMatrix = true;
  14169. if (projection !== undefined) {
  14170. this._projectionMatrix = projection;
  14171. }
  14172. };
  14173. ;
  14174. Camera.prototype.unfreezeProjectionMatrix = function () {
  14175. this._doNotComputeProjectionMatrix = false;
  14176. };
  14177. ;
  14178. Camera.prototype.getProjectionMatrix = function (force) {
  14179. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14180. return this._projectionMatrix;
  14181. }
  14182. this._refreshFrustumPlanes = true;
  14183. var engine = this.getEngine();
  14184. var scene = this.getScene();
  14185. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14186. if (this.minZ <= 0) {
  14187. this.minZ = 0.1;
  14188. }
  14189. if (scene.useRightHandedSystem) {
  14190. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14191. }
  14192. else {
  14193. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14194. }
  14195. return this._projectionMatrix;
  14196. }
  14197. var halfWidth = engine.getRenderWidth() / 2.0;
  14198. var halfHeight = engine.getRenderHeight() / 2.0;
  14199. if (scene.useRightHandedSystem) {
  14200. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14201. }
  14202. else {
  14203. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14204. }
  14205. return this._projectionMatrix;
  14206. };
  14207. Camera.prototype.getTranformationMatrix = function () {
  14208. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14209. return this._transformMatrix;
  14210. };
  14211. Camera.prototype.updateFrustumPlanes = function () {
  14212. if (!this._refreshFrustumPlanes) {
  14213. return;
  14214. }
  14215. this.getTranformationMatrix();
  14216. if (!this._frustumPlanes) {
  14217. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14218. }
  14219. else {
  14220. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14221. }
  14222. this._refreshFrustumPlanes = false;
  14223. };
  14224. Camera.prototype.isInFrustum = function (target) {
  14225. this.updateFrustumPlanes();
  14226. return target.isInFrustum(this._frustumPlanes);
  14227. };
  14228. Camera.prototype.isCompletelyInFrustum = function (target) {
  14229. this.updateFrustumPlanes();
  14230. return target.isCompletelyInFrustum(this._frustumPlanes);
  14231. };
  14232. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14233. if (length === void 0) { length = 100; }
  14234. if (!transform) {
  14235. transform = this.getWorldMatrix();
  14236. }
  14237. if (!origin) {
  14238. origin = this.position;
  14239. }
  14240. var forward = new BABYLON.Vector3(0, 0, 1);
  14241. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14242. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14243. return new BABYLON.Ray(origin, direction, length);
  14244. };
  14245. Camera.prototype.dispose = function () {
  14246. // Animations
  14247. this.getScene().stopAnimation(this);
  14248. // Remove from scene
  14249. this.getScene().removeCamera(this);
  14250. while (this._rigCameras.length > 0) {
  14251. this._rigCameras.pop().dispose();
  14252. }
  14253. // Postprocesses
  14254. var i = this._postProcesses.length;
  14255. while (--i >= 0) {
  14256. this._postProcesses[i].dispose(this);
  14257. }
  14258. _super.prototype.dispose.call(this);
  14259. };
  14260. Object.defineProperty(Camera.prototype, "leftCamera", {
  14261. // ---- Camera rigs section ----
  14262. get: function () {
  14263. if (this._rigCameras.length < 1) {
  14264. return undefined;
  14265. }
  14266. return this._rigCameras[0];
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. Object.defineProperty(Camera.prototype, "rightCamera", {
  14272. get: function () {
  14273. if (this._rigCameras.length < 2) {
  14274. return undefined;
  14275. }
  14276. return this._rigCameras[1];
  14277. },
  14278. enumerable: true,
  14279. configurable: true
  14280. });
  14281. Camera.prototype.getLeftTarget = function () {
  14282. if (this._rigCameras.length < 1) {
  14283. return undefined;
  14284. }
  14285. return this._rigCameras[0].getTarget();
  14286. };
  14287. Camera.prototype.getRightTarget = function () {
  14288. if (this._rigCameras.length < 2) {
  14289. return undefined;
  14290. }
  14291. return this._rigCameras[1].getTarget();
  14292. };
  14293. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14294. while (this._rigCameras.length > 0) {
  14295. this._rigCameras.pop().dispose();
  14296. }
  14297. this.cameraRigMode = mode;
  14298. this._cameraRigParams = {};
  14299. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14300. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14301. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14302. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14303. // create the rig cameras, unless none
  14304. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14305. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14306. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14307. }
  14308. switch (this.cameraRigMode) {
  14309. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14310. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14311. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14312. break;
  14313. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14314. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14315. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14316. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14317. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14318. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14319. break;
  14320. case Camera.RIG_MODE_VR:
  14321. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14322. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14323. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14324. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14325. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14326. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14327. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14328. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14329. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14330. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14331. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14332. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14333. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14334. if (metrics.compensateDistortion) {
  14335. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14336. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14337. }
  14338. break;
  14339. case Camera.RIG_MODE_WEBVR:
  14340. if (rigParams.vrDisplay) {
  14341. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14342. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14343. //Left eye
  14344. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14345. this._rigCameras[0].setCameraRigParameter("left", true);
  14346. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14347. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14348. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14349. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14350. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14351. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14352. this._rigCameras[0].parent = this;
  14353. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14354. //Right eye
  14355. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14356. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14357. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14358. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14359. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14360. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14361. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14362. this._rigCameras[1].parent = this;
  14363. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14364. }
  14365. break;
  14366. }
  14367. this._cascadePostProcessesToRigCams();
  14368. this.
  14369. update();
  14370. };
  14371. Camera.prototype._getVRProjectionMatrix = function () {
  14372. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14373. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14374. return this._projectionMatrix;
  14375. };
  14376. Camera.prototype._updateCameraRotationMatrix = function () {
  14377. //Here for WebVR
  14378. };
  14379. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14380. //Here for WebVR
  14381. };
  14382. /**
  14383. * This function MUST be overwritten by the different WebVR cameras available.
  14384. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14385. */
  14386. Camera.prototype._getWebVRProjectionMatrix = function () {
  14387. return BABYLON.Matrix.Identity();
  14388. };
  14389. /**
  14390. * This function MUST be overwritten by the different WebVR cameras available.
  14391. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14392. */
  14393. Camera.prototype._getWebVRViewMatrix = function () {
  14394. return BABYLON.Matrix.Identity();
  14395. };
  14396. Camera.prototype.setCameraRigParameter = function (name, value) {
  14397. if (!this._cameraRigParams) {
  14398. this._cameraRigParams = {};
  14399. }
  14400. this._cameraRigParams[name] = value;
  14401. //provisionnally:
  14402. if (name === "interaxialDistance") {
  14403. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14404. }
  14405. };
  14406. /**
  14407. * needs to be overridden by children so sub has required properties to be copied
  14408. */
  14409. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14410. return null;
  14411. };
  14412. /**
  14413. * May need to be overridden by children
  14414. */
  14415. Camera.prototype._updateRigCameras = function () {
  14416. for (var i = 0; i < this._rigCameras.length; i++) {
  14417. this._rigCameras[i].minZ = this.minZ;
  14418. this._rigCameras[i].maxZ = this.maxZ;
  14419. this._rigCameras[i].fov = this.fov;
  14420. }
  14421. // only update viewport when ANAGLYPH
  14422. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14423. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14424. }
  14425. };
  14426. Camera.prototype._setupInputs = function () {
  14427. };
  14428. Camera.prototype.serialize = function () {
  14429. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14430. // Type
  14431. serializationObject.type = this.getClassName();
  14432. // Parent
  14433. if (this.parent) {
  14434. serializationObject.parentId = this.parent.id;
  14435. }
  14436. if (this.inputs) {
  14437. this.inputs.serialize(serializationObject);
  14438. }
  14439. // Animations
  14440. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14441. serializationObject.ranges = this.serializeAnimationRanges();
  14442. return serializationObject;
  14443. };
  14444. Camera.prototype.clone = function (name) {
  14445. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14446. };
  14447. Camera.prototype.getDirection = function (localAxis) {
  14448. var result = BABYLON.Vector3.Zero();
  14449. this.getDirectionToRef(localAxis, result);
  14450. return result;
  14451. };
  14452. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14453. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14454. };
  14455. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14456. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14457. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14458. switch (type) {
  14459. case "ArcRotateCamera":
  14460. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14461. case "DeviceOrientationCamera":
  14462. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14463. case "FollowCamera":
  14464. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14465. case "ArcFollowCamera":
  14466. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14467. case "GamepadCamera":
  14468. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14469. case "TouchCamera":
  14470. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14471. case "VirtualJoysticksCamera":
  14472. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14473. case "WebVRFreeCamera":
  14474. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14475. case "WebVRGamepadCamera":
  14476. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14477. case "VRDeviceOrientationFreeCamera":
  14478. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14479. case "VRDeviceOrientationGamepadCamera":
  14480. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14481. case "AnaglyphArcRotateCamera":
  14482. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14483. case "AnaglyphFreeCamera":
  14484. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14485. case "AnaglyphGamepadCamera":
  14486. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14487. case "AnaglyphUniversalCamera":
  14488. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14489. case "StereoscopicArcRotateCamera":
  14490. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14491. case "StereoscopicFreeCamera":
  14492. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14493. case "StereoscopicGamepadCamera":
  14494. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14495. case "StereoscopicUniversalCamera":
  14496. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14497. case "FreeCamera":
  14498. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14499. default:
  14500. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14501. }
  14502. };
  14503. Camera.Parse = function (parsedCamera, scene) {
  14504. var type = parsedCamera.type;
  14505. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14506. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14507. // Parent
  14508. if (parsedCamera.parentId) {
  14509. camera._waitingParentId = parsedCamera.parentId;
  14510. }
  14511. //If camera has an input manager, let it parse inputs settings
  14512. if (camera.inputs) {
  14513. camera.inputs.parse(parsedCamera);
  14514. camera._setupInputs();
  14515. }
  14516. // Target
  14517. if (parsedCamera.target) {
  14518. if (camera.setTarget) {
  14519. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14520. }
  14521. }
  14522. // Apply 3d rig, when found
  14523. if (parsedCamera.cameraRigMode) {
  14524. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14525. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14526. }
  14527. // Animations
  14528. if (parsedCamera.animations) {
  14529. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14530. var parsedAnimation = parsedCamera.animations[animationIndex];
  14531. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14532. }
  14533. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14534. }
  14535. if (parsedCamera.autoAnimate) {
  14536. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14537. }
  14538. return camera;
  14539. };
  14540. return Camera;
  14541. }(BABYLON.Node));
  14542. // Statics
  14543. Camera._PERSPECTIVE_CAMERA = 0;
  14544. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14545. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14546. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14547. Camera._RIG_MODE_NONE = 0;
  14548. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14549. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14550. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14551. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14552. Camera._RIG_MODE_VR = 20;
  14553. Camera._RIG_MODE_WEBVR = 21;
  14554. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14555. __decorate([
  14556. BABYLON.serializeAsVector3()
  14557. ], Camera.prototype, "position", void 0);
  14558. __decorate([
  14559. BABYLON.serializeAsVector3()
  14560. ], Camera.prototype, "upVector", void 0);
  14561. __decorate([
  14562. BABYLON.serialize()
  14563. ], Camera.prototype, "orthoLeft", void 0);
  14564. __decorate([
  14565. BABYLON.serialize()
  14566. ], Camera.prototype, "orthoRight", void 0);
  14567. __decorate([
  14568. BABYLON.serialize()
  14569. ], Camera.prototype, "orthoBottom", void 0);
  14570. __decorate([
  14571. BABYLON.serialize()
  14572. ], Camera.prototype, "orthoTop", void 0);
  14573. __decorate([
  14574. BABYLON.serialize()
  14575. ], Camera.prototype, "fov", void 0);
  14576. __decorate([
  14577. BABYLON.serialize()
  14578. ], Camera.prototype, "minZ", void 0);
  14579. __decorate([
  14580. BABYLON.serialize()
  14581. ], Camera.prototype, "maxZ", void 0);
  14582. __decorate([
  14583. BABYLON.serialize()
  14584. ], Camera.prototype, "inertia", void 0);
  14585. __decorate([
  14586. BABYLON.serialize()
  14587. ], Camera.prototype, "mode", void 0);
  14588. __decorate([
  14589. BABYLON.serialize()
  14590. ], Camera.prototype, "layerMask", void 0);
  14591. __decorate([
  14592. BABYLON.serialize()
  14593. ], Camera.prototype, "fovMode", void 0);
  14594. __decorate([
  14595. BABYLON.serialize()
  14596. ], Camera.prototype, "cameraRigMode", void 0);
  14597. __decorate([
  14598. BABYLON.serialize()
  14599. ], Camera.prototype, "interaxialDistance", void 0);
  14600. __decorate([
  14601. BABYLON.serialize()
  14602. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14603. BABYLON.Camera = Camera;
  14604. })(BABYLON || (BABYLON = {}));
  14605. //# sourceMappingURL=babylon.camera.js.map
  14606. var BABYLON;
  14607. (function (BABYLON) {
  14608. var RenderingManager = (function () {
  14609. function RenderingManager(scene) {
  14610. this._renderingGroups = new Array();
  14611. this._autoClearDepthStencil = {};
  14612. this._customOpaqueSortCompareFn = {};
  14613. this._customAlphaTestSortCompareFn = {};
  14614. this._customTransparentSortCompareFn = {};
  14615. this._renderinGroupInfo = null;
  14616. this._scene = scene;
  14617. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14618. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14619. }
  14620. }
  14621. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14622. if (depth === void 0) { depth = true; }
  14623. if (stencil === void 0) { stencil = true; }
  14624. if (this._depthStencilBufferAlreadyCleaned) {
  14625. return;
  14626. }
  14627. this._scene.getEngine().clear(null, false, depth, stencil);
  14628. this._depthStencilBufferAlreadyCleaned = true;
  14629. };
  14630. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14631. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14632. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14633. var info = null;
  14634. if (observable) {
  14635. if (!this._renderinGroupInfo) {
  14636. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14637. }
  14638. info = this._renderinGroupInfo;
  14639. info.scene = this._scene;
  14640. info.camera = this._scene.activeCamera;
  14641. }
  14642. // Dispatch sprites
  14643. if (renderSprites) {
  14644. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14645. var manager = this._scene.spriteManagers[index];
  14646. this.dispatchSprites(manager);
  14647. }
  14648. }
  14649. // Render
  14650. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14651. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14652. var renderingGroup = this._renderingGroups[index];
  14653. if (!renderingGroup && !observable)
  14654. continue;
  14655. this._currentIndex = index;
  14656. var renderingGroupMask = 0;
  14657. // Fire PRECLEAR stage
  14658. if (observable) {
  14659. renderingGroupMask = Math.pow(2, index);
  14660. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14661. info.renderingGroupId = index;
  14662. observable.notifyObservers(info, renderingGroupMask);
  14663. }
  14664. // Clear depth/stencil if needed
  14665. if (RenderingManager.AUTOCLEAR) {
  14666. var autoClear = this._autoClearDepthStencil[index];
  14667. if (autoClear && autoClear.autoClear) {
  14668. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14669. }
  14670. }
  14671. if (observable) {
  14672. // Fire PREOPAQUE stage
  14673. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14674. observable.notifyObservers(info, renderingGroupMask);
  14675. // Fire PRETRANSPARENT stage
  14676. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14677. observable.notifyObservers(info, renderingGroupMask);
  14678. }
  14679. if (renderingGroup)
  14680. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14681. // Fire POSTTRANSPARENT stage
  14682. if (observable) {
  14683. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14684. observable.notifyObservers(info, renderingGroupMask);
  14685. }
  14686. }
  14687. };
  14688. RenderingManager.prototype.reset = function () {
  14689. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14690. var renderingGroup = this._renderingGroups[index];
  14691. if (renderingGroup) {
  14692. renderingGroup.prepare();
  14693. }
  14694. }
  14695. };
  14696. RenderingManager.prototype.dispose = function () {
  14697. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14698. var renderingGroup = this._renderingGroups[index];
  14699. if (renderingGroup) {
  14700. renderingGroup.dispose();
  14701. }
  14702. }
  14703. this._renderingGroups.length = 0;
  14704. };
  14705. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14706. if (!this._renderingGroups[renderingGroupId]) {
  14707. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14708. }
  14709. };
  14710. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14711. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14712. this._prepareRenderingGroup(renderingGroupId);
  14713. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14714. };
  14715. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14716. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14717. this._prepareRenderingGroup(renderingGroupId);
  14718. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14719. };
  14720. RenderingManager.prototype.dispatch = function (subMesh) {
  14721. var mesh = subMesh.getMesh();
  14722. var renderingGroupId = mesh.renderingGroupId || 0;
  14723. this._prepareRenderingGroup(renderingGroupId);
  14724. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14725. };
  14726. /**
  14727. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14728. * This allowed control for front to back rendering or reversly depending of the special needs.
  14729. *
  14730. * @param renderingGroupId The rendering group id corresponding to its index
  14731. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14732. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14733. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14734. */
  14735. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14736. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14737. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14738. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14739. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14740. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14741. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14742. if (this._renderingGroups[renderingGroupId]) {
  14743. var group = this._renderingGroups[renderingGroupId];
  14744. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14745. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14746. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14747. }
  14748. };
  14749. /**
  14750. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14751. *
  14752. * @param renderingGroupId The rendering group id corresponding to its index
  14753. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14754. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14755. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14756. */
  14757. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14758. if (depth === void 0) { depth = true; }
  14759. if (stencil === void 0) { stencil = true; }
  14760. this._autoClearDepthStencil[renderingGroupId] = {
  14761. autoClear: autoClearDepthStencil,
  14762. depth: depth,
  14763. stencil: stencil
  14764. };
  14765. };
  14766. return RenderingManager;
  14767. }());
  14768. /**
  14769. * The max id used for rendering groups (not included)
  14770. */
  14771. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14772. /**
  14773. * The min id used for rendering groups (included)
  14774. */
  14775. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14776. /**
  14777. * Used to globally prevent autoclearing scenes.
  14778. */
  14779. RenderingManager.AUTOCLEAR = true;
  14780. BABYLON.RenderingManager = RenderingManager;
  14781. })(BABYLON || (BABYLON = {}));
  14782. //# sourceMappingURL=babylon.renderingManager.js.map
  14783. var BABYLON;
  14784. (function (BABYLON) {
  14785. var RenderingGroup = (function () {
  14786. /**
  14787. * Creates a new rendering group.
  14788. * @param index The rendering group index
  14789. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14790. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14791. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14792. */
  14793. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14794. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14795. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14796. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14797. this.index = index;
  14798. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14799. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14800. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14801. this._particleSystems = new BABYLON.SmartArray(256);
  14802. this._spriteManagers = new BABYLON.SmartArray(256);
  14803. this._edgesRenderers = new BABYLON.SmartArray(16);
  14804. this._scene = scene;
  14805. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14806. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14807. this.transparentSortCompareFn = transparentSortCompareFn;
  14808. }
  14809. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14810. /**
  14811. * Set the opaque sort comparison function.
  14812. * If null the sub meshes will be render in the order they were created
  14813. */
  14814. set: function (value) {
  14815. this._opaqueSortCompareFn = value;
  14816. if (value) {
  14817. this._renderOpaque = this.renderOpaqueSorted;
  14818. }
  14819. else {
  14820. this._renderOpaque = RenderingGroup.renderUnsorted;
  14821. }
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14827. /**
  14828. * Set the alpha test sort comparison function.
  14829. * If null the sub meshes will be render in the order they were created
  14830. */
  14831. set: function (value) {
  14832. this._alphaTestSortCompareFn = value;
  14833. if (value) {
  14834. this._renderAlphaTest = this.renderAlphaTestSorted;
  14835. }
  14836. else {
  14837. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14838. }
  14839. },
  14840. enumerable: true,
  14841. configurable: true
  14842. });
  14843. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14844. /**
  14845. * Set the transparent sort comparison function.
  14846. * If null the sub meshes will be render in the order they were created
  14847. */
  14848. set: function (value) {
  14849. if (value) {
  14850. this._transparentSortCompareFn = value;
  14851. }
  14852. else {
  14853. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14854. }
  14855. this._renderTransparent = this.renderTransparentSorted;
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. /**
  14861. * Render all the sub meshes contained in the group.
  14862. * @param customRenderFunction Used to override the default render behaviour of the group.
  14863. * @returns true if rendered some submeshes.
  14864. */
  14865. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14866. if (customRenderFunction) {
  14867. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14868. return;
  14869. }
  14870. var engine = this._scene.getEngine();
  14871. // Opaque
  14872. if (this._opaqueSubMeshes.length !== 0) {
  14873. this._renderOpaque(this._opaqueSubMeshes);
  14874. }
  14875. // Alpha test
  14876. if (this._alphaTestSubMeshes.length !== 0) {
  14877. engine.setAlphaTesting(true);
  14878. this._renderAlphaTest(this._alphaTestSubMeshes);
  14879. engine.setAlphaTesting(false);
  14880. }
  14881. var stencilState = engine.getStencilBuffer();
  14882. engine.setStencilBuffer(false);
  14883. // Sprites
  14884. if (renderSprites) {
  14885. this._renderSprites();
  14886. }
  14887. // Particles
  14888. if (renderParticles) {
  14889. this._renderParticles(activeMeshes);
  14890. }
  14891. if (this.onBeforeTransparentRendering) {
  14892. this.onBeforeTransparentRendering();
  14893. }
  14894. // Transparent
  14895. if (this._transparentSubMeshes.length !== 0) {
  14896. this._renderTransparent(this._transparentSubMeshes);
  14897. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14898. }
  14899. engine.setStencilBuffer(stencilState);
  14900. // Edges
  14901. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14902. this._edgesRenderers.data[edgesRendererIndex].render();
  14903. }
  14904. };
  14905. /**
  14906. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14907. * @param subMeshes The submeshes to render
  14908. */
  14909. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14910. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14911. };
  14912. /**
  14913. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14914. * @param subMeshes The submeshes to render
  14915. */
  14916. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14917. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14918. };
  14919. /**
  14920. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14921. * @param subMeshes The submeshes to render
  14922. */
  14923. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14924. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14925. };
  14926. /**
  14927. * Renders the submeshes in a specified order.
  14928. * @param subMeshes The submeshes to sort before render
  14929. * @param sortCompareFn The comparison function use to sort
  14930. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14931. * @param transparent Specifies to activate blending if true
  14932. */
  14933. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14934. var subIndex = 0;
  14935. var subMesh;
  14936. for (; subIndex < subMeshes.length; subIndex++) {
  14937. subMesh = subMeshes.data[subIndex];
  14938. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14939. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14940. }
  14941. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14942. sortedArray.sort(sortCompareFn);
  14943. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14944. subMesh = sortedArray[subIndex];
  14945. subMesh.render(transparent);
  14946. }
  14947. };
  14948. /**
  14949. * Renders the submeshes in the order they were dispatched (no sort applied).
  14950. * @param subMeshes The submeshes to render
  14951. */
  14952. RenderingGroup.renderUnsorted = function (subMeshes) {
  14953. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14954. var submesh = subMeshes.data[subIndex];
  14955. submesh.render(false);
  14956. }
  14957. };
  14958. /**
  14959. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14960. * are rendered back to front if in the same alpha index.
  14961. *
  14962. * @param a The first submesh
  14963. * @param b The second submesh
  14964. * @returns The result of the comparison
  14965. */
  14966. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14967. // Alpha index first
  14968. if (a._alphaIndex > b._alphaIndex) {
  14969. return 1;
  14970. }
  14971. if (a._alphaIndex < b._alphaIndex) {
  14972. return -1;
  14973. }
  14974. // Then distance to camera
  14975. return RenderingGroup.backToFrontSortCompare(a, b);
  14976. };
  14977. /**
  14978. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14979. * are rendered back to front.
  14980. *
  14981. * @param a The first submesh
  14982. * @param b The second submesh
  14983. * @returns The result of the comparison
  14984. */
  14985. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14986. // Then distance to camera
  14987. if (a._distanceToCamera < b._distanceToCamera) {
  14988. return 1;
  14989. }
  14990. if (a._distanceToCamera > b._distanceToCamera) {
  14991. return -1;
  14992. }
  14993. return 0;
  14994. };
  14995. /**
  14996. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14997. * are rendered front to back (prevent overdraw).
  14998. *
  14999. * @param a The first submesh
  15000. * @param b The second submesh
  15001. * @returns The result of the comparison
  15002. */
  15003. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15004. // Then distance to camera
  15005. if (a._distanceToCamera < b._distanceToCamera) {
  15006. return -1;
  15007. }
  15008. if (a._distanceToCamera > b._distanceToCamera) {
  15009. return 1;
  15010. }
  15011. return 0;
  15012. };
  15013. /**
  15014. * Resets the different lists of submeshes to prepare a new frame.
  15015. */
  15016. RenderingGroup.prototype.prepare = function () {
  15017. this._opaqueSubMeshes.reset();
  15018. this._transparentSubMeshes.reset();
  15019. this._alphaTestSubMeshes.reset();
  15020. this._particleSystems.reset();
  15021. this._spriteManagers.reset();
  15022. this._edgesRenderers.reset();
  15023. };
  15024. RenderingGroup.prototype.dispose = function () {
  15025. this._opaqueSubMeshes.dispose();
  15026. this._transparentSubMeshes.dispose();
  15027. this._alphaTestSubMeshes.dispose();
  15028. this._particleSystems.dispose();
  15029. this._spriteManagers.dispose();
  15030. this._edgesRenderers.dispose();
  15031. };
  15032. /**
  15033. * Inserts the submesh in its correct queue depending on its material.
  15034. * @param subMesh The submesh to dispatch
  15035. */
  15036. RenderingGroup.prototype.dispatch = function (subMesh) {
  15037. var material = subMesh.getMaterial();
  15038. var mesh = subMesh.getMesh();
  15039. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15040. this._transparentSubMeshes.push(subMesh);
  15041. }
  15042. else if (material.needAlphaTesting()) {
  15043. this._alphaTestSubMeshes.push(subMesh);
  15044. }
  15045. else {
  15046. this._opaqueSubMeshes.push(subMesh); // Opaque
  15047. }
  15048. if (mesh._edgesRenderer) {
  15049. this._edgesRenderers.push(mesh._edgesRenderer);
  15050. }
  15051. };
  15052. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15053. this._spriteManagers.push(spriteManager);
  15054. };
  15055. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15056. this._particleSystems.push(particleSystem);
  15057. };
  15058. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15059. if (this._particleSystems.length === 0) {
  15060. return;
  15061. }
  15062. // Particles
  15063. var activeCamera = this._scene.activeCamera;
  15064. this._scene._particlesDuration.beginMonitoring();
  15065. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15066. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15067. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15068. continue;
  15069. }
  15070. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15071. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15072. }
  15073. }
  15074. this._scene._particlesDuration.endMonitoring(false);
  15075. };
  15076. RenderingGroup.prototype._renderSprites = function () {
  15077. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15078. return;
  15079. }
  15080. // Sprites
  15081. var activeCamera = this._scene.activeCamera;
  15082. this._scene._spritesDuration.beginMonitoring();
  15083. for (var id = 0; id < this._spriteManagers.length; id++) {
  15084. var spriteManager = this._spriteManagers.data[id];
  15085. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15086. spriteManager.render();
  15087. }
  15088. }
  15089. this._scene._spritesDuration.endMonitoring(false);
  15090. };
  15091. return RenderingGroup;
  15092. }());
  15093. BABYLON.RenderingGroup = RenderingGroup;
  15094. })(BABYLON || (BABYLON = {}));
  15095. //# sourceMappingURL=babylon.renderingGroup.js.map
  15096. var BABYLON;
  15097. (function (BABYLON) {
  15098. var ClickInfo = (function () {
  15099. function ClickInfo() {
  15100. this._singleClick = false;
  15101. this._doubleClick = false;
  15102. this._hasSwiped = false;
  15103. this._ignore = false;
  15104. }
  15105. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15106. get: function () {
  15107. return this._singleClick;
  15108. },
  15109. set: function (b) {
  15110. this._singleClick = b;
  15111. },
  15112. enumerable: true,
  15113. configurable: true
  15114. });
  15115. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15116. get: function () {
  15117. return this._doubleClick;
  15118. },
  15119. set: function (b) {
  15120. this._doubleClick = b;
  15121. },
  15122. enumerable: true,
  15123. configurable: true
  15124. });
  15125. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15126. get: function () {
  15127. return this._hasSwiped;
  15128. },
  15129. set: function (b) {
  15130. this._hasSwiped = b;
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15136. get: function () {
  15137. return this._ignore;
  15138. },
  15139. set: function (b) {
  15140. this._ignore = b;
  15141. },
  15142. enumerable: true,
  15143. configurable: true
  15144. });
  15145. return ClickInfo;
  15146. }());
  15147. var PointerEventTypes = (function () {
  15148. function PointerEventTypes() {
  15149. }
  15150. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15151. get: function () {
  15152. return PointerEventTypes._POINTERDOWN;
  15153. },
  15154. enumerable: true,
  15155. configurable: true
  15156. });
  15157. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15158. get: function () {
  15159. return PointerEventTypes._POINTERUP;
  15160. },
  15161. enumerable: true,
  15162. configurable: true
  15163. });
  15164. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15165. get: function () {
  15166. return PointerEventTypes._POINTERMOVE;
  15167. },
  15168. enumerable: true,
  15169. configurable: true
  15170. });
  15171. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15172. get: function () {
  15173. return PointerEventTypes._POINTERWHEEL;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15179. get: function () {
  15180. return PointerEventTypes._POINTERPICK;
  15181. },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15186. get: function () {
  15187. return PointerEventTypes._POINTERTAP;
  15188. },
  15189. enumerable: true,
  15190. configurable: true
  15191. });
  15192. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15193. get: function () {
  15194. return PointerEventTypes._POINTERDOUBLETAP;
  15195. },
  15196. enumerable: true,
  15197. configurable: true
  15198. });
  15199. return PointerEventTypes;
  15200. }());
  15201. PointerEventTypes._POINTERDOWN = 0x01;
  15202. PointerEventTypes._POINTERUP = 0x02;
  15203. PointerEventTypes._POINTERMOVE = 0x04;
  15204. PointerEventTypes._POINTERWHEEL = 0x08;
  15205. PointerEventTypes._POINTERPICK = 0x10;
  15206. PointerEventTypes._POINTERTAP = 0x20;
  15207. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15208. BABYLON.PointerEventTypes = PointerEventTypes;
  15209. var PointerInfoBase = (function () {
  15210. function PointerInfoBase(type, event) {
  15211. this.type = type;
  15212. this.event = event;
  15213. }
  15214. return PointerInfoBase;
  15215. }());
  15216. BABYLON.PointerInfoBase = PointerInfoBase;
  15217. /**
  15218. * This class is used to store pointer related info for the onPrePointerObservable event.
  15219. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15220. */
  15221. var PointerInfoPre = (function (_super) {
  15222. __extends(PointerInfoPre, _super);
  15223. function PointerInfoPre(type, event, localX, localY) {
  15224. var _this = _super.call(this, type, event) || this;
  15225. _this.skipOnPointerObservable = false;
  15226. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15227. return _this;
  15228. }
  15229. return PointerInfoPre;
  15230. }(PointerInfoBase));
  15231. BABYLON.PointerInfoPre = PointerInfoPre;
  15232. /**
  15233. * This type contains all the data related to a pointer event in Babylon.js.
  15234. * 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.
  15235. */
  15236. var PointerInfo = (function (_super) {
  15237. __extends(PointerInfo, _super);
  15238. function PointerInfo(type, event, pickInfo) {
  15239. var _this = _super.call(this, type, event) || this;
  15240. _this.pickInfo = pickInfo;
  15241. return _this;
  15242. }
  15243. return PointerInfo;
  15244. }(PointerInfoBase));
  15245. BABYLON.PointerInfo = PointerInfo;
  15246. /**
  15247. * This class is used by the onRenderingGroupObservable
  15248. */
  15249. var RenderingGroupInfo = (function () {
  15250. function RenderingGroupInfo() {
  15251. }
  15252. return RenderingGroupInfo;
  15253. }());
  15254. /**
  15255. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15256. * This stage will be fired no matter what
  15257. */
  15258. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15259. /**
  15260. * Called before opaque object are rendered.
  15261. * This stage will be fired only if there's 3D Opaque content to render
  15262. */
  15263. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15264. /**
  15265. * Called after the opaque objects are rendered and before the transparent ones
  15266. * This stage will be fired only if there's 3D transparent content to render
  15267. */
  15268. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15269. /**
  15270. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15271. * This stage will be fired no matter what
  15272. */
  15273. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15274. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15275. /**
  15276. * Represents a scene to be rendered by the engine.
  15277. * @see http://doc.babylonjs.com/page.php?p=21911
  15278. */
  15279. var Scene = (function () {
  15280. /**
  15281. * @constructor
  15282. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15283. */
  15284. function Scene(engine) {
  15285. // Members
  15286. this.autoClear = true;
  15287. this.autoClearDepthAndStencil = true;
  15288. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15289. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15290. this.forceWireframe = false;
  15291. this._forcePointsCloud = false;
  15292. this.forceShowBoundingBoxes = false;
  15293. this.animationsEnabled = true;
  15294. this.constantlyUpdateMeshUnderPointer = false;
  15295. this.hoverCursor = "pointer";
  15296. // Metadata
  15297. this.metadata = null;
  15298. // Events
  15299. /**
  15300. * An event triggered when the scene is disposed.
  15301. * @type {BABYLON.Observable}
  15302. */
  15303. this.onDisposeObservable = new BABYLON.Observable();
  15304. /**
  15305. * An event triggered before rendering the scene
  15306. * @type {BABYLON.Observable}
  15307. */
  15308. this.onBeforeRenderObservable = new BABYLON.Observable();
  15309. /**
  15310. * An event triggered after rendering the scene
  15311. * @type {BABYLON.Observable}
  15312. */
  15313. this.onAfterRenderObservable = new BABYLON.Observable();
  15314. /**
  15315. * An event triggered when the scene is ready
  15316. * @type {BABYLON.Observable}
  15317. */
  15318. this.onReadyObservable = new BABYLON.Observable();
  15319. /**
  15320. * An event triggered before rendering a camera
  15321. * @type {BABYLON.Observable}
  15322. */
  15323. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15324. /**
  15325. * An event triggered after rendering a camera
  15326. * @type {BABYLON.Observable}
  15327. */
  15328. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15329. /**
  15330. * An event triggered when a camera is created
  15331. * @type {BABYLON.Observable}
  15332. */
  15333. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15334. /**
  15335. * An event triggered when a camera is removed
  15336. * @type {BABYLON.Observable}
  15337. */
  15338. this.onCameraRemovedObservable = new BABYLON.Observable();
  15339. /**
  15340. * An event triggered when a light is created
  15341. * @type {BABYLON.Observable}
  15342. */
  15343. this.onNewLightAddedObservable = new BABYLON.Observable();
  15344. /**
  15345. * An event triggered when a light is removed
  15346. * @type {BABYLON.Observable}
  15347. */
  15348. this.onLightRemovedObservable = new BABYLON.Observable();
  15349. /**
  15350. * An event triggered when a geometry is created
  15351. * @type {BABYLON.Observable}
  15352. */
  15353. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15354. /**
  15355. * An event triggered when a geometry is removed
  15356. * @type {BABYLON.Observable}
  15357. */
  15358. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15359. /**
  15360. * An event triggered when a mesh is created
  15361. * @type {BABYLON.Observable}
  15362. */
  15363. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15364. /**
  15365. * An event triggered when a mesh is removed
  15366. * @type {BABYLON.Observable}
  15367. */
  15368. this.onMeshRemovedObservable = new BABYLON.Observable();
  15369. /**
  15370. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15371. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15372. * 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)
  15373. */
  15374. this.onRenderingGroupObservable = new BABYLON.Observable();
  15375. // Animations
  15376. this.animations = [];
  15377. /**
  15378. * 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).
  15379. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15380. */
  15381. this.onPrePointerObservable = new BABYLON.Observable();
  15382. /**
  15383. * Observable event triggered each time an input event is received from the rendering canvas
  15384. */
  15385. this.onPointerObservable = new BABYLON.Observable();
  15386. this._meshPickProceed = false;
  15387. this._previousHasSwiped = false;
  15388. this._currentPickResult = null;
  15389. this._previousPickResult = null;
  15390. this._isButtonPressed = false;
  15391. this._doubleClickOccured = false;
  15392. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  15393. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15394. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15395. this._startingPointerTime = 0;
  15396. this._previousStartingPointerTime = 0;
  15397. // Coordinate system
  15398. /**
  15399. * use right-handed coordinate system on this scene.
  15400. * @type {boolean}
  15401. */
  15402. this._useRightHandedSystem = false;
  15403. // Fog
  15404. /**
  15405. * is fog enabled on this scene.
  15406. * @type {boolean}
  15407. */
  15408. this._fogEnabled = true;
  15409. this._fogMode = Scene.FOGMODE_NONE;
  15410. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15411. this.fogDensity = 0.1;
  15412. this.fogStart = 0;
  15413. this.fogEnd = 1000.0;
  15414. // Lights
  15415. /**
  15416. * is shadow enabled on this scene.
  15417. * @type {boolean}
  15418. */
  15419. this._shadowsEnabled = true;
  15420. /**
  15421. * is light enabled on this scene.
  15422. * @type {boolean}
  15423. */
  15424. this._lightsEnabled = true;
  15425. /**
  15426. * All of the lights added to this scene.
  15427. * @see BABYLON.Light
  15428. * @type {BABYLON.Light[]}
  15429. */
  15430. this.lights = new Array();
  15431. // Cameras
  15432. /**
  15433. * All of the cameras added to this scene.
  15434. * @see BABYLON.Camera
  15435. * @type {BABYLON.Camera[]}
  15436. */
  15437. this.cameras = new Array();
  15438. this.activeCameras = new Array();
  15439. // Meshes
  15440. /**
  15441. * All of the (abstract) meshes added to this scene.
  15442. * @see BABYLON.AbstractMesh
  15443. * @type {BABYLON.AbstractMesh[]}
  15444. */
  15445. this.meshes = new Array();
  15446. // Geometries
  15447. this._geometries = new Array();
  15448. this.materials = new Array();
  15449. this.multiMaterials = new Array();
  15450. // Textures
  15451. this._texturesEnabled = true;
  15452. this.textures = new Array();
  15453. // Particles
  15454. this.particlesEnabled = true;
  15455. this.particleSystems = new Array();
  15456. // Sprites
  15457. this.spritesEnabled = true;
  15458. this.spriteManagers = new Array();
  15459. // Layers
  15460. this.layers = new Array();
  15461. this.highlightLayers = new Array();
  15462. // Skeletons
  15463. this._skeletonsEnabled = true;
  15464. this.skeletons = new Array();
  15465. // Morph targets
  15466. this.morphTargetManagers = new Array();
  15467. // Lens flares
  15468. this.lensFlaresEnabled = true;
  15469. this.lensFlareSystems = new Array();
  15470. // Collisions
  15471. this.collisionsEnabled = true;
  15472. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15473. // Postprocesses
  15474. this.postProcessesEnabled = true;
  15475. // Customs render targets
  15476. this.renderTargetsEnabled = true;
  15477. this.dumpNextRenderTargets = false;
  15478. this.customRenderTargets = new Array();
  15479. // Imported meshes
  15480. this.importedMeshesFiles = new Array();
  15481. // Probes
  15482. this.probesEnabled = true;
  15483. this.reflectionProbes = new Array();
  15484. this._actionManagers = new Array();
  15485. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15486. // Procedural textures
  15487. this.proceduralTexturesEnabled = true;
  15488. this._proceduralTextures = new Array();
  15489. this.soundTracks = new Array();
  15490. this._audioEnabled = true;
  15491. this._headphone = false;
  15492. // Performance counters
  15493. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15494. this._totalLightsCounter = new BABYLON.PerfCounter();
  15495. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15496. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15497. this._totalVertices = new BABYLON.PerfCounter();
  15498. this._activeIndices = new BABYLON.PerfCounter();
  15499. this._activeParticles = new BABYLON.PerfCounter();
  15500. this._lastFrameDuration = new BABYLON.PerfCounter();
  15501. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15502. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15503. this._particlesDuration = new BABYLON.PerfCounter();
  15504. this._renderDuration = new BABYLON.PerfCounter();
  15505. this._spritesDuration = new BABYLON.PerfCounter();
  15506. this._activeBones = new BABYLON.PerfCounter();
  15507. this._animationTime = 0;
  15508. this.animationTimeScale = 1;
  15509. this._renderId = 0;
  15510. this._executeWhenReadyTimeoutId = -1;
  15511. this._intermediateRendering = false;
  15512. this._viewUpdateFlag = -1;
  15513. this._projectionUpdateFlag = -1;
  15514. this._toBeDisposed = new BABYLON.SmartArray(256);
  15515. this._pendingData = []; //ANY
  15516. this._activeMeshes = new BABYLON.SmartArray(256);
  15517. this._processedMaterials = new BABYLON.SmartArray(256);
  15518. this._renderTargets = new BABYLON.SmartArray(256);
  15519. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15520. this._activeSkeletons = new BABYLON.SmartArray(32);
  15521. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15522. this._activeAnimatables = new Array();
  15523. this._transformMatrix = BABYLON.Matrix.Zero();
  15524. this.requireLightSorting = false;
  15525. this._uniqueIdCounter = 0;
  15526. this.offscreenRenderTarget = null;
  15527. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15528. this._engine.scenes.push(this);
  15529. this._uid = null;
  15530. this._renderingManager = new BABYLON.RenderingManager(this);
  15531. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15532. if (BABYLON.OutlineRenderer) {
  15533. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15534. }
  15535. this.attachControl();
  15536. if (BABYLON.SoundTrack) {
  15537. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15538. }
  15539. //simplification queue
  15540. if (BABYLON.SimplificationQueue) {
  15541. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15542. }
  15543. //collision coordinator initialization. For now legacy per default.
  15544. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15545. // Uniform Buffer
  15546. this._createUbo();
  15547. }
  15548. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15549. get: function () {
  15550. return Scene._FOGMODE_NONE;
  15551. },
  15552. enumerable: true,
  15553. configurable: true
  15554. });
  15555. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15556. get: function () {
  15557. return Scene._FOGMODE_EXP;
  15558. },
  15559. enumerable: true,
  15560. configurable: true
  15561. });
  15562. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15563. get: function () {
  15564. return Scene._FOGMODE_EXP2;
  15565. },
  15566. enumerable: true,
  15567. configurable: true
  15568. });
  15569. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15570. get: function () {
  15571. return Scene._FOGMODE_LINEAR;
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15577. /**
  15578. * Texture used in all pbr material as the reflection texture.
  15579. * As in the majority of the scene they are the same (exception for multi room and so on),
  15580. * this is easier to reference from here than from all the materials.
  15581. */
  15582. get: function () {
  15583. return this._environmentTexture;
  15584. },
  15585. /**
  15586. * Texture used in all pbr material as the reflection texture.
  15587. * As in the majority of the scene they are the same (exception for multi room and so on),
  15588. * this is easier to set here than in all the materials.
  15589. */
  15590. set: function (value) {
  15591. this._environmentTexture = value;
  15592. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15598. get: function () {
  15599. return this._forcePointsCloud;
  15600. },
  15601. set: function (value) {
  15602. if (this._forcePointsCloud === value) {
  15603. return;
  15604. }
  15605. this._forcePointsCloud = value;
  15606. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15607. },
  15608. enumerable: true,
  15609. configurable: true
  15610. });
  15611. Object.defineProperty(Scene.prototype, "onDispose", {
  15612. set: function (callback) {
  15613. if (this._onDisposeObserver) {
  15614. this.onDisposeObservable.remove(this._onDisposeObserver);
  15615. }
  15616. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15617. },
  15618. enumerable: true,
  15619. configurable: true
  15620. });
  15621. Object.defineProperty(Scene.prototype, "beforeRender", {
  15622. set: function (callback) {
  15623. if (this._onBeforeRenderObserver) {
  15624. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15625. }
  15626. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15627. },
  15628. enumerable: true,
  15629. configurable: true
  15630. });
  15631. Object.defineProperty(Scene.prototype, "afterRender", {
  15632. set: function (callback) {
  15633. if (this._onAfterRenderObserver) {
  15634. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15635. }
  15636. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15637. },
  15638. enumerable: true,
  15639. configurable: true
  15640. });
  15641. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15642. set: function (callback) {
  15643. if (this._onBeforeCameraRenderObserver) {
  15644. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15645. }
  15646. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15647. },
  15648. enumerable: true,
  15649. configurable: true
  15650. });
  15651. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15652. set: function (callback) {
  15653. if (this._onAfterCameraRenderObserver) {
  15654. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15655. }
  15656. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15657. },
  15658. enumerable: true,
  15659. configurable: true
  15660. });
  15661. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15662. get: function () {
  15663. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15664. },
  15665. enumerable: true,
  15666. configurable: true
  15667. });
  15668. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15669. get: function () {
  15670. return this._useRightHandedSystem;
  15671. },
  15672. set: function (value) {
  15673. if (this._useRightHandedSystem === value) {
  15674. return;
  15675. }
  15676. this._useRightHandedSystem = value;
  15677. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15678. },
  15679. enumerable: true,
  15680. configurable: true
  15681. });
  15682. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15683. get: function () {
  15684. return this._fogEnabled;
  15685. },
  15686. set: function (value) {
  15687. if (this._fogEnabled === value) {
  15688. return;
  15689. }
  15690. this._fogEnabled = value;
  15691. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Scene.prototype, "fogMode", {
  15697. get: function () {
  15698. return this._fogMode;
  15699. },
  15700. set: function (value) {
  15701. if (this._fogMode === value) {
  15702. return;
  15703. }
  15704. this._fogMode = value;
  15705. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15706. },
  15707. enumerable: true,
  15708. configurable: true
  15709. });
  15710. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15711. get: function () {
  15712. return this._shadowsEnabled;
  15713. },
  15714. set: function (value) {
  15715. if (this._shadowsEnabled === value) {
  15716. return;
  15717. }
  15718. this._shadowsEnabled = value;
  15719. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15720. },
  15721. enumerable: true,
  15722. configurable: true
  15723. });
  15724. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15725. get: function () {
  15726. return this._lightsEnabled;
  15727. },
  15728. set: function (value) {
  15729. if (this._lightsEnabled === value) {
  15730. return;
  15731. }
  15732. this._lightsEnabled = value;
  15733. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15734. },
  15735. enumerable: true,
  15736. configurable: true
  15737. });
  15738. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15739. get: function () {
  15740. if (!this._defaultMaterial) {
  15741. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15742. }
  15743. return this._defaultMaterial;
  15744. },
  15745. set: function (value) {
  15746. this._defaultMaterial = value;
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15752. get: function () {
  15753. return this._texturesEnabled;
  15754. },
  15755. set: function (value) {
  15756. if (this._texturesEnabled === value) {
  15757. return;
  15758. }
  15759. this._texturesEnabled = value;
  15760. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15766. get: function () {
  15767. return this._skeletonsEnabled;
  15768. },
  15769. set: function (value) {
  15770. if (this._skeletonsEnabled === value) {
  15771. return;
  15772. }
  15773. this._skeletonsEnabled = value;
  15774. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15775. },
  15776. enumerable: true,
  15777. configurable: true
  15778. });
  15779. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15780. get: function () {
  15781. if (!this._postProcessRenderPipelineManager) {
  15782. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15783. }
  15784. return this._postProcessRenderPipelineManager;
  15785. },
  15786. enumerable: true,
  15787. configurable: true
  15788. });
  15789. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15790. get: function () {
  15791. return this._frustumPlanes;
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. Object.defineProperty(Scene.prototype, "debugLayer", {
  15797. // Properties
  15798. get: function () {
  15799. if (!this._debugLayer) {
  15800. this._debugLayer = new BABYLON.DebugLayer(this);
  15801. }
  15802. return this._debugLayer;
  15803. },
  15804. enumerable: true,
  15805. configurable: true
  15806. });
  15807. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15808. get: function () {
  15809. return this._workerCollisions;
  15810. },
  15811. set: function (enabled) {
  15812. if (!BABYLON.CollisionCoordinatorLegacy) {
  15813. return;
  15814. }
  15815. enabled = (enabled && !!Worker);
  15816. this._workerCollisions = enabled;
  15817. if (this.collisionCoordinator) {
  15818. this.collisionCoordinator.destroy();
  15819. }
  15820. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15821. this.collisionCoordinator.init(this);
  15822. },
  15823. enumerable: true,
  15824. configurable: true
  15825. });
  15826. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15827. get: function () {
  15828. return this._selectionOctree;
  15829. },
  15830. enumerable: true,
  15831. configurable: true
  15832. });
  15833. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15834. /**
  15835. * The mesh that is currently under the pointer.
  15836. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15837. */
  15838. get: function () {
  15839. return this._pointerOverMesh;
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. Object.defineProperty(Scene.prototype, "pointerX", {
  15845. /**
  15846. * Current on-screen X position of the pointer
  15847. * @return {number} X position of the pointer
  15848. */
  15849. get: function () {
  15850. return this._pointerX;
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. Object.defineProperty(Scene.prototype, "pointerY", {
  15856. /**
  15857. * Current on-screen Y position of the pointer
  15858. * @return {number} Y position of the pointer
  15859. */
  15860. get: function () {
  15861. return this._pointerY;
  15862. },
  15863. enumerable: true,
  15864. configurable: true
  15865. });
  15866. Scene.prototype.getCachedMaterial = function () {
  15867. return this._cachedMaterial;
  15868. };
  15869. Scene.prototype.getCachedEffect = function () {
  15870. return this._cachedEffect;
  15871. };
  15872. Scene.prototype.getCachedVisibility = function () {
  15873. return this._cachedVisibility;
  15874. };
  15875. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15876. if (visibility === void 0) { visibility = 0; }
  15877. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15878. };
  15879. Scene.prototype.getBoundingBoxRenderer = function () {
  15880. if (!this._boundingBoxRenderer) {
  15881. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15882. }
  15883. return this._boundingBoxRenderer;
  15884. };
  15885. Scene.prototype.getOutlineRenderer = function () {
  15886. return this._outlineRenderer;
  15887. };
  15888. Scene.prototype.getEngine = function () {
  15889. return this._engine;
  15890. };
  15891. Scene.prototype.getTotalVertices = function () {
  15892. return this._totalVertices.current;
  15893. };
  15894. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15895. get: function () {
  15896. return this._totalVertices;
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. Scene.prototype.getActiveIndices = function () {
  15902. return this._activeIndices.current;
  15903. };
  15904. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15905. get: function () {
  15906. return this._activeIndices;
  15907. },
  15908. enumerable: true,
  15909. configurable: true
  15910. });
  15911. Scene.prototype.getActiveParticles = function () {
  15912. return this._activeParticles.current;
  15913. };
  15914. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15915. get: function () {
  15916. return this._activeParticles;
  15917. },
  15918. enumerable: true,
  15919. configurable: true
  15920. });
  15921. Scene.prototype.getActiveBones = function () {
  15922. return this._activeBones.current;
  15923. };
  15924. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15925. get: function () {
  15926. return this._activeBones;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. // Stats
  15932. Scene.prototype.getLastFrameDuration = function () {
  15933. return this._lastFrameDuration.current;
  15934. };
  15935. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15936. get: function () {
  15937. return this._lastFrameDuration;
  15938. },
  15939. enumerable: true,
  15940. configurable: true
  15941. });
  15942. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15943. return this._evaluateActiveMeshesDuration.current;
  15944. };
  15945. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15946. get: function () {
  15947. return this._evaluateActiveMeshesDuration;
  15948. },
  15949. enumerable: true,
  15950. configurable: true
  15951. });
  15952. Scene.prototype.getActiveMeshes = function () {
  15953. return this._activeMeshes;
  15954. };
  15955. Scene.prototype.getRenderTargetsDuration = function () {
  15956. return this._renderTargetsDuration.current;
  15957. };
  15958. Scene.prototype.getRenderDuration = function () {
  15959. return this._renderDuration.current;
  15960. };
  15961. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15962. get: function () {
  15963. return this._renderDuration;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Scene.prototype.getParticlesDuration = function () {
  15969. return this._particlesDuration.current;
  15970. };
  15971. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15972. get: function () {
  15973. return this._particlesDuration;
  15974. },
  15975. enumerable: true,
  15976. configurable: true
  15977. });
  15978. Scene.prototype.getSpritesDuration = function () {
  15979. return this._spritesDuration.current;
  15980. };
  15981. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15982. get: function () {
  15983. return this._spritesDuration;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Scene.prototype.getAnimationRatio = function () {
  15989. return this._animationRatio;
  15990. };
  15991. Scene.prototype.getRenderId = function () {
  15992. return this._renderId;
  15993. };
  15994. Scene.prototype.incrementRenderId = function () {
  15995. this._renderId++;
  15996. };
  15997. Scene.prototype._updatePointerPosition = function (evt) {
  15998. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15999. this._pointerX = evt.clientX - canvasRect.left;
  16000. this._pointerY = evt.clientY - canvasRect.top;
  16001. this._unTranslatedPointerX = this._pointerX;
  16002. this._unTranslatedPointerY = this._pointerY;
  16003. if (this.cameraToUseForPointers) {
  16004. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16005. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16006. }
  16007. };
  16008. Scene.prototype._createUbo = function () {
  16009. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16010. this._sceneUbo.addUniform("viewProjection", 16);
  16011. this._sceneUbo.addUniform("view", 16);
  16012. };
  16013. // Pointers handling
  16014. /**
  16015. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16016. * @param attachUp defines if you want to attach events to pointerup
  16017. * @param attachDown defines if you want to attach events to pointerdown
  16018. * @param attachMove defines if you want to attach events to pointermove
  16019. */
  16020. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16021. var _this = this;
  16022. if (attachUp === void 0) { attachUp = true; }
  16023. if (attachDown === void 0) { attachDown = true; }
  16024. if (attachMove === void 0) { attachMove = true; }
  16025. this._initActionManager = function (act, clickInfo) {
  16026. if (!_this._meshPickProceed) {
  16027. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16028. _this._currentPickResult = pickResult;
  16029. if (pickResult) {
  16030. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16031. }
  16032. _this._meshPickProceed = true;
  16033. }
  16034. return act;
  16035. };
  16036. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16037. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16038. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16039. btn !== _this._previousButtonPressed) {
  16040. _this._doubleClickOccured = false;
  16041. clickInfo.singleClick = true;
  16042. clickInfo.ignore = false;
  16043. cb(clickInfo, _this._currentPickResult);
  16044. }
  16045. };
  16046. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16047. var clickInfo = new ClickInfo();
  16048. _this._currentPickResult = null;
  16049. var act;
  16050. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16051. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16052. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16053. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16054. act = _this._initActionManager(act, clickInfo);
  16055. if (act)
  16056. checkPicking = act.hasPickTriggers;
  16057. }
  16058. if (checkPicking) {
  16059. var btn = evt.button;
  16060. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16061. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16062. if (!clickInfo.hasSwiped) {
  16063. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16064. if (!checkSingleClickImmediately) {
  16065. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16066. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16067. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16068. act = _this._initActionManager(act, clickInfo);
  16069. if (act)
  16070. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16071. }
  16072. }
  16073. if (checkSingleClickImmediately) {
  16074. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16075. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16076. btn !== _this._previousButtonPressed) {
  16077. clickInfo.singleClick = true;
  16078. cb(clickInfo, _this._currentPickResult);
  16079. }
  16080. }
  16081. else {
  16082. // wait that no double click has been raised during the double click delay
  16083. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16084. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16085. }
  16086. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16087. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16088. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16089. act = _this._initActionManager(act, clickInfo);
  16090. if (act)
  16091. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16092. }
  16093. if (checkDoubleClick) {
  16094. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16095. if (btn === _this._previousButtonPressed &&
  16096. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16097. !_this._doubleClickOccured) {
  16098. // pointer has not moved for 2 clicks, it's a double click
  16099. if (!clickInfo.hasSwiped &&
  16100. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16101. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16102. _this._previousStartingPointerTime = 0;
  16103. _this._doubleClickOccured = true;
  16104. clickInfo.doubleClick = true;
  16105. clickInfo.ignore = false;
  16106. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16107. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16108. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16109. cb(clickInfo, _this._currentPickResult);
  16110. }
  16111. else {
  16112. _this._doubleClickOccured = false;
  16113. _this._previousStartingPointerTime = _this._startingPointerTime;
  16114. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16115. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16116. _this._previousButtonPressed = btn;
  16117. _this._previousHasSwiped = clickInfo.hasSwiped;
  16118. if (Scene.ExclusiveDoubleClickMode) {
  16119. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16120. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16121. }
  16122. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16123. cb(clickInfo, _this._previousPickResult);
  16124. }
  16125. else {
  16126. cb(clickInfo, _this._currentPickResult);
  16127. }
  16128. }
  16129. }
  16130. else {
  16131. _this._doubleClickOccured = false;
  16132. _this._previousStartingPointerTime = _this._startingPointerTime;
  16133. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16134. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16135. _this._previousButtonPressed = btn;
  16136. _this._previousHasSwiped = clickInfo.hasSwiped;
  16137. }
  16138. }
  16139. }
  16140. }
  16141. clickInfo.ignore = true;
  16142. cb(clickInfo, _this._currentPickResult);
  16143. };
  16144. var spritePredicate = function (sprite) {
  16145. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16146. };
  16147. this._onPointerMove = function (evt) {
  16148. _this._updatePointerPosition(evt);
  16149. // PreObservable support
  16150. if (_this.onPrePointerObservable.hasObservers()) {
  16151. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16152. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16153. _this.onPrePointerObservable.notifyObservers(pi, type);
  16154. if (pi.skipOnPointerObservable) {
  16155. return;
  16156. }
  16157. }
  16158. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16159. return;
  16160. }
  16161. var canvas = _this._engine.getRenderingCanvas();
  16162. if (!_this.pointerMovePredicate) {
  16163. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16164. }
  16165. // Meshes
  16166. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16167. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16168. _this.setPointerOverSprite(null);
  16169. _this.setPointerOverMesh(pickResult.pickedMesh);
  16170. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16171. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16172. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16173. }
  16174. else {
  16175. canvas.style.cursor = _this.hoverCursor;
  16176. }
  16177. }
  16178. else {
  16179. canvas.style.cursor = "";
  16180. }
  16181. }
  16182. else {
  16183. _this.setPointerOverMesh(null);
  16184. // Sprites
  16185. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16186. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16187. _this.setPointerOverSprite(pickResult.pickedSprite);
  16188. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16189. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16190. }
  16191. else {
  16192. canvas.style.cursor = _this.hoverCursor;
  16193. }
  16194. }
  16195. else {
  16196. _this.setPointerOverSprite(null);
  16197. // Restore pointer
  16198. canvas.style.cursor = "";
  16199. }
  16200. }
  16201. if (_this.onPointerMove) {
  16202. _this.onPointerMove(evt, pickResult);
  16203. }
  16204. if (_this.onPointerObservable.hasObservers()) {
  16205. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16206. var pi = new PointerInfo(type, evt, pickResult);
  16207. _this.onPointerObservable.notifyObservers(pi, type);
  16208. }
  16209. };
  16210. this._onPointerDown = function (evt) {
  16211. _this._isButtonPressed = true;
  16212. _this._pickedDownMesh = null;
  16213. _this._meshPickProceed = false;
  16214. _this._updatePointerPosition(evt);
  16215. // PreObservable support
  16216. if (_this.onPrePointerObservable.hasObservers()) {
  16217. var type = PointerEventTypes.POINTERDOWN;
  16218. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16219. _this.onPrePointerObservable.notifyObservers(pi, type);
  16220. if (pi.skipOnPointerObservable) {
  16221. return;
  16222. }
  16223. }
  16224. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16225. return;
  16226. }
  16227. _this._startingPointerPosition.x = _this._pointerX;
  16228. _this._startingPointerPosition.y = _this._pointerY;
  16229. _this._startingPointerTime = new Date().getTime();
  16230. if (!_this.pointerDownPredicate) {
  16231. _this.pointerDownPredicate = function (mesh) {
  16232. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16233. };
  16234. }
  16235. // Meshes
  16236. _this._pickedDownMesh = null;
  16237. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16238. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16239. _this._pickedDownMesh = pickResult.pickedMesh;
  16240. var actionManager = pickResult.pickedMesh.actionManager;
  16241. if (actionManager) {
  16242. if (actionManager.hasPickTriggers) {
  16243. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16244. switch (evt.button) {
  16245. case 0:
  16246. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16247. break;
  16248. case 1:
  16249. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16250. break;
  16251. case 2:
  16252. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16253. break;
  16254. }
  16255. }
  16256. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16257. window.setTimeout((function () {
  16258. var _this = this;
  16259. 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);
  16260. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16261. if (this._isButtonPressed &&
  16262. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16263. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16264. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16265. this._startingPointerTime = 0;
  16266. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16267. }
  16268. }
  16269. }).bind(_this), Scene.LongPressDelay);
  16270. }
  16271. }
  16272. }
  16273. if (_this.onPointerDown) {
  16274. _this.onPointerDown(evt, pickResult);
  16275. }
  16276. if (_this.onPointerObservable.hasObservers()) {
  16277. var type = PointerEventTypes.POINTERDOWN;
  16278. var pi = new PointerInfo(type, evt, pickResult);
  16279. _this.onPointerObservable.notifyObservers(pi, type);
  16280. }
  16281. // Sprites
  16282. _this._pickedDownSprite = null;
  16283. if (_this.spriteManagers.length > 0) {
  16284. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16285. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16286. if (pickResult.pickedSprite.actionManager) {
  16287. _this._pickedDownSprite = pickResult.pickedSprite;
  16288. switch (evt.button) {
  16289. case 0:
  16290. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16291. break;
  16292. case 1:
  16293. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16294. break;
  16295. case 2:
  16296. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16297. break;
  16298. }
  16299. if (pickResult.pickedSprite.actionManager) {
  16300. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16301. }
  16302. }
  16303. }
  16304. }
  16305. };
  16306. this._onPointerUp = function (evt) {
  16307. _this._isButtonPressed = false;
  16308. _this._pickedUpMesh = null;
  16309. _this._meshPickProceed = false;
  16310. _this._updatePointerPosition(evt);
  16311. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16312. // PreObservable support
  16313. if (this.onPrePointerObservable.hasObservers()) {
  16314. if (!clickInfo.ignore) {
  16315. if (!clickInfo.hasSwiped) {
  16316. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16317. var type = PointerEventTypes.POINTERTAP;
  16318. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16319. this.onPrePointerObservable.notifyObservers(pi, type);
  16320. if (pi.skipOnPointerObservable) {
  16321. return;
  16322. }
  16323. }
  16324. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16325. var type = PointerEventTypes.POINTERDOUBLETAP;
  16326. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16327. this.onPrePointerObservable.notifyObservers(pi, type);
  16328. if (pi.skipOnPointerObservable) {
  16329. return;
  16330. }
  16331. }
  16332. }
  16333. }
  16334. else {
  16335. var type = PointerEventTypes.POINTERUP;
  16336. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16337. this.onPrePointerObservable.notifyObservers(pi, type);
  16338. if (pi.skipOnPointerObservable) {
  16339. return;
  16340. }
  16341. }
  16342. }
  16343. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16344. return;
  16345. }
  16346. if (!this.pointerUpPredicate) {
  16347. this.pointerUpPredicate = function (mesh) {
  16348. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16349. };
  16350. }
  16351. // Meshes
  16352. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16353. this._initActionManager(null, clickInfo);
  16354. }
  16355. if (!pickResult) {
  16356. pickResult = this._currentPickResult;
  16357. }
  16358. if (pickResult && pickResult && pickResult.pickedMesh) {
  16359. this._pickedUpMesh = pickResult.pickedMesh;
  16360. if (this._pickedDownMesh === this._pickedUpMesh) {
  16361. if (this.onPointerPick) {
  16362. this.onPointerPick(evt, pickResult);
  16363. }
  16364. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16365. var type = PointerEventTypes.POINTERPICK;
  16366. var pi = new PointerInfo(type, evt, pickResult);
  16367. this.onPointerObservable.notifyObservers(pi, type);
  16368. }
  16369. }
  16370. if (pickResult.pickedMesh.actionManager) {
  16371. if (clickInfo.ignore) {
  16372. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16373. }
  16374. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16375. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16376. }
  16377. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16379. }
  16380. }
  16381. }
  16382. if (this._pickedDownMesh &&
  16383. this._pickedDownMesh.actionManager &&
  16384. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16385. this._pickedDownMesh !== this._pickedUpMesh) {
  16386. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16387. }
  16388. if (this.onPointerUp) {
  16389. this.onPointerUp(evt, pickResult);
  16390. }
  16391. if (this.onPointerObservable.hasObservers()) {
  16392. if (!clickInfo.ignore) {
  16393. if (!clickInfo.hasSwiped) {
  16394. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16395. var type = PointerEventTypes.POINTERTAP;
  16396. var pi = new PointerInfo(type, evt, pickResult);
  16397. this.onPointerObservable.notifyObservers(pi, type);
  16398. }
  16399. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16400. var type = PointerEventTypes.POINTERDOUBLETAP;
  16401. var pi = new PointerInfo(type, evt, pickResult);
  16402. this.onPointerObservable.notifyObservers(pi, type);
  16403. }
  16404. }
  16405. }
  16406. else {
  16407. var type = PointerEventTypes.POINTERUP;
  16408. var pi = new PointerInfo(type, evt, pickResult);
  16409. this.onPointerObservable.notifyObservers(pi, type);
  16410. }
  16411. }
  16412. // Sprites
  16413. if (this.spriteManagers.length > 0) {
  16414. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16415. if (pickResult.hit && pickResult.pickedSprite) {
  16416. if (pickResult.pickedSprite.actionManager) {
  16417. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16418. if (pickResult.pickedSprite.actionManager) {
  16419. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16420. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16421. }
  16422. }
  16423. }
  16424. }
  16425. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16426. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16427. }
  16428. }
  16429. this._previousPickResult = this._currentPickResult;
  16430. }).bind(_this));
  16431. };
  16432. this._onKeyDown = function (evt) {
  16433. if (_this.actionManager) {
  16434. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16435. }
  16436. };
  16437. this._onKeyUp = function (evt) {
  16438. if (_this.actionManager) {
  16439. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16440. }
  16441. };
  16442. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16443. var canvas = this._engine.getRenderingCanvas();
  16444. if (attachMove) {
  16445. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16446. // Wheel
  16447. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16448. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16449. }
  16450. if (attachDown) {
  16451. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16452. }
  16453. if (attachUp) {
  16454. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16455. }
  16456. canvas.tabIndex = 1;
  16457. canvas.addEventListener("keydown", this._onKeyDown, false);
  16458. canvas.addEventListener("keyup", this._onKeyUp, false);
  16459. };
  16460. Scene.prototype.detachControl = function () {
  16461. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16462. var canvas = this._engine.getRenderingCanvas();
  16463. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16464. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16465. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16466. // Wheel
  16467. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16468. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16469. canvas.removeEventListener("keydown", this._onKeyDown);
  16470. canvas.removeEventListener("keyup", this._onKeyUp);
  16471. };
  16472. // Ready
  16473. Scene.prototype.isReady = function () {
  16474. if (this._pendingData.length > 0) {
  16475. return false;
  16476. }
  16477. var index;
  16478. // Geometries
  16479. for (index = 0; index < this._geometries.length; index++) {
  16480. var geometry = this._geometries[index];
  16481. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16482. return false;
  16483. }
  16484. }
  16485. // Meshes
  16486. for (index = 0; index < this.meshes.length; index++) {
  16487. var mesh = this.meshes[index];
  16488. if (!mesh.isEnabled()) {
  16489. continue;
  16490. }
  16491. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16492. continue;
  16493. }
  16494. if (!mesh.isReady()) {
  16495. return false;
  16496. }
  16497. var mat = mesh.material;
  16498. if (mat) {
  16499. if (!mat.isReady(mesh)) {
  16500. return false;
  16501. }
  16502. }
  16503. }
  16504. return true;
  16505. };
  16506. Scene.prototype.resetCachedMaterial = function () {
  16507. this._cachedMaterial = null;
  16508. this._cachedEffect = null;
  16509. this._cachedVisibility = null;
  16510. };
  16511. Scene.prototype.registerBeforeRender = function (func) {
  16512. this.onBeforeRenderObservable.add(func);
  16513. };
  16514. Scene.prototype.unregisterBeforeRender = function (func) {
  16515. this.onBeforeRenderObservable.removeCallback(func);
  16516. };
  16517. Scene.prototype.registerAfterRender = function (func) {
  16518. this.onAfterRenderObservable.add(func);
  16519. };
  16520. Scene.prototype.unregisterAfterRender = function (func) {
  16521. this.onAfterRenderObservable.removeCallback(func);
  16522. };
  16523. Scene.prototype._addPendingData = function (data) {
  16524. this._pendingData.push(data);
  16525. };
  16526. Scene.prototype._removePendingData = function (data) {
  16527. var index = this._pendingData.indexOf(data);
  16528. if (index !== -1) {
  16529. this._pendingData.splice(index, 1);
  16530. }
  16531. };
  16532. Scene.prototype.getWaitingItemsCount = function () {
  16533. return this._pendingData.length;
  16534. };
  16535. /**
  16536. * Registers a function to be executed when the scene is ready.
  16537. * @param {Function} func - the function to be executed.
  16538. */
  16539. Scene.prototype.executeWhenReady = function (func) {
  16540. var _this = this;
  16541. this.onReadyObservable.add(func);
  16542. if (this._executeWhenReadyTimeoutId !== -1) {
  16543. return;
  16544. }
  16545. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16546. _this._checkIsReady();
  16547. }, 150);
  16548. };
  16549. Scene.prototype._checkIsReady = function () {
  16550. var _this = this;
  16551. if (this.isReady()) {
  16552. this.onReadyObservable.notifyObservers(this);
  16553. this.onReadyObservable.clear();
  16554. this._executeWhenReadyTimeoutId = -1;
  16555. return;
  16556. }
  16557. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16558. _this._checkIsReady();
  16559. }, 150);
  16560. };
  16561. // Animations
  16562. /**
  16563. * Will start the animation sequence of a given target
  16564. * @param target - the target
  16565. * @param {number} from - from which frame should animation start
  16566. * @param {number} to - till which frame should animation run.
  16567. * @param {boolean} [loop] - should the animation loop
  16568. * @param {number} [speedRatio] - the speed in which to run the animation
  16569. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16570. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16571. * @return {BABYLON.Animatable} the animatable object created for this animation
  16572. * @see BABYLON.Animatable
  16573. * @see http://doc.babylonjs.com/page.php?p=22081
  16574. */
  16575. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16576. if (speedRatio === void 0) { speedRatio = 1.0; }
  16577. this.stopAnimation(target);
  16578. if (!animatable) {
  16579. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16580. }
  16581. // Local animations
  16582. if (target.animations) {
  16583. animatable.appendAnimations(target, target.animations);
  16584. }
  16585. // Children animations
  16586. if (target.getAnimatables) {
  16587. var animatables = target.getAnimatables();
  16588. for (var index = 0; index < animatables.length; index++) {
  16589. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16590. }
  16591. }
  16592. animatable.reset();
  16593. return animatable;
  16594. };
  16595. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16596. if (speedRatio === undefined) {
  16597. speedRatio = 1.0;
  16598. }
  16599. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16600. return animatable;
  16601. };
  16602. Scene.prototype.getAnimatableByTarget = function (target) {
  16603. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16604. if (this._activeAnimatables[index].target === target) {
  16605. return this._activeAnimatables[index];
  16606. }
  16607. }
  16608. return null;
  16609. };
  16610. Object.defineProperty(Scene.prototype, "Animatables", {
  16611. get: function () {
  16612. return this._activeAnimatables;
  16613. },
  16614. enumerable: true,
  16615. configurable: true
  16616. });
  16617. /**
  16618. * Will stop the animation of the given target
  16619. * @param target - the target
  16620. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16621. * @see beginAnimation
  16622. */
  16623. Scene.prototype.stopAnimation = function (target, animationName) {
  16624. var animatable = this.getAnimatableByTarget(target);
  16625. if (animatable) {
  16626. animatable.stop(animationName);
  16627. }
  16628. };
  16629. Scene.prototype._animate = function () {
  16630. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16631. return;
  16632. }
  16633. // Getting time
  16634. var now = BABYLON.Tools.Now;
  16635. if (!this._animationTimeLast) {
  16636. if (this._pendingData.length > 0) {
  16637. return;
  16638. }
  16639. this._animationTimeLast = now;
  16640. }
  16641. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16642. this._animationTime += deltaTime;
  16643. this._animationTimeLast = now;
  16644. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16645. this._activeAnimatables[index]._animate(this._animationTime);
  16646. }
  16647. };
  16648. // Matrix
  16649. Scene.prototype.getViewMatrix = function () {
  16650. return this._viewMatrix;
  16651. };
  16652. Scene.prototype.getProjectionMatrix = function () {
  16653. return this._projectionMatrix;
  16654. };
  16655. Scene.prototype.getTransformMatrix = function () {
  16656. return this._transformMatrix;
  16657. };
  16658. Scene.prototype.setTransformMatrix = function (view, projection) {
  16659. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16660. return;
  16661. }
  16662. this._viewUpdateFlag = view.updateFlag;
  16663. this._projectionUpdateFlag = projection.updateFlag;
  16664. this._viewMatrix = view;
  16665. this._projectionMatrix = projection;
  16666. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16667. // Update frustum
  16668. if (!this._frustumPlanes) {
  16669. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16670. }
  16671. else {
  16672. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16673. }
  16674. if (this._sceneUbo.useUbo) {
  16675. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16676. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16677. this._sceneUbo.update();
  16678. }
  16679. };
  16680. Scene.prototype.getSceneUniformBuffer = function () {
  16681. return this._sceneUbo;
  16682. };
  16683. // Methods
  16684. Scene.prototype.getUniqueId = function () {
  16685. var result = this._uniqueIdCounter;
  16686. this._uniqueIdCounter++;
  16687. return result;
  16688. };
  16689. Scene.prototype.addMesh = function (newMesh) {
  16690. newMesh.uniqueId = this.getUniqueId();
  16691. var position = this.meshes.push(newMesh);
  16692. //notify the collision coordinator
  16693. if (this.collisionCoordinator) {
  16694. this.collisionCoordinator.onMeshAdded(newMesh);
  16695. }
  16696. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16697. };
  16698. Scene.prototype.removeMesh = function (toRemove) {
  16699. var index = this.meshes.indexOf(toRemove);
  16700. if (index !== -1) {
  16701. // Remove from the scene if mesh found
  16702. this.meshes.splice(index, 1);
  16703. }
  16704. //notify the collision coordinator
  16705. if (this.collisionCoordinator) {
  16706. this.collisionCoordinator.onMeshRemoved(toRemove);
  16707. }
  16708. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16709. return index;
  16710. };
  16711. Scene.prototype.removeSkeleton = function (toRemove) {
  16712. var index = this.skeletons.indexOf(toRemove);
  16713. if (index !== -1) {
  16714. // Remove from the scene if found
  16715. this.skeletons.splice(index, 1);
  16716. }
  16717. return index;
  16718. };
  16719. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16720. var index = this.morphTargetManagers.indexOf(toRemove);
  16721. if (index !== -1) {
  16722. // Remove from the scene if found
  16723. this.morphTargetManagers.splice(index, 1);
  16724. }
  16725. return index;
  16726. };
  16727. Scene.prototype.removeLight = function (toRemove) {
  16728. var index = this.lights.indexOf(toRemove);
  16729. if (index !== -1) {
  16730. // Remove from the scene if mesh found
  16731. this.lights.splice(index, 1);
  16732. this.sortLightsByPriority();
  16733. }
  16734. this.onLightRemovedObservable.notifyObservers(toRemove);
  16735. return index;
  16736. };
  16737. Scene.prototype.removeCamera = function (toRemove) {
  16738. var index = this.cameras.indexOf(toRemove);
  16739. if (index !== -1) {
  16740. // Remove from the scene if mesh found
  16741. this.cameras.splice(index, 1);
  16742. }
  16743. // Remove from activeCameras
  16744. var index2 = this.activeCameras.indexOf(toRemove);
  16745. if (index2 !== -1) {
  16746. // Remove from the scene if mesh found
  16747. this.activeCameras.splice(index2, 1);
  16748. }
  16749. // Reset the activeCamera
  16750. if (this.activeCamera === toRemove) {
  16751. if (this.cameras.length > 0) {
  16752. this.activeCamera = this.cameras[0];
  16753. }
  16754. else {
  16755. this.activeCamera = null;
  16756. }
  16757. }
  16758. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16759. return index;
  16760. };
  16761. Scene.prototype.addLight = function (newLight) {
  16762. newLight.uniqueId = this.getUniqueId();
  16763. this.lights.push(newLight);
  16764. this.sortLightsByPriority();
  16765. this.onNewLightAddedObservable.notifyObservers(newLight);
  16766. };
  16767. Scene.prototype.sortLightsByPriority = function () {
  16768. if (this.requireLightSorting) {
  16769. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16770. }
  16771. };
  16772. Scene.prototype.addCamera = function (newCamera) {
  16773. newCamera.uniqueId = this.getUniqueId();
  16774. var position = this.cameras.push(newCamera);
  16775. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16776. };
  16777. /**
  16778. * Switch active camera
  16779. * @param {Camera} newCamera - new active camera
  16780. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16781. */
  16782. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16783. if (attachControl === void 0) { attachControl = true; }
  16784. var canvas = this._engine.getRenderingCanvas();
  16785. this.activeCamera.detachControl(canvas);
  16786. this.activeCamera = newCamera;
  16787. if (attachControl) {
  16788. newCamera.attachControl(canvas);
  16789. }
  16790. };
  16791. /**
  16792. * sets the active camera of the scene using its ID
  16793. * @param {string} id - the camera's ID
  16794. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16795. * @see activeCamera
  16796. */
  16797. Scene.prototype.setActiveCameraByID = function (id) {
  16798. var camera = this.getCameraByID(id);
  16799. if (camera) {
  16800. this.activeCamera = camera;
  16801. return camera;
  16802. }
  16803. return null;
  16804. };
  16805. /**
  16806. * sets the active camera of the scene using its name
  16807. * @param {string} name - the camera's name
  16808. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16809. * @see activeCamera
  16810. */
  16811. Scene.prototype.setActiveCameraByName = function (name) {
  16812. var camera = this.getCameraByName(name);
  16813. if (camera) {
  16814. this.activeCamera = camera;
  16815. return camera;
  16816. }
  16817. return null;
  16818. };
  16819. /**
  16820. * get a material using its id
  16821. * @param {string} the material's ID
  16822. * @return {BABYLON.Material|null} the material or null if none found.
  16823. */
  16824. Scene.prototype.getMaterialByID = function (id) {
  16825. for (var index = 0; index < this.materials.length; index++) {
  16826. if (this.materials[index].id === id) {
  16827. return this.materials[index];
  16828. }
  16829. }
  16830. return null;
  16831. };
  16832. /**
  16833. * get a material using its name
  16834. * @param {string} the material's name
  16835. * @return {BABYLON.Material|null} the material or null if none found.
  16836. */
  16837. Scene.prototype.getMaterialByName = function (name) {
  16838. for (var index = 0; index < this.materials.length; index++) {
  16839. if (this.materials[index].name === name) {
  16840. return this.materials[index];
  16841. }
  16842. }
  16843. return null;
  16844. };
  16845. Scene.prototype.getLensFlareSystemByName = function (name) {
  16846. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16847. if (this.lensFlareSystems[index].name === name) {
  16848. return this.lensFlareSystems[index];
  16849. }
  16850. }
  16851. return null;
  16852. };
  16853. Scene.prototype.getLensFlareSystemByID = function (id) {
  16854. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16855. if (this.lensFlareSystems[index].id === id) {
  16856. return this.lensFlareSystems[index];
  16857. }
  16858. }
  16859. return null;
  16860. };
  16861. Scene.prototype.getCameraByID = function (id) {
  16862. for (var index = 0; index < this.cameras.length; index++) {
  16863. if (this.cameras[index].id === id) {
  16864. return this.cameras[index];
  16865. }
  16866. }
  16867. return null;
  16868. };
  16869. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16870. for (var index = 0; index < this.cameras.length; index++) {
  16871. if (this.cameras[index].uniqueId === uniqueId) {
  16872. return this.cameras[index];
  16873. }
  16874. }
  16875. return null;
  16876. };
  16877. /**
  16878. * get a camera using its name
  16879. * @param {string} the camera's name
  16880. * @return {BABYLON.Camera|null} the camera or null if none found.
  16881. */
  16882. Scene.prototype.getCameraByName = function (name) {
  16883. for (var index = 0; index < this.cameras.length; index++) {
  16884. if (this.cameras[index].name === name) {
  16885. return this.cameras[index];
  16886. }
  16887. }
  16888. return null;
  16889. };
  16890. /**
  16891. * get a bone using its id
  16892. * @param {string} the bone's id
  16893. * @return {BABYLON.Bone|null} the bone or null if not found
  16894. */
  16895. Scene.prototype.getBoneByID = function (id) {
  16896. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16897. var skeleton = this.skeletons[skeletonIndex];
  16898. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16899. if (skeleton.bones[boneIndex].id === id) {
  16900. return skeleton.bones[boneIndex];
  16901. }
  16902. }
  16903. }
  16904. return null;
  16905. };
  16906. /**
  16907. * get a bone using its id
  16908. * @param {string} the bone's name
  16909. * @return {BABYLON.Bone|null} the bone or null if not found
  16910. */
  16911. Scene.prototype.getBoneByName = function (name) {
  16912. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16913. var skeleton = this.skeletons[skeletonIndex];
  16914. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16915. if (skeleton.bones[boneIndex].name === name) {
  16916. return skeleton.bones[boneIndex];
  16917. }
  16918. }
  16919. }
  16920. return null;
  16921. };
  16922. /**
  16923. * get a light node using its name
  16924. * @param {string} the light's name
  16925. * @return {BABYLON.Light|null} the light or null if none found.
  16926. */
  16927. Scene.prototype.getLightByName = function (name) {
  16928. for (var index = 0; index < this.lights.length; index++) {
  16929. if (this.lights[index].name === name) {
  16930. return this.lights[index];
  16931. }
  16932. }
  16933. return null;
  16934. };
  16935. /**
  16936. * get a light node using its ID
  16937. * @param {string} the light's id
  16938. * @return {BABYLON.Light|null} the light or null if none found.
  16939. */
  16940. Scene.prototype.getLightByID = function (id) {
  16941. for (var index = 0; index < this.lights.length; index++) {
  16942. if (this.lights[index].id === id) {
  16943. return this.lights[index];
  16944. }
  16945. }
  16946. return null;
  16947. };
  16948. /**
  16949. * get a light node using its scene-generated unique ID
  16950. * @param {number} the light's unique id
  16951. * @return {BABYLON.Light|null} the light or null if none found.
  16952. */
  16953. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16954. for (var index = 0; index < this.lights.length; index++) {
  16955. if (this.lights[index].uniqueId === uniqueId) {
  16956. return this.lights[index];
  16957. }
  16958. }
  16959. return null;
  16960. };
  16961. /**
  16962. * get a particle system by id
  16963. * @param id {number} the particle system id
  16964. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16965. */
  16966. Scene.prototype.getParticleSystemByID = function (id) {
  16967. for (var index = 0; index < this.particleSystems.length; index++) {
  16968. if (this.particleSystems[index].id === id) {
  16969. return this.particleSystems[index];
  16970. }
  16971. }
  16972. return null;
  16973. };
  16974. /**
  16975. * get a geometry using its ID
  16976. * @param {string} the geometry's id
  16977. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16978. */
  16979. Scene.prototype.getGeometryByID = function (id) {
  16980. for (var index = 0; index < this._geometries.length; index++) {
  16981. if (this._geometries[index].id === id) {
  16982. return this._geometries[index];
  16983. }
  16984. }
  16985. return null;
  16986. };
  16987. /**
  16988. * add a new geometry to this scene.
  16989. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16990. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16991. * @return {boolean} was the geometry added or not
  16992. */
  16993. Scene.prototype.pushGeometry = function (geometry, force) {
  16994. if (!force && this.getGeometryByID(geometry.id)) {
  16995. return false;
  16996. }
  16997. this._geometries.push(geometry);
  16998. //notify the collision coordinator
  16999. if (this.collisionCoordinator) {
  17000. this.collisionCoordinator.onGeometryAdded(geometry);
  17001. }
  17002. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17003. return true;
  17004. };
  17005. /**
  17006. * Removes an existing geometry
  17007. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17008. * @return {boolean} was the geometry removed or not
  17009. */
  17010. Scene.prototype.removeGeometry = function (geometry) {
  17011. var index = this._geometries.indexOf(geometry);
  17012. if (index > -1) {
  17013. this._geometries.splice(index, 1);
  17014. //notify the collision coordinator
  17015. if (this.collisionCoordinator) {
  17016. this.collisionCoordinator.onGeometryDeleted(geometry);
  17017. }
  17018. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17019. return true;
  17020. }
  17021. return false;
  17022. };
  17023. Scene.prototype.getGeometries = function () {
  17024. return this._geometries;
  17025. };
  17026. /**
  17027. * Get the first added mesh found of a given ID
  17028. * @param {string} id - the id to search for
  17029. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17030. */
  17031. Scene.prototype.getMeshByID = function (id) {
  17032. for (var index = 0; index < this.meshes.length; index++) {
  17033. if (this.meshes[index].id === id) {
  17034. return this.meshes[index];
  17035. }
  17036. }
  17037. return null;
  17038. };
  17039. Scene.prototype.getMeshesByID = function (id) {
  17040. return this.meshes.filter(function (m) {
  17041. return m.id === id;
  17042. });
  17043. };
  17044. /**
  17045. * Get a mesh with its auto-generated unique id
  17046. * @param {number} uniqueId - the unique id to search for
  17047. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17048. */
  17049. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17050. for (var index = 0; index < this.meshes.length; index++) {
  17051. if (this.meshes[index].uniqueId === uniqueId) {
  17052. return this.meshes[index];
  17053. }
  17054. }
  17055. return null;
  17056. };
  17057. /**
  17058. * Get a the last added mesh found of a given ID
  17059. * @param {string} id - the id to search for
  17060. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17061. */
  17062. Scene.prototype.getLastMeshByID = function (id) {
  17063. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17064. if (this.meshes[index].id === id) {
  17065. return this.meshes[index];
  17066. }
  17067. }
  17068. return null;
  17069. };
  17070. /**
  17071. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17072. * @param {string} id - the id to search for
  17073. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17074. */
  17075. Scene.prototype.getLastEntryByID = function (id) {
  17076. var index;
  17077. for (index = this.meshes.length - 1; index >= 0; index--) {
  17078. if (this.meshes[index].id === id) {
  17079. return this.meshes[index];
  17080. }
  17081. }
  17082. for (index = this.cameras.length - 1; index >= 0; index--) {
  17083. if (this.cameras[index].id === id) {
  17084. return this.cameras[index];
  17085. }
  17086. }
  17087. for (index = this.lights.length - 1; index >= 0; index--) {
  17088. if (this.lights[index].id === id) {
  17089. return this.lights[index];
  17090. }
  17091. }
  17092. return null;
  17093. };
  17094. Scene.prototype.getNodeByID = function (id) {
  17095. var mesh = this.getMeshByID(id);
  17096. if (mesh) {
  17097. return mesh;
  17098. }
  17099. var light = this.getLightByID(id);
  17100. if (light) {
  17101. return light;
  17102. }
  17103. var camera = this.getCameraByID(id);
  17104. if (camera) {
  17105. return camera;
  17106. }
  17107. var bone = this.getBoneByID(id);
  17108. return bone;
  17109. };
  17110. Scene.prototype.getNodeByName = function (name) {
  17111. var mesh = this.getMeshByName(name);
  17112. if (mesh) {
  17113. return mesh;
  17114. }
  17115. var light = this.getLightByName(name);
  17116. if (light) {
  17117. return light;
  17118. }
  17119. var camera = this.getCameraByName(name);
  17120. if (camera) {
  17121. return camera;
  17122. }
  17123. var bone = this.getBoneByName(name);
  17124. return bone;
  17125. };
  17126. Scene.prototype.getMeshByName = function (name) {
  17127. for (var index = 0; index < this.meshes.length; index++) {
  17128. if (this.meshes[index].name === name) {
  17129. return this.meshes[index];
  17130. }
  17131. }
  17132. return null;
  17133. };
  17134. Scene.prototype.getSoundByName = function (name) {
  17135. var index;
  17136. if (BABYLON.AudioEngine) {
  17137. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17138. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17139. return this.mainSoundTrack.soundCollection[index];
  17140. }
  17141. }
  17142. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17143. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17144. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17145. return this.soundTracks[sdIndex].soundCollection[index];
  17146. }
  17147. }
  17148. }
  17149. }
  17150. return null;
  17151. };
  17152. Scene.prototype.getLastSkeletonByID = function (id) {
  17153. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17154. if (this.skeletons[index].id === id) {
  17155. return this.skeletons[index];
  17156. }
  17157. }
  17158. return null;
  17159. };
  17160. Scene.prototype.getSkeletonById = function (id) {
  17161. for (var index = 0; index < this.skeletons.length; index++) {
  17162. if (this.skeletons[index].id === id) {
  17163. return this.skeletons[index];
  17164. }
  17165. }
  17166. return null;
  17167. };
  17168. Scene.prototype.getSkeletonByName = function (name) {
  17169. for (var index = 0; index < this.skeletons.length; index++) {
  17170. if (this.skeletons[index].name === name) {
  17171. return this.skeletons[index];
  17172. }
  17173. }
  17174. return null;
  17175. };
  17176. Scene.prototype.getMorphTargetManagerById = function (id) {
  17177. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17178. if (this.morphTargetManagers[index].uniqueId === id) {
  17179. return this.morphTargetManagers[index];
  17180. }
  17181. }
  17182. return null;
  17183. };
  17184. Scene.prototype.isActiveMesh = function (mesh) {
  17185. return (this._activeMeshes.indexOf(mesh) !== -1);
  17186. };
  17187. /**
  17188. * Return a the first highlight layer of the scene with a given name.
  17189. * @param name The name of the highlight layer to look for.
  17190. * @return The highlight layer if found otherwise null.
  17191. */
  17192. Scene.prototype.getHighlightLayerByName = function (name) {
  17193. for (var index = 0; index < this.highlightLayers.length; index++) {
  17194. if (this.highlightLayers[index].name === name) {
  17195. return this.highlightLayers[index];
  17196. }
  17197. }
  17198. return null;
  17199. };
  17200. Object.defineProperty(Scene.prototype, "uid", {
  17201. /**
  17202. * Return a unique id as a string which can serve as an identifier for the scene
  17203. */
  17204. get: function () {
  17205. if (!this._uid) {
  17206. this._uid = BABYLON.Tools.RandomId();
  17207. }
  17208. return this._uid;
  17209. },
  17210. enumerable: true,
  17211. configurable: true
  17212. });
  17213. /**
  17214. * Add an externaly attached data from its key.
  17215. * This method call will fail and return false, if such key already exists.
  17216. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17217. * @param key the unique key that identifies the data
  17218. * @param data the data object to associate to the key for this Engine instance
  17219. * @return true if no such key were already present and the data was added successfully, false otherwise
  17220. */
  17221. Scene.prototype.addExternalData = function (key, data) {
  17222. if (!this._externalData) {
  17223. this._externalData = new BABYLON.StringDictionary();
  17224. }
  17225. return this._externalData.add(key, data);
  17226. };
  17227. /**
  17228. * Get an externaly attached data from its key
  17229. * @param key the unique key that identifies the data
  17230. * @return the associated data, if present (can be null), or undefined if not present
  17231. */
  17232. Scene.prototype.getExternalData = function (key) {
  17233. if (!this._externalData) {
  17234. return null;
  17235. }
  17236. return this._externalData.get(key);
  17237. };
  17238. /**
  17239. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17240. * @param key the unique key that identifies the data
  17241. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17242. * @return the associated data, can be null if the factory returned null.
  17243. */
  17244. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17245. if (!this._externalData) {
  17246. this._externalData = new BABYLON.StringDictionary();
  17247. }
  17248. return this._externalData.getOrAddWithFactory(key, factory);
  17249. };
  17250. /**
  17251. * Remove an externaly attached data from the Engine instance
  17252. * @param key the unique key that identifies the data
  17253. * @return true if the data was successfully removed, false if it doesn't exist
  17254. */
  17255. Scene.prototype.removeExternalData = function (key) {
  17256. return this._externalData.remove(key);
  17257. };
  17258. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17259. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17260. var material = subMesh.getMaterial();
  17261. if (mesh.showSubMeshesBoundingBox) {
  17262. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17263. }
  17264. if (material) {
  17265. // Render targets
  17266. if (material.getRenderTargetTextures) {
  17267. if (this._processedMaterials.indexOf(material) === -1) {
  17268. this._processedMaterials.push(material);
  17269. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17270. }
  17271. }
  17272. // Dispatch
  17273. this._activeIndices.addCount(subMesh.indexCount, false);
  17274. this._renderingManager.dispatch(subMesh);
  17275. }
  17276. }
  17277. };
  17278. Scene.prototype._isInIntermediateRendering = function () {
  17279. return this._intermediateRendering;
  17280. };
  17281. Scene.prototype._evaluateActiveMeshes = function () {
  17282. this.activeCamera._activeMeshes.reset();
  17283. this._activeMeshes.reset();
  17284. this._renderingManager.reset();
  17285. this._processedMaterials.reset();
  17286. this._activeParticleSystems.reset();
  17287. this._activeSkeletons.reset();
  17288. this._softwareSkinnedMeshes.reset();
  17289. if (this._boundingBoxRenderer) {
  17290. this._boundingBoxRenderer.reset();
  17291. }
  17292. // Meshes
  17293. var meshes;
  17294. var len;
  17295. if (this._selectionOctree) {
  17296. var selection = this._selectionOctree.select(this._frustumPlanes);
  17297. meshes = selection.data;
  17298. len = selection.length;
  17299. }
  17300. else {
  17301. len = this.meshes.length;
  17302. meshes = this.meshes;
  17303. }
  17304. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17305. var mesh = meshes[meshIndex];
  17306. if (mesh.isBlocked) {
  17307. continue;
  17308. }
  17309. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17310. if (!mesh.isReady() || !mesh.isEnabled()) {
  17311. continue;
  17312. }
  17313. mesh.computeWorldMatrix();
  17314. // Intersections
  17315. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17316. this._meshesForIntersections.pushNoDuplicate(mesh);
  17317. }
  17318. // Switch to current LOD
  17319. var meshLOD = mesh.getLOD(this.activeCamera);
  17320. if (!meshLOD) {
  17321. continue;
  17322. }
  17323. mesh._preActivate();
  17324. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17325. this._activeMeshes.push(mesh);
  17326. this.activeCamera._activeMeshes.push(mesh);
  17327. mesh._activate(this._renderId);
  17328. this._activeMesh(mesh, meshLOD);
  17329. }
  17330. }
  17331. // Particle systems
  17332. this._particlesDuration.beginMonitoring();
  17333. var beforeParticlesDate = BABYLON.Tools.Now;
  17334. if (this.particlesEnabled) {
  17335. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17336. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17337. var particleSystem = this.particleSystems[particleIndex];
  17338. if (!particleSystem.isStarted()) {
  17339. continue;
  17340. }
  17341. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17342. this._activeParticleSystems.push(particleSystem);
  17343. particleSystem.animate();
  17344. this._renderingManager.dispatchParticles(particleSystem);
  17345. }
  17346. }
  17347. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17348. }
  17349. this._particlesDuration.endMonitoring(false);
  17350. };
  17351. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17352. if (mesh.skeleton && this.skeletonsEnabled) {
  17353. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17354. mesh.skeleton.prepare();
  17355. }
  17356. if (!mesh.computeBonesUsingShaders) {
  17357. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17358. }
  17359. }
  17360. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17361. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17362. }
  17363. if (mesh && mesh.subMeshes) {
  17364. // Submeshes Octrees
  17365. var len;
  17366. var subMeshes;
  17367. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17368. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17369. len = intersections.length;
  17370. subMeshes = intersections.data;
  17371. }
  17372. else {
  17373. subMeshes = mesh.subMeshes;
  17374. len = subMeshes.length;
  17375. }
  17376. for (var subIndex = 0; subIndex < len; subIndex++) {
  17377. var subMesh = subMeshes[subIndex];
  17378. this._evaluateSubMesh(subMesh, mesh);
  17379. }
  17380. }
  17381. };
  17382. Scene.prototype.updateTransformMatrix = function (force) {
  17383. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17384. };
  17385. Scene.prototype._renderForCamera = function (camera) {
  17386. var engine = this._engine;
  17387. var startTime = BABYLON.Tools.Now;
  17388. this.activeCamera = camera;
  17389. if (!this.activeCamera)
  17390. throw new Error("Active camera not set");
  17391. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17392. // Viewport
  17393. engine.setViewport(this.activeCamera.viewport);
  17394. // Camera
  17395. this.resetCachedMaterial();
  17396. this._renderId++;
  17397. this.updateTransformMatrix();
  17398. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17399. // Meshes
  17400. this._evaluateActiveMeshesDuration.beginMonitoring();
  17401. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17402. this._evaluateActiveMeshes();
  17403. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17404. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17405. // Software skinning
  17406. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17407. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17408. mesh.applySkeleton(mesh.skeleton);
  17409. }
  17410. // Render targets
  17411. this._renderTargetsDuration.beginMonitoring();
  17412. var needsRestoreFrameBuffer = false;
  17413. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17414. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17415. this._intermediateRendering = true;
  17416. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17417. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17418. var renderTarget = this._renderTargets.data[renderIndex];
  17419. if (renderTarget._shouldRender()) {
  17420. this._renderId++;
  17421. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17422. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17423. }
  17424. }
  17425. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17426. this._intermediateRendering = false;
  17427. this._renderId++;
  17428. needsRestoreFrameBuffer = true; // Restore back buffer
  17429. }
  17430. // Render HighlightLayer Texture
  17431. var stencilState = this._engine.getStencilBuffer();
  17432. var renderhighlights = false;
  17433. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17434. this._intermediateRendering = true;
  17435. for (var i = 0; i < this.highlightLayers.length; i++) {
  17436. var highlightLayer = this.highlightLayers[i];
  17437. if (highlightLayer.shouldRender() &&
  17438. (!highlightLayer.camera ||
  17439. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17440. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17441. renderhighlights = true;
  17442. var renderTarget = highlightLayer._mainTexture;
  17443. if (renderTarget._shouldRender()) {
  17444. this._renderId++;
  17445. renderTarget.render(false, false);
  17446. needsRestoreFrameBuffer = true;
  17447. }
  17448. }
  17449. }
  17450. this._intermediateRendering = false;
  17451. this._renderId++;
  17452. }
  17453. if (needsRestoreFrameBuffer) {
  17454. if (this.offscreenRenderTarget) {
  17455. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17456. }
  17457. else {
  17458. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17459. }
  17460. }
  17461. this._renderTargetsDuration.endMonitoring(false);
  17462. // Prepare Frame
  17463. this.postProcessManager._prepareFrame();
  17464. this._renderDuration.beginMonitoring();
  17465. // Backgrounds
  17466. var layerIndex;
  17467. var layer;
  17468. if (this.layers.length) {
  17469. engine.setDepthBuffer(false);
  17470. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17471. layer = this.layers[layerIndex];
  17472. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17473. layer.render();
  17474. }
  17475. }
  17476. engine.setDepthBuffer(true);
  17477. }
  17478. // Render
  17479. BABYLON.Tools.StartPerformanceCounter("Main render");
  17480. // Activate HighlightLayer stencil
  17481. if (renderhighlights) {
  17482. this._engine.setStencilBuffer(true);
  17483. }
  17484. this._renderingManager.render(null, null, true, true);
  17485. // Restore HighlightLayer stencil
  17486. if (renderhighlights) {
  17487. this._engine.setStencilBuffer(stencilState);
  17488. }
  17489. BABYLON.Tools.EndPerformanceCounter("Main render");
  17490. // Bounding boxes
  17491. if (this._boundingBoxRenderer) {
  17492. this._boundingBoxRenderer.render();
  17493. }
  17494. // Lens flares
  17495. if (this.lensFlaresEnabled) {
  17496. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17497. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17498. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17499. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17500. lensFlareSystem.render();
  17501. }
  17502. }
  17503. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17504. }
  17505. // Foregrounds
  17506. if (this.layers.length) {
  17507. engine.setDepthBuffer(false);
  17508. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17509. layer = this.layers[layerIndex];
  17510. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17511. layer.render();
  17512. }
  17513. }
  17514. engine.setDepthBuffer(true);
  17515. }
  17516. // Highlight Layer
  17517. if (renderhighlights) {
  17518. engine.setDepthBuffer(false);
  17519. for (var i = 0; i < this.highlightLayers.length; i++) {
  17520. if (this.highlightLayers[i].shouldRender()) {
  17521. this.highlightLayers[i].render();
  17522. }
  17523. }
  17524. engine.setDepthBuffer(true);
  17525. }
  17526. this._renderDuration.endMonitoring(false);
  17527. // Finalize frame
  17528. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17529. // Update camera
  17530. this.activeCamera._updateFromScene();
  17531. // Reset some special arrays
  17532. this._renderTargets.reset();
  17533. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17534. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17535. };
  17536. Scene.prototype._processSubCameras = function (camera) {
  17537. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17538. this._renderForCamera(camera);
  17539. return;
  17540. }
  17541. // rig cameras
  17542. for (var index = 0; index < camera._rigCameras.length; index++) {
  17543. this._renderForCamera(camera._rigCameras[index]);
  17544. }
  17545. this.activeCamera = camera;
  17546. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17547. // Update camera
  17548. this.activeCamera._updateFromScene();
  17549. };
  17550. Scene.prototype._checkIntersections = function () {
  17551. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17552. var sourceMesh = this._meshesForIntersections.data[index];
  17553. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17554. var action = sourceMesh.actionManager.actions[actionIndex];
  17555. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17556. var parameters = action.getTriggerParameter();
  17557. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17558. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17559. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17560. if (areIntersecting && currentIntersectionInProgress === -1) {
  17561. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17562. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17563. sourceMesh._intersectionsInProgress.push(otherMesh);
  17564. }
  17565. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17566. sourceMesh._intersectionsInProgress.push(otherMesh);
  17567. }
  17568. }
  17569. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17570. //They intersected, and now they don't.
  17571. //is this trigger an exit trigger? execute an event.
  17572. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17573. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17574. }
  17575. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17576. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17577. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17578. }
  17579. }
  17580. }
  17581. }
  17582. }
  17583. };
  17584. Scene.prototype.render = function () {
  17585. if (this.isDisposed) {
  17586. return;
  17587. }
  17588. this._lastFrameDuration.beginMonitoring();
  17589. this._particlesDuration.fetchNewFrame();
  17590. this._spritesDuration.fetchNewFrame();
  17591. this._activeParticles.fetchNewFrame();
  17592. this._renderDuration.fetchNewFrame();
  17593. this._renderTargetsDuration.fetchNewFrame();
  17594. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17595. this._totalVertices.fetchNewFrame();
  17596. this._activeIndices.fetchNewFrame();
  17597. this._activeBones.fetchNewFrame();
  17598. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17599. this._meshesForIntersections.reset();
  17600. this.resetCachedMaterial();
  17601. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17602. // Actions
  17603. if (this.actionManager) {
  17604. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17605. }
  17606. //Simplification Queue
  17607. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17608. this.simplificationQueue.executeNext();
  17609. }
  17610. // Animations
  17611. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17612. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17613. this._animate();
  17614. // Physics
  17615. if (this._physicsEngine) {
  17616. BABYLON.Tools.StartPerformanceCounter("Physics");
  17617. this._physicsEngine._step(deltaTime / 1000.0);
  17618. BABYLON.Tools.EndPerformanceCounter("Physics");
  17619. }
  17620. // Before render
  17621. this.onBeforeRenderObservable.notifyObservers(this);
  17622. // Customs render targets
  17623. this._renderTargetsDuration.beginMonitoring();
  17624. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17625. var engine = this.getEngine();
  17626. var currentActiveCamera = this.activeCamera;
  17627. if (this.renderTargetsEnabled) {
  17628. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17629. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17630. var renderTarget = this.customRenderTargets[customIndex];
  17631. if (renderTarget._shouldRender()) {
  17632. this._renderId++;
  17633. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17634. if (!this.activeCamera)
  17635. throw new Error("Active camera not set");
  17636. // Viewport
  17637. engine.setViewport(this.activeCamera.viewport);
  17638. // Camera
  17639. this.updateTransformMatrix();
  17640. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17641. }
  17642. }
  17643. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17644. this._renderId++;
  17645. }
  17646. if (this.offscreenRenderTarget) {
  17647. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17648. }
  17649. else {
  17650. // Restore back buffer
  17651. if (this.customRenderTargets.length > 0) {
  17652. engine.restoreDefaultFramebuffer();
  17653. }
  17654. }
  17655. this._renderTargetsDuration.endMonitoring();
  17656. this.activeCamera = currentActiveCamera;
  17657. // Procedural textures
  17658. if (this.proceduralTexturesEnabled) {
  17659. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17660. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17661. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17662. if (proceduralTexture._shouldRender()) {
  17663. proceduralTexture.render();
  17664. }
  17665. }
  17666. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17667. }
  17668. // Clear
  17669. if (this.autoClearDepthAndStencil || this.autoClear) {
  17670. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17671. }
  17672. // Shadows
  17673. if (this.shadowsEnabled) {
  17674. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17675. var light = this.lights[lightIndex];
  17676. var shadowGenerator = light.getShadowGenerator();
  17677. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17678. var shadowMap = shadowGenerator.getShadowMap();
  17679. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17680. this._renderTargets.push(shadowMap);
  17681. }
  17682. }
  17683. }
  17684. }
  17685. // Depth renderer
  17686. if (this._depthRenderer) {
  17687. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17688. }
  17689. // Geometry renderer
  17690. if (this._geometryBufferRenderer) {
  17691. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17692. }
  17693. // RenderPipeline
  17694. if (this._postProcessRenderPipelineManager) {
  17695. this._postProcessRenderPipelineManager.update();
  17696. }
  17697. // Multi-cameras?
  17698. if (this.activeCameras.length > 0) {
  17699. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17700. if (cameraIndex > 0) {
  17701. this._engine.clear(null, false, true, true);
  17702. }
  17703. this._processSubCameras(this.activeCameras[cameraIndex]);
  17704. }
  17705. }
  17706. else {
  17707. if (!this.activeCamera) {
  17708. throw new Error("No camera defined");
  17709. }
  17710. this._processSubCameras(this.activeCamera);
  17711. }
  17712. // Intersection checks
  17713. this._checkIntersections();
  17714. // Update the audio listener attached to the camera
  17715. if (BABYLON.AudioEngine) {
  17716. this._updateAudioParameters();
  17717. }
  17718. // After render
  17719. if (this.afterRender) {
  17720. this.afterRender();
  17721. }
  17722. this.onAfterRenderObservable.notifyObservers(this);
  17723. // Cleaning
  17724. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17725. this._toBeDisposed.data[index].dispose();
  17726. this._toBeDisposed[index] = null;
  17727. }
  17728. this._toBeDisposed.reset();
  17729. if (this.dumpNextRenderTargets) {
  17730. this.dumpNextRenderTargets = false;
  17731. }
  17732. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17733. this._lastFrameDuration.endMonitoring();
  17734. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17735. this._totalLightsCounter.addCount(this.lights.length, true);
  17736. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17737. this._totalTexturesCounter.addCount(this.textures.length, true);
  17738. this._activeBones.addCount(0, true);
  17739. this._activeIndices.addCount(0, true);
  17740. this._activeParticles.addCount(0, true);
  17741. };
  17742. Scene.prototype._updateAudioParameters = function () {
  17743. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17744. return;
  17745. }
  17746. var listeningCamera;
  17747. var audioEngine = BABYLON.Engine.audioEngine;
  17748. if (this.activeCameras.length > 0) {
  17749. listeningCamera = this.activeCameras[0];
  17750. }
  17751. else {
  17752. listeningCamera = this.activeCamera;
  17753. }
  17754. if (listeningCamera && audioEngine.canUseWebAudio) {
  17755. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17756. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17757. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17758. cameraDirection.normalize();
  17759. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17760. var i;
  17761. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17762. var sound = this.mainSoundTrack.soundCollection[i];
  17763. if (sound.useCustomAttenuation) {
  17764. sound.updateDistanceFromListener();
  17765. }
  17766. }
  17767. for (i = 0; i < this.soundTracks.length; i++) {
  17768. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17769. sound = this.soundTracks[i].soundCollection[j];
  17770. if (sound.useCustomAttenuation) {
  17771. sound.updateDistanceFromListener();
  17772. }
  17773. }
  17774. }
  17775. }
  17776. };
  17777. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17778. // Audio
  17779. get: function () {
  17780. return this._audioEnabled;
  17781. },
  17782. set: function (value) {
  17783. this._audioEnabled = value;
  17784. if (BABYLON.AudioEngine) {
  17785. if (this._audioEnabled) {
  17786. this._enableAudio();
  17787. }
  17788. else {
  17789. this._disableAudio();
  17790. }
  17791. }
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. Scene.prototype._disableAudio = function () {
  17797. var i;
  17798. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17799. this.mainSoundTrack.soundCollection[i].pause();
  17800. }
  17801. for (i = 0; i < this.soundTracks.length; i++) {
  17802. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17803. this.soundTracks[i].soundCollection[j].pause();
  17804. }
  17805. }
  17806. };
  17807. Scene.prototype._enableAudio = function () {
  17808. var i;
  17809. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17810. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17811. this.mainSoundTrack.soundCollection[i].play();
  17812. }
  17813. }
  17814. for (i = 0; i < this.soundTracks.length; i++) {
  17815. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17816. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17817. this.soundTracks[i].soundCollection[j].play();
  17818. }
  17819. }
  17820. }
  17821. };
  17822. Object.defineProperty(Scene.prototype, "headphone", {
  17823. get: function () {
  17824. return this._headphone;
  17825. },
  17826. set: function (value) {
  17827. this._headphone = value;
  17828. if (BABYLON.AudioEngine) {
  17829. if (this._headphone) {
  17830. this._switchAudioModeForHeadphones();
  17831. }
  17832. else {
  17833. this._switchAudioModeForNormalSpeakers();
  17834. }
  17835. }
  17836. },
  17837. enumerable: true,
  17838. configurable: true
  17839. });
  17840. Scene.prototype._switchAudioModeForHeadphones = function () {
  17841. this.mainSoundTrack.switchPanningModelToHRTF();
  17842. for (var i = 0; i < this.soundTracks.length; i++) {
  17843. this.soundTracks[i].switchPanningModelToHRTF();
  17844. }
  17845. };
  17846. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17847. this.mainSoundTrack.switchPanningModelToEqualPower();
  17848. for (var i = 0; i < this.soundTracks.length; i++) {
  17849. this.soundTracks[i].switchPanningModelToEqualPower();
  17850. }
  17851. };
  17852. Scene.prototype.enableDepthRenderer = function () {
  17853. if (this._depthRenderer) {
  17854. return this._depthRenderer;
  17855. }
  17856. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17857. return this._depthRenderer;
  17858. };
  17859. Scene.prototype.disableDepthRenderer = function () {
  17860. if (!this._depthRenderer) {
  17861. return;
  17862. }
  17863. this._depthRenderer.dispose();
  17864. this._depthRenderer = null;
  17865. };
  17866. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17867. if (ratio === void 0) { ratio = 1; }
  17868. if (this._geometryBufferRenderer) {
  17869. return this._geometryBufferRenderer;
  17870. }
  17871. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17872. if (!this._geometryBufferRenderer.isSupported) {
  17873. this._geometryBufferRenderer = null;
  17874. }
  17875. return this._geometryBufferRenderer;
  17876. };
  17877. Scene.prototype.disableGeometryBufferRenderer = function () {
  17878. if (!this._geometryBufferRenderer) {
  17879. return;
  17880. }
  17881. this._geometryBufferRenderer.dispose();
  17882. this._geometryBufferRenderer = null;
  17883. };
  17884. Scene.prototype.freezeMaterials = function () {
  17885. for (var i = 0; i < this.materials.length; i++) {
  17886. this.materials[i].freeze();
  17887. }
  17888. };
  17889. Scene.prototype.unfreezeMaterials = function () {
  17890. for (var i = 0; i < this.materials.length; i++) {
  17891. this.materials[i].unfreeze();
  17892. }
  17893. };
  17894. Scene.prototype.dispose = function () {
  17895. this.beforeRender = null;
  17896. this.afterRender = null;
  17897. this.skeletons = [];
  17898. this.morphTargetManagers = [];
  17899. this.importedMeshesFiles = new Array();
  17900. if (this._depthRenderer) {
  17901. this._depthRenderer.dispose();
  17902. }
  17903. // Smart arrays
  17904. if (this.activeCamera) {
  17905. this.activeCamera._activeMeshes.dispose();
  17906. this.activeCamera = null;
  17907. }
  17908. this._activeMeshes.dispose();
  17909. this._renderingManager.dispose();
  17910. this._processedMaterials.dispose();
  17911. this._activeParticleSystems.dispose();
  17912. this._activeSkeletons.dispose();
  17913. this._softwareSkinnedMeshes.dispose();
  17914. if (this._boundingBoxRenderer) {
  17915. this._boundingBoxRenderer.dispose();
  17916. }
  17917. this._meshesForIntersections.dispose();
  17918. this._toBeDisposed.dispose();
  17919. // Debug layer
  17920. if (this._debugLayer) {
  17921. this._debugLayer.hide();
  17922. }
  17923. // Events
  17924. this.onDisposeObservable.notifyObservers(this);
  17925. this.onDisposeObservable.clear();
  17926. this.onBeforeRenderObservable.clear();
  17927. this.onAfterRenderObservable.clear();
  17928. this.detachControl();
  17929. // Release sounds & sounds tracks
  17930. if (BABYLON.AudioEngine) {
  17931. this.disposeSounds();
  17932. }
  17933. // Detach cameras
  17934. var canvas = this._engine.getRenderingCanvas();
  17935. var index;
  17936. for (index = 0; index < this.cameras.length; index++) {
  17937. this.cameras[index].detachControl(canvas);
  17938. }
  17939. // Release lights
  17940. while (this.lights.length) {
  17941. this.lights[0].dispose();
  17942. }
  17943. // Release meshes
  17944. while (this.meshes.length) {
  17945. this.meshes[0].dispose(true);
  17946. }
  17947. // Release cameras
  17948. while (this.cameras.length) {
  17949. this.cameras[0].dispose();
  17950. }
  17951. // Release materials
  17952. while (this.materials.length) {
  17953. this.materials[0].dispose();
  17954. }
  17955. // Release particles
  17956. while (this.particleSystems.length) {
  17957. this.particleSystems[0].dispose();
  17958. }
  17959. // Release sprites
  17960. while (this.spriteManagers.length) {
  17961. this.spriteManagers[0].dispose();
  17962. }
  17963. // Release layers
  17964. while (this.layers.length) {
  17965. this.layers[0].dispose();
  17966. }
  17967. while (this.highlightLayers.length) {
  17968. this.highlightLayers[0].dispose();
  17969. }
  17970. // Release textures
  17971. while (this.textures.length) {
  17972. this.textures[0].dispose();
  17973. }
  17974. // Release UBO
  17975. this._sceneUbo.dispose();
  17976. // Post-processes
  17977. this.postProcessManager.dispose();
  17978. // Physics
  17979. if (this._physicsEngine) {
  17980. this.disablePhysicsEngine();
  17981. }
  17982. // Remove from engine
  17983. index = this._engine.scenes.indexOf(this);
  17984. if (index > -1) {
  17985. this._engine.scenes.splice(index, 1);
  17986. }
  17987. this._engine.wipeCaches();
  17988. this._engine = null;
  17989. };
  17990. Object.defineProperty(Scene.prototype, "isDisposed", {
  17991. get: function () {
  17992. return !this._engine;
  17993. },
  17994. enumerable: true,
  17995. configurable: true
  17996. });
  17997. // Release sounds & sounds tracks
  17998. Scene.prototype.disposeSounds = function () {
  17999. this.mainSoundTrack.dispose();
  18000. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18001. this.soundTracks[scIndex].dispose();
  18002. }
  18003. };
  18004. // Octrees
  18005. Scene.prototype.getWorldExtends = function () {
  18006. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18007. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18008. for (var index = 0; index < this.meshes.length; index++) {
  18009. var mesh = this.meshes[index];
  18010. mesh.computeWorldMatrix(true);
  18011. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18012. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18013. BABYLON.Tools.CheckExtends(minBox, min, max);
  18014. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18015. }
  18016. return {
  18017. min: min,
  18018. max: max
  18019. };
  18020. };
  18021. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18022. if (maxCapacity === void 0) { maxCapacity = 64; }
  18023. if (maxDepth === void 0) { maxDepth = 2; }
  18024. if (!this._selectionOctree) {
  18025. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18026. }
  18027. var worldExtends = this.getWorldExtends();
  18028. // Update octree
  18029. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18030. return this._selectionOctree;
  18031. };
  18032. // Picking
  18033. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18034. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18035. var engine = this._engine;
  18036. if (!camera) {
  18037. if (!this.activeCamera)
  18038. throw new Error("Active camera not set");
  18039. camera = this.activeCamera;
  18040. }
  18041. var cameraViewport = camera.viewport;
  18042. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18043. // Moving coordinates to local viewport world
  18044. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18045. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18046. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18047. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18048. };
  18049. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18050. if (!BABYLON.PickingInfo) {
  18051. return null;
  18052. }
  18053. var engine = this._engine;
  18054. if (!camera) {
  18055. if (!this.activeCamera)
  18056. throw new Error("Active camera not set");
  18057. camera = this.activeCamera;
  18058. }
  18059. var cameraViewport = camera.viewport;
  18060. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18061. var identity = BABYLON.Matrix.Identity();
  18062. // Moving coordinates to local viewport world
  18063. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18064. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18065. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18066. };
  18067. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18068. if (!BABYLON.PickingInfo) {
  18069. return null;
  18070. }
  18071. var pickingInfo = null;
  18072. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18073. var mesh = this.meshes[meshIndex];
  18074. if (predicate) {
  18075. if (!predicate(mesh)) {
  18076. continue;
  18077. }
  18078. }
  18079. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18080. continue;
  18081. }
  18082. var world = mesh.getWorldMatrix();
  18083. var ray = rayFunction(world);
  18084. var result = mesh.intersects(ray, fastCheck);
  18085. if (!result || !result.hit)
  18086. continue;
  18087. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18088. continue;
  18089. pickingInfo = result;
  18090. if (fastCheck) {
  18091. break;
  18092. }
  18093. }
  18094. return pickingInfo || new BABYLON.PickingInfo();
  18095. };
  18096. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18097. if (!BABYLON.PickingInfo) {
  18098. return null;
  18099. }
  18100. var pickingInfos = new Array();
  18101. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18102. var mesh = this.meshes[meshIndex];
  18103. if (predicate) {
  18104. if (!predicate(mesh)) {
  18105. continue;
  18106. }
  18107. }
  18108. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18109. continue;
  18110. }
  18111. var world = mesh.getWorldMatrix();
  18112. var ray = rayFunction(world);
  18113. var result = mesh.intersects(ray, false);
  18114. if (!result || !result.hit)
  18115. continue;
  18116. pickingInfos.push(result);
  18117. }
  18118. return pickingInfos;
  18119. };
  18120. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18121. if (!BABYLON.PickingInfo) {
  18122. return null;
  18123. }
  18124. var pickingInfo = null;
  18125. camera = camera || this.activeCamera;
  18126. if (this.spriteManagers.length > 0) {
  18127. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18128. var spriteManager = this.spriteManagers[spriteIndex];
  18129. if (!spriteManager.isPickable) {
  18130. continue;
  18131. }
  18132. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18133. if (!result || !result.hit)
  18134. continue;
  18135. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18136. continue;
  18137. pickingInfo = result;
  18138. if (fastCheck) {
  18139. break;
  18140. }
  18141. }
  18142. }
  18143. return pickingInfo || new BABYLON.PickingInfo();
  18144. };
  18145. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18146. /// <param name="x">X position on screen</param>
  18147. /// <param name="y">Y position on screen</param>
  18148. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  18149. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18150. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18151. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18152. var _this = this;
  18153. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18154. };
  18155. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18156. /// <param name="x">X position on screen</param>
  18157. /// <param name="y">Y position on screen</param>
  18158. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  18159. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18160. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18161. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18162. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18163. };
  18164. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18165. var _this = this;
  18166. return this._internalPick(function (world) {
  18167. if (!_this._pickWithRayInverseMatrix) {
  18168. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18169. }
  18170. world.invertToRef(_this._pickWithRayInverseMatrix);
  18171. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18172. }, predicate, fastCheck);
  18173. };
  18174. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18175. /// <param name="x">X position on screen</param>
  18176. /// <param name="y">Y position on screen</param>
  18177. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  18178. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18179. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18180. var _this = this;
  18181. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18182. };
  18183. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18184. /// <param name="ray">Ray to use</param>
  18185. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  18186. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18187. var _this = this;
  18188. return this._internalMultiPick(function (world) {
  18189. if (!_this._pickWithRayInverseMatrix) {
  18190. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18191. }
  18192. world.invertToRef(_this._pickWithRayInverseMatrix);
  18193. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18194. }, predicate);
  18195. };
  18196. Scene.prototype.setPointerOverMesh = function (mesh) {
  18197. if (this._pointerOverMesh === mesh) {
  18198. return;
  18199. }
  18200. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18201. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18202. }
  18203. this._pointerOverMesh = mesh;
  18204. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18205. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18206. }
  18207. };
  18208. Scene.prototype.getPointerOverMesh = function () {
  18209. return this._pointerOverMesh;
  18210. };
  18211. Scene.prototype.setPointerOverSprite = function (sprite) {
  18212. if (this._pointerOverSprite === sprite) {
  18213. return;
  18214. }
  18215. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18216. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18217. }
  18218. this._pointerOverSprite = sprite;
  18219. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18220. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18221. }
  18222. };
  18223. Scene.prototype.getPointerOverSprite = function () {
  18224. return this._pointerOverSprite;
  18225. };
  18226. // Physics
  18227. Scene.prototype.getPhysicsEngine = function () {
  18228. return this._physicsEngine;
  18229. };
  18230. /**
  18231. * Enables physics to the current scene
  18232. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18233. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18234. * @return {boolean} was the physics engine initialized
  18235. */
  18236. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18237. if (this._physicsEngine) {
  18238. return true;
  18239. }
  18240. try {
  18241. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18242. return true;
  18243. }
  18244. catch (e) {
  18245. BABYLON.Tools.Error(e.message);
  18246. return false;
  18247. }
  18248. };
  18249. Scene.prototype.disablePhysicsEngine = function () {
  18250. if (!this._physicsEngine) {
  18251. return;
  18252. }
  18253. this._physicsEngine.dispose();
  18254. this._physicsEngine = undefined;
  18255. };
  18256. Scene.prototype.isPhysicsEnabled = function () {
  18257. return this._physicsEngine !== undefined;
  18258. };
  18259. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18260. var mesh = compound.parts[0].mesh;
  18261. mesh.physicsImpostor.dispose();
  18262. mesh.physicsImpostor = null;
  18263. };
  18264. // Misc.
  18265. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18266. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18267. // Light
  18268. if (this.lights.length === 0) {
  18269. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18270. }
  18271. // Camera
  18272. if (!this.activeCamera) {
  18273. var worldExtends = this.getWorldExtends();
  18274. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18275. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18276. var camera;
  18277. var radius = worldSize.length() * 1.5;
  18278. if (createArcRotateCamera) {
  18279. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18280. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18281. arcRotateCamera.wheelPrecision = 100 / radius;
  18282. camera = arcRotateCamera;
  18283. }
  18284. else {
  18285. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18286. freeCamera.setTarget(worldCenter);
  18287. camera = freeCamera;
  18288. }
  18289. camera.minZ = radius * 0.01;
  18290. camera.maxZ = radius * 100;
  18291. camera.speed = radius * 0.2;
  18292. this.activeCamera = camera;
  18293. }
  18294. };
  18295. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18296. if (pbr === void 0) { pbr = false; }
  18297. if (environmentTexture) {
  18298. this.environmentTexture = environmentTexture;
  18299. }
  18300. if (!this.environmentTexture) {
  18301. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18302. return;
  18303. }
  18304. if (!this.environmentTexture) {
  18305. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18306. return;
  18307. }
  18308. // Skybox
  18309. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18310. if (pbr) {
  18311. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18312. hdrSkyboxMaterial.backFaceCulling = false;
  18313. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18314. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18315. hdrSkyboxMaterial.microSurface = 1.0;
  18316. hdrSkyboxMaterial.disableLighting = true;
  18317. hdrSkybox.infiniteDistance = true;
  18318. hdrSkybox.material = hdrSkyboxMaterial;
  18319. }
  18320. else {
  18321. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18322. skyboxMaterial.backFaceCulling = false;
  18323. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18324. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18325. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18326. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18327. skyboxMaterial.disableLighting = true;
  18328. hdrSkybox.infiniteDistance = true;
  18329. hdrSkybox.material = skyboxMaterial;
  18330. }
  18331. return hdrSkybox;
  18332. };
  18333. // Tags
  18334. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18335. if (tagsQuery === undefined) {
  18336. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18337. return list;
  18338. }
  18339. var listByTags = [];
  18340. forEach = forEach || (function (item) { return; });
  18341. for (var i in list) {
  18342. var item = list[i];
  18343. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18344. listByTags.push(item);
  18345. forEach(item);
  18346. }
  18347. }
  18348. return listByTags;
  18349. };
  18350. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18351. return this._getByTags(this.meshes, tagsQuery, forEach);
  18352. };
  18353. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18354. return this._getByTags(this.cameras, tagsQuery, forEach);
  18355. };
  18356. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18357. return this._getByTags(this.lights, tagsQuery, forEach);
  18358. };
  18359. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18360. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18361. };
  18362. /**
  18363. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18364. * This allowed control for front to back rendering or reversly depending of the special needs.
  18365. *
  18366. * @param renderingGroupId The rendering group id corresponding to its index
  18367. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18368. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18369. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18370. */
  18371. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18372. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18373. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18374. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18375. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18376. };
  18377. /**
  18378. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18379. *
  18380. * @param renderingGroupId The rendering group id corresponding to its index
  18381. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18382. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18383. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18384. */
  18385. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18386. if (depth === void 0) { depth = true; }
  18387. if (stencil === void 0) { stencil = true; }
  18388. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18389. };
  18390. /**
  18391. * Will flag all materials as dirty to trigger new shader compilation
  18392. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18393. */
  18394. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18395. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18396. var material = _a[_i];
  18397. if (predicate && !predicate(material)) {
  18398. continue;
  18399. }
  18400. material.markAsDirty(flag);
  18401. }
  18402. };
  18403. return Scene;
  18404. }());
  18405. // Statics
  18406. Scene._FOGMODE_NONE = 0;
  18407. Scene._FOGMODE_EXP = 1;
  18408. Scene._FOGMODE_EXP2 = 2;
  18409. Scene._FOGMODE_LINEAR = 3;
  18410. Scene.MinDeltaTime = 1.0;
  18411. Scene.MaxDeltaTime = 1000.0;
  18412. Scene.DragMovementThreshold = 10; // in pixels
  18413. Scene.LongPressDelay = 500; // in milliseconds
  18414. Scene.DoubleClickDelay = 300; // in milliseconds
  18415. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18416. BABYLON.Scene = Scene;
  18417. })(BABYLON || (BABYLON = {}));
  18418. //# sourceMappingURL=babylon.scene.js.map
  18419. var BABYLON;
  18420. (function (BABYLON) {
  18421. var Buffer = (function () {
  18422. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18423. if (engine instanceof BABYLON.Mesh) {
  18424. this._engine = engine.getScene().getEngine();
  18425. }
  18426. else {
  18427. this._engine = engine;
  18428. }
  18429. this._updatable = updatable;
  18430. this._data = data;
  18431. this._strideSize = stride;
  18432. if (!postponeInternalCreation) {
  18433. this.create();
  18434. }
  18435. this._instanced = instanced;
  18436. }
  18437. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18438. // a lot of these parameters are ignored as they are overriden by the buffer
  18439. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18440. };
  18441. // Properties
  18442. Buffer.prototype.isUpdatable = function () {
  18443. return this._updatable;
  18444. };
  18445. Buffer.prototype.getData = function () {
  18446. return this._data;
  18447. };
  18448. Buffer.prototype.getBuffer = function () {
  18449. return this._buffer;
  18450. };
  18451. Buffer.prototype.getStrideSize = function () {
  18452. return this._strideSize;
  18453. };
  18454. Buffer.prototype.getIsInstanced = function () {
  18455. return this._instanced;
  18456. };
  18457. // Methods
  18458. Buffer.prototype.create = function (data) {
  18459. if (!data && this._buffer) {
  18460. return; // nothing to do
  18461. }
  18462. data = data || this._data;
  18463. if (!this._buffer) {
  18464. if (this._updatable) {
  18465. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18466. this._data = data;
  18467. }
  18468. else {
  18469. this._buffer = this._engine.createVertexBuffer(data);
  18470. }
  18471. }
  18472. else if (this._updatable) {
  18473. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18474. this._data = data;
  18475. }
  18476. };
  18477. Buffer.prototype.update = function (data) {
  18478. this.create(data);
  18479. };
  18480. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18481. if (!this._buffer) {
  18482. return;
  18483. }
  18484. if (this._updatable) {
  18485. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18486. this._data = null;
  18487. }
  18488. };
  18489. Buffer.prototype.dispose = function () {
  18490. if (!this._buffer) {
  18491. return;
  18492. }
  18493. if (this._engine._releaseBuffer(this._buffer)) {
  18494. this._buffer = null;
  18495. }
  18496. };
  18497. return Buffer;
  18498. }());
  18499. BABYLON.Buffer = Buffer;
  18500. })(BABYLON || (BABYLON = {}));
  18501. //# sourceMappingURL=babylon.buffer.js.map
  18502. var BABYLON;
  18503. (function (BABYLON) {
  18504. var VertexBuffer = (function () {
  18505. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18506. if (!stride) {
  18507. // Deduce stride from kind
  18508. switch (kind) {
  18509. case VertexBuffer.PositionKind:
  18510. stride = 3;
  18511. break;
  18512. case VertexBuffer.NormalKind:
  18513. stride = 3;
  18514. break;
  18515. case VertexBuffer.UVKind:
  18516. case VertexBuffer.UV2Kind:
  18517. case VertexBuffer.UV3Kind:
  18518. case VertexBuffer.UV4Kind:
  18519. case VertexBuffer.UV5Kind:
  18520. case VertexBuffer.UV6Kind:
  18521. stride = 2;
  18522. break;
  18523. case VertexBuffer.TangentKind:
  18524. case VertexBuffer.ColorKind:
  18525. stride = 4;
  18526. break;
  18527. case VertexBuffer.MatricesIndicesKind:
  18528. case VertexBuffer.MatricesIndicesExtraKind:
  18529. stride = 4;
  18530. break;
  18531. case VertexBuffer.MatricesWeightsKind:
  18532. case VertexBuffer.MatricesWeightsExtraKind:
  18533. stride = 4;
  18534. break;
  18535. }
  18536. }
  18537. if (data instanceof BABYLON.Buffer) {
  18538. if (!stride) {
  18539. stride = data.getStrideSize();
  18540. }
  18541. this._buffer = data;
  18542. this._ownsBuffer = false;
  18543. }
  18544. else {
  18545. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18546. this._ownsBuffer = true;
  18547. }
  18548. this._stride = stride;
  18549. this._offset = offset ? offset : 0;
  18550. this._size = size ? size : stride;
  18551. this._kind = kind;
  18552. }
  18553. /**
  18554. * Returns the kind of the VertexBuffer (string).
  18555. */
  18556. VertexBuffer.prototype.getKind = function () {
  18557. return this._kind;
  18558. };
  18559. // Properties
  18560. /**
  18561. * Boolean : is the VertexBuffer updatable ?
  18562. */
  18563. VertexBuffer.prototype.isUpdatable = function () {
  18564. return this._buffer.isUpdatable();
  18565. };
  18566. /**
  18567. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18568. */
  18569. VertexBuffer.prototype.getData = function () {
  18570. return this._buffer.getData();
  18571. };
  18572. /**
  18573. * Returns the WebGLBuffer associated to the VertexBuffer.
  18574. */
  18575. VertexBuffer.prototype.getBuffer = function () {
  18576. return this._buffer.getBuffer();
  18577. };
  18578. /**
  18579. * Returns the stride of the VertexBuffer (integer).
  18580. */
  18581. VertexBuffer.prototype.getStrideSize = function () {
  18582. return this._stride;
  18583. };
  18584. /**
  18585. * Returns the offset (integer).
  18586. */
  18587. VertexBuffer.prototype.getOffset = function () {
  18588. return this._offset;
  18589. };
  18590. /**
  18591. * Returns the VertexBuffer total size (integer).
  18592. */
  18593. VertexBuffer.prototype.getSize = function () {
  18594. return this._size;
  18595. };
  18596. /**
  18597. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18598. */
  18599. VertexBuffer.prototype.getIsInstanced = function () {
  18600. return this._buffer.getIsInstanced();
  18601. };
  18602. // Methods
  18603. /**
  18604. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18605. * Returns the created WebGLBuffer.
  18606. */
  18607. VertexBuffer.prototype.create = function (data) {
  18608. return this._buffer.create(data);
  18609. };
  18610. /**
  18611. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18612. * Returns the updated WebGLBuffer.
  18613. */
  18614. VertexBuffer.prototype.update = function (data) {
  18615. return this._buffer.update(data);
  18616. };
  18617. /**
  18618. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18619. * Returns the directly updated WebGLBuffer.
  18620. */
  18621. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18622. return this._buffer.updateDirectly(data, offset);
  18623. };
  18624. /**
  18625. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18626. */
  18627. VertexBuffer.prototype.dispose = function () {
  18628. if (this._ownsBuffer) {
  18629. this._buffer.dispose();
  18630. }
  18631. };
  18632. Object.defineProperty(VertexBuffer, "PositionKind", {
  18633. get: function () {
  18634. return VertexBuffer._PositionKind;
  18635. },
  18636. enumerable: true,
  18637. configurable: true
  18638. });
  18639. Object.defineProperty(VertexBuffer, "NormalKind", {
  18640. get: function () {
  18641. return VertexBuffer._NormalKind;
  18642. },
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. Object.defineProperty(VertexBuffer, "TangentKind", {
  18647. get: function () {
  18648. return VertexBuffer._TangentKind;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. Object.defineProperty(VertexBuffer, "UVKind", {
  18654. get: function () {
  18655. return VertexBuffer._UVKind;
  18656. },
  18657. enumerable: true,
  18658. configurable: true
  18659. });
  18660. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18661. get: function () {
  18662. return VertexBuffer._UV2Kind;
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18668. get: function () {
  18669. return VertexBuffer._UV3Kind;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18675. get: function () {
  18676. return VertexBuffer._UV4Kind;
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18682. get: function () {
  18683. return VertexBuffer._UV5Kind;
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18689. get: function () {
  18690. return VertexBuffer._UV6Kind;
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(VertexBuffer, "ColorKind", {
  18696. get: function () {
  18697. return VertexBuffer._ColorKind;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18703. get: function () {
  18704. return VertexBuffer._MatricesIndicesKind;
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18710. get: function () {
  18711. return VertexBuffer._MatricesWeightsKind;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18717. get: function () {
  18718. return VertexBuffer._MatricesIndicesExtraKind;
  18719. },
  18720. enumerable: true,
  18721. configurable: true
  18722. });
  18723. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18724. get: function () {
  18725. return VertexBuffer._MatricesWeightsExtraKind;
  18726. },
  18727. enumerable: true,
  18728. configurable: true
  18729. });
  18730. return VertexBuffer;
  18731. }());
  18732. // Enums
  18733. VertexBuffer._PositionKind = "position";
  18734. VertexBuffer._NormalKind = "normal";
  18735. VertexBuffer._TangentKind = "tangent";
  18736. VertexBuffer._UVKind = "uv";
  18737. VertexBuffer._UV2Kind = "uv2";
  18738. VertexBuffer._UV3Kind = "uv3";
  18739. VertexBuffer._UV4Kind = "uv4";
  18740. VertexBuffer._UV5Kind = "uv5";
  18741. VertexBuffer._UV6Kind = "uv6";
  18742. VertexBuffer._ColorKind = "color";
  18743. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18744. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18745. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18746. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18747. BABYLON.VertexBuffer = VertexBuffer;
  18748. })(BABYLON || (BABYLON = {}));
  18749. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18750. var BABYLON;
  18751. (function (BABYLON) {
  18752. var BaseTexture = (function () {
  18753. function BaseTexture(scene) {
  18754. this._hasAlpha = false;
  18755. this.getAlphaFromRGB = false;
  18756. this.level = 1;
  18757. this.coordinatesIndex = 0;
  18758. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18759. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18760. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18761. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18762. this.isCube = false;
  18763. this.isRenderTarget = false;
  18764. this.animations = new Array();
  18765. /**
  18766. * An event triggered when the texture is disposed.
  18767. * @type {BABYLON.Observable}
  18768. */
  18769. this.onDisposeObservable = new BABYLON.Observable();
  18770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18771. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18772. this._scene.textures.push(this);
  18773. this._uid = null;
  18774. }
  18775. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18776. get: function () {
  18777. return this._hasAlpha;
  18778. },
  18779. set: function (value) {
  18780. if (this._hasAlpha === value) {
  18781. return;
  18782. }
  18783. this._hasAlpha = value;
  18784. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18785. },
  18786. enumerable: true,
  18787. configurable: true
  18788. });
  18789. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18790. get: function () {
  18791. return this._coordinatesMode;
  18792. },
  18793. set: function (value) {
  18794. if (this._coordinatesMode === value) {
  18795. return;
  18796. }
  18797. this._coordinatesMode = value;
  18798. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. Object.defineProperty(BaseTexture.prototype, "uid", {
  18804. get: function () {
  18805. if (!this._uid) {
  18806. this._uid = BABYLON.Tools.RandomId();
  18807. }
  18808. return this._uid;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. BaseTexture.prototype.toString = function () {
  18814. return this.name;
  18815. };
  18816. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18817. set: function (callback) {
  18818. if (this._onDisposeObserver) {
  18819. this.onDisposeObservable.remove(this._onDisposeObserver);
  18820. }
  18821. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18827. get: function () {
  18828. return true;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. BaseTexture.prototype.getScene = function () {
  18834. return this._scene;
  18835. };
  18836. BaseTexture.prototype.getTextureMatrix = function () {
  18837. return null;
  18838. };
  18839. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18840. return null;
  18841. };
  18842. BaseTexture.prototype.getInternalTexture = function () {
  18843. return this._texture;
  18844. };
  18845. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18846. return !this.isBlocking || this.isReady();
  18847. };
  18848. BaseTexture.prototype.isReady = function () {
  18849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18850. this.delayLoad();
  18851. return false;
  18852. }
  18853. if (this._texture) {
  18854. return this._texture.isReady;
  18855. }
  18856. return false;
  18857. };
  18858. BaseTexture.prototype.getSize = function () {
  18859. if (this._texture._width) {
  18860. return new BABYLON.Size(this._texture._width, this._texture._height);
  18861. }
  18862. if (this._texture._size) {
  18863. return new BABYLON.Size(this._texture._size, this._texture._size);
  18864. }
  18865. return BABYLON.Size.Zero();
  18866. };
  18867. BaseTexture.prototype.getBaseSize = function () {
  18868. if (!this.isReady() || !this._texture)
  18869. return BABYLON.Size.Zero();
  18870. if (this._texture._size) {
  18871. return new BABYLON.Size(this._texture._size, this._texture._size);
  18872. }
  18873. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18874. };
  18875. BaseTexture.prototype.scale = function (ratio) {
  18876. };
  18877. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18878. get: function () {
  18879. return false;
  18880. },
  18881. enumerable: true,
  18882. configurable: true
  18883. });
  18884. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18885. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18886. for (var index = 0; index < texturesCache.length; index++) {
  18887. var texturesCacheEntry = texturesCache[index];
  18888. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18889. texturesCache.splice(index, 1);
  18890. return;
  18891. }
  18892. }
  18893. };
  18894. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18895. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18896. for (var index = 0; index < texturesCache.length; index++) {
  18897. var texturesCacheEntry = texturesCache[index];
  18898. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18899. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18900. texturesCacheEntry.references++;
  18901. return texturesCacheEntry;
  18902. }
  18903. }
  18904. }
  18905. return null;
  18906. };
  18907. BaseTexture.prototype.delayLoad = function () {
  18908. };
  18909. BaseTexture.prototype.clone = function () {
  18910. return null;
  18911. };
  18912. BaseTexture.prototype.releaseInternalTexture = function () {
  18913. if (this._texture) {
  18914. this._scene.getEngine().releaseInternalTexture(this._texture);
  18915. delete this._texture;
  18916. }
  18917. };
  18918. BaseTexture.prototype.dispose = function () {
  18919. // Animations
  18920. this.getScene().stopAnimation(this);
  18921. // Remove from scene
  18922. this._scene._removePendingData(this);
  18923. var index = this._scene.textures.indexOf(this);
  18924. if (index >= 0) {
  18925. this._scene.textures.splice(index, 1);
  18926. }
  18927. if (this._texture === undefined) {
  18928. return;
  18929. }
  18930. // Release
  18931. this.releaseInternalTexture();
  18932. // Callback
  18933. this.onDisposeObservable.notifyObservers(this);
  18934. this.onDisposeObservable.clear();
  18935. };
  18936. BaseTexture.prototype.serialize = function () {
  18937. if (!this.name) {
  18938. return null;
  18939. }
  18940. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18941. // Animations
  18942. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18943. return serializationObject;
  18944. };
  18945. return BaseTexture;
  18946. }());
  18947. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18948. __decorate([
  18949. BABYLON.serialize()
  18950. ], BaseTexture.prototype, "name", void 0);
  18951. __decorate([
  18952. BABYLON.serialize("hasAlpha")
  18953. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18954. __decorate([
  18955. BABYLON.serialize()
  18956. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18957. __decorate([
  18958. BABYLON.serialize()
  18959. ], BaseTexture.prototype, "level", void 0);
  18960. __decorate([
  18961. BABYLON.serialize()
  18962. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18963. __decorate([
  18964. BABYLON.serialize("coordinatesMode")
  18965. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18966. __decorate([
  18967. BABYLON.serialize()
  18968. ], BaseTexture.prototype, "wrapU", void 0);
  18969. __decorate([
  18970. BABYLON.serialize()
  18971. ], BaseTexture.prototype, "wrapV", void 0);
  18972. __decorate([
  18973. BABYLON.serialize()
  18974. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18975. __decorate([
  18976. BABYLON.serialize()
  18977. ], BaseTexture.prototype, "isCube", void 0);
  18978. __decorate([
  18979. BABYLON.serialize()
  18980. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18981. BABYLON.BaseTexture = BaseTexture;
  18982. })(BABYLON || (BABYLON = {}));
  18983. //# sourceMappingURL=babylon.baseTexture.js.map
  18984. var BABYLON;
  18985. (function (BABYLON) {
  18986. var Texture = (function (_super) {
  18987. __extends(Texture, _super);
  18988. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18989. if (noMipmap === void 0) { noMipmap = false; }
  18990. if (invertY === void 0) { invertY = true; }
  18991. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18992. if (onLoad === void 0) { onLoad = null; }
  18993. if (onError === void 0) { onError = null; }
  18994. if (buffer === void 0) { buffer = null; }
  18995. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18996. var _this = _super.call(this, scene) || this;
  18997. _this.uOffset = 0;
  18998. _this.vOffset = 0;
  18999. _this.uScale = 1.0;
  19000. _this.vScale = 1.0;
  19001. _this.uAng = 0;
  19002. _this.vAng = 0;
  19003. _this.wAng = 0;
  19004. _this._isBlocking = true;
  19005. _this.name = url;
  19006. _this.url = url;
  19007. _this._noMipmap = noMipmap;
  19008. _this._invertY = invertY;
  19009. _this._samplingMode = samplingMode;
  19010. _this._buffer = buffer;
  19011. _this._deleteBuffer = deleteBuffer;
  19012. _this._format = format;
  19013. scene = _this.getScene();
  19014. if (!url) {
  19015. return _this;
  19016. }
  19017. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19018. var load = function () {
  19019. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19020. _this.onLoadObservable.notifyObservers(true);
  19021. }
  19022. if (onLoad) {
  19023. onLoad();
  19024. }
  19025. if (!_this.isBlocking) {
  19026. scene.resetCachedMaterial();
  19027. }
  19028. };
  19029. if (!_this._texture) {
  19030. if (!scene.useDelayedTextureLoading) {
  19031. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19032. if (deleteBuffer) {
  19033. delete _this._buffer;
  19034. }
  19035. }
  19036. else {
  19037. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19038. _this._delayedOnLoad = load;
  19039. _this._delayedOnError = onError;
  19040. }
  19041. }
  19042. else {
  19043. if (_this._texture.isReady) {
  19044. BABYLON.Tools.SetImmediate(function () { return load(); });
  19045. }
  19046. else {
  19047. _this._texture.onLoadedCallbacks.push(load);
  19048. }
  19049. }
  19050. return _this;
  19051. }
  19052. Object.defineProperty(Texture.prototype, "noMipmap", {
  19053. get: function () {
  19054. return this._noMipmap;
  19055. },
  19056. enumerable: true,
  19057. configurable: true
  19058. });
  19059. Object.defineProperty(Texture.prototype, "isBlocking", {
  19060. get: function () {
  19061. return this._isBlocking;
  19062. },
  19063. set: function (value) {
  19064. this._isBlocking = value;
  19065. },
  19066. enumerable: true,
  19067. configurable: true
  19068. });
  19069. Texture.prototype.delayLoad = function () {
  19070. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19071. return;
  19072. }
  19073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19074. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19075. if (!this._texture) {
  19076. 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);
  19077. if (this._deleteBuffer) {
  19078. delete this._buffer;
  19079. }
  19080. }
  19081. };
  19082. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19083. if (!this._texture) {
  19084. return;
  19085. }
  19086. this._samplingMode = samplingMode;
  19087. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19088. };
  19089. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19090. x *= this.uScale;
  19091. y *= this.vScale;
  19092. x -= 0.5 * this.uScale;
  19093. y -= 0.5 * this.vScale;
  19094. z -= 0.5;
  19095. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19096. t.x += 0.5 * this.uScale + this.uOffset;
  19097. t.y += 0.5 * this.vScale + this.vOffset;
  19098. t.z += 0.5;
  19099. };
  19100. Texture.prototype.getTextureMatrix = function () {
  19101. if (this.uOffset === this._cachedUOffset &&
  19102. this.vOffset === this._cachedVOffset &&
  19103. this.uScale === this._cachedUScale &&
  19104. this.vScale === this._cachedVScale &&
  19105. this.uAng === this._cachedUAng &&
  19106. this.vAng === this._cachedVAng &&
  19107. this.wAng === this._cachedWAng) {
  19108. return this._cachedTextureMatrix;
  19109. }
  19110. this._cachedUOffset = this.uOffset;
  19111. this._cachedVOffset = this.vOffset;
  19112. this._cachedUScale = this.uScale;
  19113. this._cachedVScale = this.vScale;
  19114. this._cachedUAng = this.uAng;
  19115. this._cachedVAng = this.vAng;
  19116. this._cachedWAng = this.wAng;
  19117. if (!this._cachedTextureMatrix) {
  19118. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19119. this._rowGenerationMatrix = new BABYLON.Matrix();
  19120. this._t0 = BABYLON.Vector3.Zero();
  19121. this._t1 = BABYLON.Vector3.Zero();
  19122. this._t2 = BABYLON.Vector3.Zero();
  19123. }
  19124. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19125. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19126. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19127. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19128. this._t1.subtractInPlace(this._t0);
  19129. this._t2.subtractInPlace(this._t0);
  19130. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19131. this._cachedTextureMatrix.m[0] = this._t1.x;
  19132. this._cachedTextureMatrix.m[1] = this._t1.y;
  19133. this._cachedTextureMatrix.m[2] = this._t1.z;
  19134. this._cachedTextureMatrix.m[4] = this._t2.x;
  19135. this._cachedTextureMatrix.m[5] = this._t2.y;
  19136. this._cachedTextureMatrix.m[6] = this._t2.z;
  19137. this._cachedTextureMatrix.m[8] = this._t0.x;
  19138. this._cachedTextureMatrix.m[9] = this._t0.y;
  19139. this._cachedTextureMatrix.m[10] = this._t0.z;
  19140. return this._cachedTextureMatrix;
  19141. };
  19142. Texture.prototype.getReflectionTextureMatrix = function () {
  19143. if (this.uOffset === this._cachedUOffset &&
  19144. this.vOffset === this._cachedVOffset &&
  19145. this.uScale === this._cachedUScale &&
  19146. this.vScale === this._cachedVScale &&
  19147. this.coordinatesMode === this._cachedCoordinatesMode) {
  19148. return this._cachedTextureMatrix;
  19149. }
  19150. if (!this._cachedTextureMatrix) {
  19151. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19152. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19153. }
  19154. this._cachedCoordinatesMode = this.coordinatesMode;
  19155. switch (this.coordinatesMode) {
  19156. case Texture.PLANAR_MODE:
  19157. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19158. this._cachedTextureMatrix[0] = this.uScale;
  19159. this._cachedTextureMatrix[5] = this.vScale;
  19160. this._cachedTextureMatrix[12] = this.uOffset;
  19161. this._cachedTextureMatrix[13] = this.vOffset;
  19162. break;
  19163. case Texture.PROJECTION_MODE:
  19164. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19165. this._projectionModeMatrix.m[0] = 0.5;
  19166. this._projectionModeMatrix.m[5] = -0.5;
  19167. this._projectionModeMatrix.m[10] = 0.0;
  19168. this._projectionModeMatrix.m[12] = 0.5;
  19169. this._projectionModeMatrix.m[13] = 0.5;
  19170. this._projectionModeMatrix.m[14] = 1.0;
  19171. this._projectionModeMatrix.m[15] = 1.0;
  19172. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19173. break;
  19174. default:
  19175. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19176. break;
  19177. }
  19178. return this._cachedTextureMatrix;
  19179. };
  19180. Texture.prototype.clone = function () {
  19181. var _this = this;
  19182. return BABYLON.SerializationHelper.Clone(function () {
  19183. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19184. }, this);
  19185. };
  19186. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19187. get: function () {
  19188. if (!this._onLoadObservarble) {
  19189. this._onLoadObservarble = new BABYLON.Observable();
  19190. }
  19191. return this._onLoadObservarble;
  19192. },
  19193. enumerable: true,
  19194. configurable: true
  19195. });
  19196. // Statics
  19197. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19198. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19199. if (onLoad === void 0) { onLoad = null; }
  19200. if (onError === void 0) { onError = null; }
  19201. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19202. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19203. };
  19204. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19205. if (parsedTexture.customType) {
  19206. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19207. // Update Sampling Mode
  19208. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19209. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19210. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19211. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19212. }
  19213. }
  19214. return parsedCustomTexture;
  19215. }
  19216. if (parsedTexture.isCube) {
  19217. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19218. }
  19219. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19220. return null;
  19221. }
  19222. var texture = BABYLON.SerializationHelper.Parse(function () {
  19223. if (parsedTexture.mirrorPlane) {
  19224. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19225. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19226. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19227. return mirrorTexture;
  19228. }
  19229. else if (parsedTexture.isRenderTarget) {
  19230. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19231. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19232. return renderTargetTexture;
  19233. }
  19234. else {
  19235. var texture;
  19236. if (parsedTexture.base64String) {
  19237. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19238. }
  19239. else {
  19240. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19241. }
  19242. return texture;
  19243. }
  19244. }, parsedTexture, scene);
  19245. // Update Sampling Mode
  19246. if (parsedTexture.samplingMode) {
  19247. var sampling = parsedTexture.samplingMode;
  19248. if (texture._samplingMode !== sampling) {
  19249. texture.updateSamplingMode(sampling);
  19250. }
  19251. }
  19252. // Animations
  19253. if (parsedTexture.animations) {
  19254. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19255. var parsedAnimation = parsedTexture.animations[animationIndex];
  19256. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19257. }
  19258. }
  19259. return texture;
  19260. };
  19261. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19262. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19263. if (noMipmap === void 0) { noMipmap = false; }
  19264. if (invertY === void 0) { invertY = true; }
  19265. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19266. if (onLoad === void 0) { onLoad = null; }
  19267. if (onError === void 0) { onError = null; }
  19268. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19269. if (name.substr(0, 5) !== "data:") {
  19270. name = "data:" + name;
  19271. }
  19272. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19273. };
  19274. return Texture;
  19275. }(BABYLON.BaseTexture));
  19276. // Constants
  19277. Texture.NEAREST_SAMPLINGMODE = 1;
  19278. Texture.BILINEAR_SAMPLINGMODE = 2;
  19279. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19280. Texture.EXPLICIT_MODE = 0;
  19281. Texture.SPHERICAL_MODE = 1;
  19282. Texture.PLANAR_MODE = 2;
  19283. Texture.CUBIC_MODE = 3;
  19284. Texture.PROJECTION_MODE = 4;
  19285. Texture.SKYBOX_MODE = 5;
  19286. Texture.INVCUBIC_MODE = 6;
  19287. Texture.EQUIRECTANGULAR_MODE = 7;
  19288. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19289. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19290. Texture.CLAMP_ADDRESSMODE = 0;
  19291. Texture.WRAP_ADDRESSMODE = 1;
  19292. Texture.MIRROR_ADDRESSMODE = 2;
  19293. __decorate([
  19294. BABYLON.serialize()
  19295. ], Texture.prototype, "url", void 0);
  19296. __decorate([
  19297. BABYLON.serialize()
  19298. ], Texture.prototype, "uOffset", void 0);
  19299. __decorate([
  19300. BABYLON.serialize()
  19301. ], Texture.prototype, "vOffset", void 0);
  19302. __decorate([
  19303. BABYLON.serialize()
  19304. ], Texture.prototype, "uScale", void 0);
  19305. __decorate([
  19306. BABYLON.serialize()
  19307. ], Texture.prototype, "vScale", void 0);
  19308. __decorate([
  19309. BABYLON.serialize()
  19310. ], Texture.prototype, "uAng", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], Texture.prototype, "vAng", void 0);
  19314. __decorate([
  19315. BABYLON.serialize()
  19316. ], Texture.prototype, "wAng", void 0);
  19317. __decorate([
  19318. BABYLON.serialize()
  19319. ], Texture.prototype, "isBlocking", null);
  19320. BABYLON.Texture = Texture;
  19321. })(BABYLON || (BABYLON = {}));
  19322. //# sourceMappingURL=babylon.texture.js.map
  19323. var BABYLON;
  19324. (function (BABYLON) {
  19325. var _InstancesBatch = (function () {
  19326. function _InstancesBatch() {
  19327. this.mustReturn = false;
  19328. this.visibleInstances = new Array();
  19329. this.renderSelf = new Array();
  19330. }
  19331. return _InstancesBatch;
  19332. }());
  19333. BABYLON._InstancesBatch = _InstancesBatch;
  19334. var Mesh = (function (_super) {
  19335. __extends(Mesh, _super);
  19336. /**
  19337. * @constructor
  19338. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19339. * @param {Scene} scene The scene to add this mesh to.
  19340. * @param {Node} parent The parent of this mesh, if it has one
  19341. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19342. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19343. * When false, achieved by calling a clone(), also passing False.
  19344. * This will make creation of children, recursive.
  19345. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19346. */
  19347. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19348. if (parent === void 0) { parent = null; }
  19349. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19350. var _this = _super.call(this, name, scene) || this;
  19351. // Events
  19352. /**
  19353. * An event triggered before rendering the mesh
  19354. * @type {BABYLON.Observable}
  19355. */
  19356. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19357. /**
  19358. * An event triggered after rendering the mesh
  19359. * @type {BABYLON.Observable}
  19360. */
  19361. _this.onAfterRenderObservable = new BABYLON.Observable();
  19362. /**
  19363. * An event triggered before drawing the mesh
  19364. * @type {BABYLON.Observable}
  19365. */
  19366. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19367. // Members
  19368. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19369. _this.instances = new Array();
  19370. _this._LODLevels = new Array();
  19371. _this._visibleInstances = {};
  19372. _this._renderIdForInstances = new Array();
  19373. _this._batchCache = new _InstancesBatch();
  19374. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19375. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19376. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19377. // Will be used to save a source mesh reference, If any
  19378. _this._source = null;
  19379. if (source) {
  19380. // Source mesh
  19381. _this._source = source;
  19382. // Geometry
  19383. if (source._geometry) {
  19384. source._geometry.applyToMesh(_this);
  19385. }
  19386. // Deep copy
  19387. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19388. // Parent
  19389. _this.parent = source.parent;
  19390. // Pivot
  19391. _this.setPivotMatrix(source.getPivotMatrix());
  19392. _this.id = name + "." + source.id;
  19393. // Material
  19394. _this.material = source.material;
  19395. var index;
  19396. if (!doNotCloneChildren) {
  19397. // Children
  19398. for (index = 0; index < scene.meshes.length; index++) {
  19399. var mesh = scene.meshes[index];
  19400. if (mesh.parent === source) {
  19401. // doNotCloneChildren is always going to be False
  19402. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19403. }
  19404. }
  19405. }
  19406. // Physics clone
  19407. var physicsEngine = _this.getScene().getPhysicsEngine();
  19408. if (clonePhysicsImpostor && physicsEngine) {
  19409. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19410. if (impostor) {
  19411. _this.physicsImpostor = impostor.clone(_this);
  19412. }
  19413. }
  19414. // Particles
  19415. for (index = 0; index < scene.particleSystems.length; index++) {
  19416. var system = scene.particleSystems[index];
  19417. if (system.emitter === source) {
  19418. system.clone(system.name, _this);
  19419. }
  19420. }
  19421. _this.computeWorldMatrix(true);
  19422. }
  19423. // Parent
  19424. if (parent !== null) {
  19425. _this.parent = parent;
  19426. }
  19427. return _this;
  19428. }
  19429. Object.defineProperty(Mesh, "FRONTSIDE", {
  19430. /**
  19431. * Mesh side orientation : usually the external or front surface
  19432. */
  19433. get: function () {
  19434. return Mesh._FRONTSIDE;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(Mesh, "BACKSIDE", {
  19440. /**
  19441. * Mesh side orientation : usually the internal or back surface
  19442. */
  19443. get: function () {
  19444. return Mesh._BACKSIDE;
  19445. },
  19446. enumerable: true,
  19447. configurable: true
  19448. });
  19449. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19450. /**
  19451. * Mesh side orientation : both internal and external or front and back surfaces
  19452. */
  19453. get: function () {
  19454. return Mesh._DOUBLESIDE;
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19460. /**
  19461. * Mesh side orientation : by default, `FRONTSIDE`
  19462. */
  19463. get: function () {
  19464. return Mesh._DEFAULTSIDE;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(Mesh, "NO_CAP", {
  19470. /**
  19471. * Mesh cap setting : no cap
  19472. */
  19473. get: function () {
  19474. return Mesh._NO_CAP;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(Mesh, "CAP_START", {
  19480. /**
  19481. * Mesh cap setting : one cap at the beginning of the mesh
  19482. */
  19483. get: function () {
  19484. return Mesh._CAP_START;
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. Object.defineProperty(Mesh, "CAP_END", {
  19490. /**
  19491. * Mesh cap setting : one cap at the end of the mesh
  19492. */
  19493. get: function () {
  19494. return Mesh._CAP_END;
  19495. },
  19496. enumerable: true,
  19497. configurable: true
  19498. });
  19499. Object.defineProperty(Mesh, "CAP_ALL", {
  19500. /**
  19501. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19502. */
  19503. get: function () {
  19504. return Mesh._CAP_ALL;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19510. set: function (callback) {
  19511. if (this._onBeforeDrawObserver) {
  19512. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19513. }
  19514. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19520. get: function () {
  19521. return this._morphTargetManager;
  19522. },
  19523. set: function (value) {
  19524. if (this._morphTargetManager === value) {
  19525. return;
  19526. }
  19527. this._morphTargetManager = value;
  19528. this._syncGeometryWithMorphTargetManager();
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(Mesh.prototype, "source", {
  19534. get: function () {
  19535. return this._source;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. // Methods
  19541. /**
  19542. * Returns the string "Mesh".
  19543. */
  19544. Mesh.prototype.getClassName = function () {
  19545. return "Mesh";
  19546. };
  19547. /**
  19548. * Returns a string.
  19549. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19550. */
  19551. Mesh.prototype.toString = function (fullDetails) {
  19552. var ret = _super.prototype.toString.call(this, fullDetails);
  19553. ret += ", n vertices: " + this.getTotalVertices();
  19554. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19555. if (this.animations) {
  19556. for (var i = 0; i < this.animations.length; i++) {
  19557. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19558. }
  19559. }
  19560. if (fullDetails) {
  19561. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19562. }
  19563. return ret;
  19564. };
  19565. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19566. /**
  19567. * True if the mesh has some Levels Of Details (LOD).
  19568. * Returns a boolean.
  19569. */
  19570. get: function () {
  19571. return this._LODLevels.length > 0;
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Mesh.prototype._sortLODLevels = function () {
  19577. this._LODLevels.sort(function (a, b) {
  19578. if (a.distance < b.distance) {
  19579. return 1;
  19580. }
  19581. if (a.distance > b.distance) {
  19582. return -1;
  19583. }
  19584. return 0;
  19585. });
  19586. };
  19587. /**
  19588. * Add a mesh as LOD level triggered at the given distance.
  19589. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19590. * @param {number} distance The distance from the center of the object to show this level
  19591. * @param {Mesh} mesh The mesh to be added as LOD level
  19592. * @return {Mesh} This mesh (for chaining)
  19593. */
  19594. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19595. if (mesh && mesh._masterMesh) {
  19596. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19597. return this;
  19598. }
  19599. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19600. this._LODLevels.push(level);
  19601. if (mesh) {
  19602. mesh._masterMesh = this;
  19603. }
  19604. this._sortLODLevels();
  19605. return this;
  19606. };
  19607. /**
  19608. * Returns the LOD level mesh at the passed distance or null if not found.
  19609. * It is related to the method `addLODLevel(distance, mesh)`.
  19610. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19611. * Returns an object Mesh or `null`.
  19612. */
  19613. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19614. for (var index = 0; index < this._LODLevels.length; index++) {
  19615. var level = this._LODLevels[index];
  19616. if (level.distance === distance) {
  19617. return level.mesh;
  19618. }
  19619. }
  19620. return null;
  19621. };
  19622. /**
  19623. * Remove a mesh from the LOD array
  19624. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19625. * @param {Mesh} mesh The mesh to be removed.
  19626. * @return {Mesh} This mesh (for chaining)
  19627. */
  19628. Mesh.prototype.removeLODLevel = function (mesh) {
  19629. for (var index = 0; index < this._LODLevels.length; index++) {
  19630. if (this._LODLevels[index].mesh === mesh) {
  19631. this._LODLevels.splice(index, 1);
  19632. if (mesh) {
  19633. mesh._masterMesh = null;
  19634. }
  19635. }
  19636. }
  19637. this._sortLODLevels();
  19638. return this;
  19639. };
  19640. /**
  19641. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19642. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19643. */
  19644. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19645. if (!this._LODLevels || this._LODLevels.length === 0) {
  19646. return this;
  19647. }
  19648. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19649. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19650. if (this.onLODLevelSelection) {
  19651. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19652. }
  19653. return this;
  19654. }
  19655. for (var index = 0; index < this._LODLevels.length; index++) {
  19656. var level = this._LODLevels[index];
  19657. if (level.distance < distanceToCamera) {
  19658. if (level.mesh) {
  19659. level.mesh._preActivate();
  19660. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19661. }
  19662. if (this.onLODLevelSelection) {
  19663. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19664. }
  19665. return level.mesh;
  19666. }
  19667. }
  19668. if (this.onLODLevelSelection) {
  19669. this.onLODLevelSelection(distanceToCamera, this, this);
  19670. }
  19671. return this;
  19672. };
  19673. Object.defineProperty(Mesh.prototype, "geometry", {
  19674. /**
  19675. * Returns the mesh internal Geometry object.
  19676. */
  19677. get: function () {
  19678. return this._geometry;
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. /**
  19684. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19685. */
  19686. Mesh.prototype.getTotalVertices = function () {
  19687. if (!this._geometry) {
  19688. return 0;
  19689. }
  19690. return this._geometry.getTotalVertices();
  19691. };
  19692. /**
  19693. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19694. * 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.
  19695. * You can force the copy with forceCopy === true
  19696. * Returns null if the mesh has no geometry or no vertex buffer.
  19697. * Possible `kind` values :
  19698. * - BABYLON.VertexBuffer.PositionKind
  19699. * - BABYLON.VertexBuffer.UVKind
  19700. * - BABYLON.VertexBuffer.UV2Kind
  19701. * - BABYLON.VertexBuffer.UV3Kind
  19702. * - BABYLON.VertexBuffer.UV4Kind
  19703. * - BABYLON.VertexBuffer.UV5Kind
  19704. * - BABYLON.VertexBuffer.UV6Kind
  19705. * - BABYLON.VertexBuffer.ColorKind
  19706. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19707. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19708. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19709. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19710. */
  19711. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19712. if (!this._geometry) {
  19713. return null;
  19714. }
  19715. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19716. };
  19717. /**
  19718. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19719. * Returns `undefined` if the mesh has no geometry.
  19720. * Possible `kind` values :
  19721. * - BABYLON.VertexBuffer.PositionKind
  19722. * - BABYLON.VertexBuffer.UVKind
  19723. * - BABYLON.VertexBuffer.UV2Kind
  19724. * - BABYLON.VertexBuffer.UV3Kind
  19725. * - BABYLON.VertexBuffer.UV4Kind
  19726. * - BABYLON.VertexBuffer.UV5Kind
  19727. * - BABYLON.VertexBuffer.UV6Kind
  19728. * - BABYLON.VertexBuffer.ColorKind
  19729. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19730. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19731. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19732. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19733. */
  19734. Mesh.prototype.getVertexBuffer = function (kind) {
  19735. if (!this._geometry) {
  19736. return undefined;
  19737. }
  19738. return this._geometry.getVertexBuffer(kind);
  19739. };
  19740. /**
  19741. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19742. * Possible `kind` values :
  19743. * - BABYLON.VertexBuffer.PositionKind
  19744. * - BABYLON.VertexBuffer.UVKind
  19745. * - BABYLON.VertexBuffer.UV2Kind
  19746. * - BABYLON.VertexBuffer.UV3Kind
  19747. * - BABYLON.VertexBuffer.UV4Kind
  19748. * - BABYLON.VertexBuffer.UV5Kind
  19749. * - BABYLON.VertexBuffer.UV6Kind
  19750. * - BABYLON.VertexBuffer.ColorKind
  19751. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19752. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19753. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19754. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19755. */
  19756. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19757. if (!this._geometry) {
  19758. if (this._delayInfo) {
  19759. return this._delayInfo.indexOf(kind) !== -1;
  19760. }
  19761. return false;
  19762. }
  19763. return this._geometry.isVerticesDataPresent(kind);
  19764. };
  19765. /**
  19766. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19767. * Possible `kind` values :
  19768. * - BABYLON.VertexBuffer.PositionKind
  19769. * - BABYLON.VertexBuffer.UVKind
  19770. * - BABYLON.VertexBuffer.UV2Kind
  19771. * - BABYLON.VertexBuffer.UV3Kind
  19772. * - BABYLON.VertexBuffer.UV4Kind
  19773. * - BABYLON.VertexBuffer.UV5Kind
  19774. * - BABYLON.VertexBuffer.UV6Kind
  19775. * - BABYLON.VertexBuffer.ColorKind
  19776. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19777. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19778. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19779. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19780. */
  19781. Mesh.prototype.getVerticesDataKinds = function () {
  19782. if (!this._geometry) {
  19783. var result = [];
  19784. if (this._delayInfo) {
  19785. this._delayInfo.forEach(function (kind, index, array) {
  19786. result.push(kind);
  19787. });
  19788. }
  19789. return result;
  19790. }
  19791. return this._geometry.getVerticesDataKinds();
  19792. };
  19793. /**
  19794. * Returns a positive integer : the total number of indices in this mesh geometry.
  19795. * Returns zero if the mesh has no geometry.
  19796. */
  19797. Mesh.prototype.getTotalIndices = function () {
  19798. if (!this._geometry) {
  19799. return 0;
  19800. }
  19801. return this._geometry.getTotalIndices();
  19802. };
  19803. /**
  19804. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19805. * 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.
  19806. * Returns an empty array if the mesh has no geometry.
  19807. */
  19808. Mesh.prototype.getIndices = function (copyWhenShared) {
  19809. if (!this._geometry) {
  19810. return [];
  19811. }
  19812. return this._geometry.getIndices(copyWhenShared);
  19813. };
  19814. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19815. get: function () {
  19816. return this._masterMesh !== null && this._masterMesh !== undefined;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. /**
  19822. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19823. */
  19824. Mesh.prototype.isReady = function () {
  19825. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19826. return false;
  19827. }
  19828. return _super.prototype.isReady.call(this);
  19829. };
  19830. /**
  19831. * Boolean : true if the mesh has been disposed.
  19832. */
  19833. Mesh.prototype.isDisposed = function () {
  19834. return this._isDisposed;
  19835. };
  19836. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19837. get: function () {
  19838. return this._sideOrientation;
  19839. },
  19840. /**
  19841. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19842. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19843. */
  19844. set: function (sideO) {
  19845. this._sideOrientation = sideO;
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19851. /**
  19852. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19853. * This property is pertinent only for updatable parametric shapes.
  19854. */
  19855. get: function () {
  19856. return this._areNormalsFrozen;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. /**
  19862. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19863. * It has no effect at all on other shapes.
  19864. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19865. * Returns the Mesh.
  19866. */
  19867. Mesh.prototype.freezeNormals = function () {
  19868. this._areNormalsFrozen = true;
  19869. return this;
  19870. };
  19871. /**
  19872. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19873. * It has no effect at all on other shapes.
  19874. * It reactivates the mesh normals computation if it was previously frozen.
  19875. * Returns the Mesh.
  19876. */
  19877. Mesh.prototype.unfreezeNormals = function () {
  19878. this._areNormalsFrozen = false;
  19879. return this;
  19880. };
  19881. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19882. /**
  19883. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19884. */
  19885. set: function (count) {
  19886. this._overridenInstanceCount = count;
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. // Methods
  19892. Mesh.prototype._preActivate = function () {
  19893. var sceneRenderId = this.getScene().getRenderId();
  19894. if (this._preActivateId === sceneRenderId) {
  19895. return this;
  19896. }
  19897. this._preActivateId = sceneRenderId;
  19898. this._visibleInstances = null;
  19899. return this;
  19900. };
  19901. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19902. if (this._visibleInstances) {
  19903. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19904. }
  19905. return this;
  19906. };
  19907. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19908. if (!this._visibleInstances) {
  19909. this._visibleInstances = {};
  19910. this._visibleInstances.defaultRenderId = renderId;
  19911. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19912. }
  19913. if (!this._visibleInstances[renderId]) {
  19914. this._visibleInstances[renderId] = new Array();
  19915. }
  19916. this._visibleInstances[renderId].push(instance);
  19917. return this;
  19918. };
  19919. /**
  19920. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19921. * This means the mesh underlying bounding box and sphere are recomputed.
  19922. * Returns the Mesh.
  19923. */
  19924. Mesh.prototype.refreshBoundingInfo = function () {
  19925. if (this._boundingInfo.isLocked) {
  19926. return;
  19927. }
  19928. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19929. if (data) {
  19930. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19931. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19932. }
  19933. if (this.subMeshes) {
  19934. for (var index = 0; index < this.subMeshes.length; index++) {
  19935. this.subMeshes[index].refreshBoundingInfo();
  19936. }
  19937. }
  19938. this._updateBoundingInfo();
  19939. return this;
  19940. };
  19941. Mesh.prototype._createGlobalSubMesh = function () {
  19942. var totalVertices = this.getTotalVertices();
  19943. if (!totalVertices || !this.getIndices()) {
  19944. return null;
  19945. }
  19946. this.releaseSubMeshes();
  19947. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19948. };
  19949. Mesh.prototype.subdivide = function (count) {
  19950. if (count < 1) {
  19951. return;
  19952. }
  19953. var totalIndices = this.getTotalIndices();
  19954. var subdivisionSize = (totalIndices / count) | 0;
  19955. var offset = 0;
  19956. // Ensure that subdivisionSize is a multiple of 3
  19957. while (subdivisionSize % 3 !== 0) {
  19958. subdivisionSize++;
  19959. }
  19960. this.releaseSubMeshes();
  19961. for (var index = 0; index < count; index++) {
  19962. if (offset >= totalIndices) {
  19963. break;
  19964. }
  19965. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19966. offset += subdivisionSize;
  19967. }
  19968. this.synchronizeInstances();
  19969. };
  19970. /**
  19971. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19972. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19973. * The `data` are either a numeric array either a Float32Array.
  19974. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19975. * 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).
  19976. * Note that a new underlying VertexBuffer object is created each call.
  19977. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19978. *
  19979. * Possible `kind` values :
  19980. * - BABYLON.VertexBuffer.PositionKind
  19981. * - BABYLON.VertexBuffer.UVKind
  19982. * - BABYLON.VertexBuffer.UV2Kind
  19983. * - BABYLON.VertexBuffer.UV3Kind
  19984. * - BABYLON.VertexBuffer.UV4Kind
  19985. * - BABYLON.VertexBuffer.UV5Kind
  19986. * - BABYLON.VertexBuffer.UV6Kind
  19987. * - BABYLON.VertexBuffer.ColorKind
  19988. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19989. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19990. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19991. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19992. *
  19993. * Returns the Mesh.
  19994. */
  19995. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19996. if (!this._geometry) {
  19997. var vertexData = new BABYLON.VertexData();
  19998. vertexData.set(data, kind);
  19999. var scene = this.getScene();
  20000. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20001. }
  20002. else {
  20003. this._geometry.setVerticesData(kind, data, updatable, stride);
  20004. }
  20005. return this;
  20006. };
  20007. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20008. if (updatable === void 0) { updatable = true; }
  20009. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20010. return;
  20011. }
  20012. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20013. };
  20014. /**
  20015. * Sets the mesh VertexBuffer.
  20016. * Returns the Mesh.
  20017. */
  20018. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20019. if (!this._geometry) {
  20020. var scene = this.getScene();
  20021. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20022. }
  20023. this._geometry.setVerticesBuffer(buffer);
  20024. return this;
  20025. };
  20026. /**
  20027. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20028. * If the mesh has no geometry, it is simply returned as it is.
  20029. * The `data` are either a numeric array either a Float32Array.
  20030. * No new underlying VertexBuffer object is created.
  20031. * 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.
  20032. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20033. *
  20034. * Possible `kind` values :
  20035. * - BABYLON.VertexBuffer.PositionKind
  20036. * - BABYLON.VertexBuffer.UVKind
  20037. * - BABYLON.VertexBuffer.UV2Kind
  20038. * - BABYLON.VertexBuffer.UV3Kind
  20039. * - BABYLON.VertexBuffer.UV4Kind
  20040. * - BABYLON.VertexBuffer.UV5Kind
  20041. * - BABYLON.VertexBuffer.UV6Kind
  20042. * - BABYLON.VertexBuffer.ColorKind
  20043. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20044. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20045. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20046. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20047. *
  20048. * Returns the Mesh.
  20049. */
  20050. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20051. if (!this._geometry) {
  20052. return;
  20053. }
  20054. if (!makeItUnique) {
  20055. this._geometry.updateVerticesData(kind, data, updateExtends);
  20056. }
  20057. else {
  20058. this.makeGeometryUnique();
  20059. this.updateVerticesData(kind, data, updateExtends, false);
  20060. }
  20061. return this;
  20062. };
  20063. /**
  20064. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20065. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20066. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20067. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20068. * Returns the Mesh.
  20069. */
  20070. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20071. if (computeNormals === void 0) { computeNormals = true; }
  20072. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20073. positionFunction(positions);
  20074. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20075. if (computeNormals) {
  20076. var indices = this.getIndices();
  20077. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20078. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20079. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20080. }
  20081. return this;
  20082. };
  20083. /**
  20084. * Creates a un-shared specific occurence of the geometry for the mesh.
  20085. * Returns the Mesh.
  20086. */
  20087. Mesh.prototype.makeGeometryUnique = function () {
  20088. if (!this._geometry) {
  20089. return;
  20090. }
  20091. var oldGeometry = this._geometry;
  20092. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20093. oldGeometry.releaseForMesh(this, true);
  20094. geometry.applyToMesh(this);
  20095. return this;
  20096. };
  20097. /**
  20098. * Sets the mesh indices.
  20099. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20100. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20101. * This method creates a new index buffer each call.
  20102. * Returns the Mesh.
  20103. */
  20104. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20105. if (!this._geometry) {
  20106. var vertexData = new BABYLON.VertexData();
  20107. vertexData.indices = indices;
  20108. var scene = this.getScene();
  20109. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20110. }
  20111. else {
  20112. this._geometry.setIndices(indices, totalVertices);
  20113. }
  20114. return this;
  20115. };
  20116. /**
  20117. * Invert the geometry to move from a right handed system to a left handed one.
  20118. * Returns the Mesh.
  20119. */
  20120. Mesh.prototype.toLeftHanded = function () {
  20121. if (!this._geometry) {
  20122. return;
  20123. }
  20124. this._geometry.toLeftHanded();
  20125. return this;
  20126. };
  20127. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20128. var engine = this.getScene().getEngine();
  20129. // Wireframe
  20130. var indexToBind;
  20131. if (this._unIndexed) {
  20132. indexToBind = null;
  20133. }
  20134. else {
  20135. switch (fillMode) {
  20136. case BABYLON.Material.PointFillMode:
  20137. indexToBind = null;
  20138. break;
  20139. case BABYLON.Material.WireFrameFillMode:
  20140. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20141. break;
  20142. default:
  20143. case BABYLON.Material.TriangleFillMode:
  20144. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20145. break;
  20146. }
  20147. }
  20148. // VBOs
  20149. this._geometry._bind(effect, indexToBind);
  20150. return this;
  20151. };
  20152. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20153. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20154. return this;
  20155. }
  20156. this.onBeforeDrawObservable.notifyObservers(this);
  20157. var engine = this.getScene().getEngine();
  20158. // Draw order
  20159. switch (fillMode) {
  20160. case BABYLON.Material.PointFillMode:
  20161. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20162. break;
  20163. case BABYLON.Material.WireFrameFillMode:
  20164. if (this._unIndexed) {
  20165. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20166. }
  20167. else {
  20168. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20169. }
  20170. break;
  20171. default:
  20172. if (this._unIndexed) {
  20173. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20174. }
  20175. else {
  20176. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20177. }
  20178. }
  20179. return this;
  20180. };
  20181. /**
  20182. * Registers for this mesh a javascript function called just before the rendering process.
  20183. * This function is passed the current mesh.
  20184. * Return the Mesh.
  20185. */
  20186. Mesh.prototype.registerBeforeRender = function (func) {
  20187. this.onBeforeRenderObservable.add(func);
  20188. return this;
  20189. };
  20190. /**
  20191. * Disposes a previously registered javascript function called before the rendering.
  20192. * This function is passed the current mesh.
  20193. * Returns the Mesh.
  20194. */
  20195. Mesh.prototype.unregisterBeforeRender = function (func) {
  20196. this.onBeforeRenderObservable.removeCallback(func);
  20197. return this;
  20198. };
  20199. /**
  20200. * Registers for this mesh a javascript function called just after the rendering is complete.
  20201. * This function is passed the current mesh.
  20202. * Returns the Mesh.
  20203. */
  20204. Mesh.prototype.registerAfterRender = function (func) {
  20205. this.onAfterRenderObservable.add(func);
  20206. return this;
  20207. };
  20208. /**
  20209. * Disposes a previously registered javascript function called after the rendering.
  20210. * This function is passed the current mesh.
  20211. * Return the Mesh.
  20212. */
  20213. Mesh.prototype.unregisterAfterRender = function (func) {
  20214. this.onAfterRenderObservable.removeCallback(func);
  20215. return this;
  20216. };
  20217. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20218. var scene = this.getScene();
  20219. this._batchCache.mustReturn = false;
  20220. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20221. this._batchCache.visibleInstances[subMeshId] = null;
  20222. if (this._visibleInstances) {
  20223. var currentRenderId = scene.getRenderId();
  20224. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20225. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20226. var selfRenderId = this._renderId;
  20227. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20228. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20229. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20230. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20231. }
  20232. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20233. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20234. this._batchCache.mustReturn = true;
  20235. return this._batchCache;
  20236. }
  20237. if (currentRenderId !== selfRenderId) {
  20238. this._batchCache.renderSelf[subMeshId] = false;
  20239. }
  20240. }
  20241. this._renderIdForInstances[subMeshId] = currentRenderId;
  20242. }
  20243. return this._batchCache;
  20244. };
  20245. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20246. var visibleInstances = batch.visibleInstances[subMesh._id];
  20247. var matricesCount = visibleInstances.length + 1;
  20248. var bufferSize = matricesCount * 16 * 4;
  20249. var currentInstancesBufferSize = this._instancesBufferSize;
  20250. var instancesBuffer = this._instancesBuffer;
  20251. while (this._instancesBufferSize < bufferSize) {
  20252. this._instancesBufferSize *= 2;
  20253. }
  20254. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20255. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20256. }
  20257. var offset = 0;
  20258. var instancesCount = 0;
  20259. var world = this.getWorldMatrix();
  20260. if (batch.renderSelf[subMesh._id]) {
  20261. world.copyToArray(this._instancesData, offset);
  20262. offset += 16;
  20263. instancesCount++;
  20264. }
  20265. if (visibleInstances) {
  20266. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20267. var instance = visibleInstances[instanceIndex];
  20268. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20269. offset += 16;
  20270. instancesCount++;
  20271. }
  20272. }
  20273. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20274. if (instancesBuffer) {
  20275. instancesBuffer.dispose();
  20276. }
  20277. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20278. this._instancesBuffer = instancesBuffer;
  20279. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20280. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20281. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20282. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20283. }
  20284. else {
  20285. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20286. }
  20287. this.geometry._bind(effect);
  20288. this._draw(subMesh, fillMode, instancesCount);
  20289. engine.unbindInstanceAttributes();
  20290. return this;
  20291. };
  20292. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20293. var scene = this.getScene();
  20294. var engine = scene.getEngine();
  20295. if (hardwareInstancedRendering) {
  20296. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20297. }
  20298. else {
  20299. if (batch.renderSelf[subMesh._id]) {
  20300. // Draw
  20301. if (onBeforeDraw) {
  20302. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20303. }
  20304. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20305. }
  20306. if (batch.visibleInstances[subMesh._id]) {
  20307. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20308. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20309. // World
  20310. var world = instance.getWorldMatrix();
  20311. if (onBeforeDraw) {
  20312. onBeforeDraw(true, world, effectiveMaterial);
  20313. }
  20314. // Draw
  20315. this._draw(subMesh, fillMode);
  20316. }
  20317. }
  20318. }
  20319. return this;
  20320. };
  20321. /**
  20322. * Triggers the draw call for the mesh.
  20323. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20324. * Returns the Mesh.
  20325. */
  20326. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20327. var scene = this.getScene();
  20328. // Managing instances
  20329. var batch = this._getInstancesRenderList(subMesh._id);
  20330. if (batch.mustReturn) {
  20331. return this;
  20332. }
  20333. // Checking geometry state
  20334. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20335. return this;
  20336. }
  20337. var callbackIndex;
  20338. this.onBeforeRenderObservable.notifyObservers(this);
  20339. var engine = scene.getEngine();
  20340. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20341. // Material
  20342. var effectiveMaterial = subMesh.getMaterial();
  20343. if (!effectiveMaterial) {
  20344. return this;
  20345. }
  20346. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20347. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20348. return this;
  20349. }
  20350. }
  20351. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20352. return this;
  20353. }
  20354. // Outline - step 1
  20355. var savedDepthWrite = engine.getDepthWrite();
  20356. if (this.renderOutline) {
  20357. engine.setDepthWrite(false);
  20358. scene.getOutlineRenderer().render(subMesh, batch);
  20359. engine.setDepthWrite(savedDepthWrite);
  20360. }
  20361. var effect;
  20362. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20363. effect = subMesh.effect;
  20364. }
  20365. else {
  20366. effect = effectiveMaterial.getEffect();
  20367. }
  20368. effectiveMaterial._preBind(effect);
  20369. // Bind
  20370. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20371. this._bind(subMesh, effect, fillMode);
  20372. var world = this.getWorldMatrix();
  20373. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20374. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20375. }
  20376. else {
  20377. effectiveMaterial.bind(world, this);
  20378. }
  20379. // Alpha mode
  20380. if (enableAlphaMode) {
  20381. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20382. }
  20383. // Draw
  20384. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20385. // Unbind
  20386. effectiveMaterial.unbind();
  20387. // Outline - step 2
  20388. if (this.renderOutline && savedDepthWrite) {
  20389. engine.setDepthWrite(true);
  20390. engine.setColorWrite(false);
  20391. scene.getOutlineRenderer().render(subMesh, batch);
  20392. engine.setColorWrite(true);
  20393. }
  20394. // Overlay
  20395. if (this.renderOverlay) {
  20396. var currentMode = engine.getAlphaMode();
  20397. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20398. scene.getOutlineRenderer().render(subMesh, batch, true);
  20399. engine.setAlphaMode(currentMode);
  20400. }
  20401. this.onAfterRenderObservable.notifyObservers(this);
  20402. return this;
  20403. };
  20404. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20405. if (isInstance) {
  20406. effectiveMaterial.bindOnlyWorldMatrix(world);
  20407. }
  20408. return this;
  20409. };
  20410. /**
  20411. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20412. */
  20413. Mesh.prototype.getEmittedParticleSystems = function () {
  20414. var results = new Array();
  20415. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20416. var particleSystem = this.getScene().particleSystems[index];
  20417. if (particleSystem.emitter === this) {
  20418. results.push(particleSystem);
  20419. }
  20420. }
  20421. return results;
  20422. };
  20423. /**
  20424. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20425. */
  20426. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20427. var results = new Array();
  20428. var descendants = this.getDescendants();
  20429. descendants.push(this);
  20430. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20431. var particleSystem = this.getScene().particleSystems[index];
  20432. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20433. results.push(particleSystem);
  20434. }
  20435. }
  20436. return results;
  20437. };
  20438. Mesh.prototype._checkDelayState = function () {
  20439. var scene = this.getScene();
  20440. if (this._geometry) {
  20441. this._geometry.load(scene);
  20442. }
  20443. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20444. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20445. this._queueLoad(this, scene);
  20446. }
  20447. return this;
  20448. };
  20449. Mesh.prototype._queueLoad = function (mesh, scene) {
  20450. var _this = this;
  20451. scene._addPendingData(mesh);
  20452. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20453. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20454. if (data instanceof ArrayBuffer) {
  20455. _this._delayLoadingFunction(data, _this);
  20456. }
  20457. else {
  20458. _this._delayLoadingFunction(JSON.parse(data), _this);
  20459. }
  20460. _this.instances.forEach(function (instance) {
  20461. instance._syncSubMeshes();
  20462. });
  20463. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20464. scene._removePendingData(_this);
  20465. }, function () { }, scene.database, getBinaryData);
  20466. return this;
  20467. };
  20468. /**
  20469. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20470. */
  20471. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20472. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20473. return false;
  20474. }
  20475. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20476. return false;
  20477. }
  20478. this._checkDelayState();
  20479. return true;
  20480. };
  20481. /**
  20482. * Sets the mesh material by the material or multiMaterial `id` property.
  20483. * The material `id` is a string identifying the material or the multiMaterial.
  20484. * This method returns the Mesh.
  20485. */
  20486. Mesh.prototype.setMaterialByID = function (id) {
  20487. var materials = this.getScene().materials;
  20488. var index;
  20489. for (index = materials.length - 1; index > -1; index--) {
  20490. if (materials[index].id === id) {
  20491. this.material = materials[index];
  20492. return this;
  20493. }
  20494. }
  20495. // Multi
  20496. var multiMaterials = this.getScene().multiMaterials;
  20497. for (index = multiMaterials.length - 1; index > -1; index--) {
  20498. if (multiMaterials[index].id === id) {
  20499. this.material = multiMaterials[index];
  20500. return this;
  20501. }
  20502. }
  20503. return this;
  20504. };
  20505. /**
  20506. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20507. */
  20508. Mesh.prototype.getAnimatables = function () {
  20509. var results = [];
  20510. if (this.material) {
  20511. results.push(this.material);
  20512. }
  20513. if (this.skeleton) {
  20514. results.push(this.skeleton);
  20515. }
  20516. return results;
  20517. };
  20518. /**
  20519. * Modifies the mesh geometry according to the passed transformation matrix.
  20520. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20521. * The mesh normals are modified accordingly the same transformation.
  20522. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20523. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20524. * Returns the Mesh.
  20525. */
  20526. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20527. // Position
  20528. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20529. return this;
  20530. }
  20531. var submeshes = this.subMeshes.splice(0);
  20532. this._resetPointsArrayCache();
  20533. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20534. var temp = [];
  20535. var index;
  20536. for (index = 0; index < data.length; index += 3) {
  20537. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20538. }
  20539. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20540. // Normals
  20541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20542. return this;
  20543. }
  20544. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20545. temp = [];
  20546. for (index = 0; index < data.length; index += 3) {
  20547. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20548. }
  20549. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20550. // flip faces?
  20551. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20552. this.flipFaces();
  20553. }
  20554. // Restore submeshes
  20555. this.releaseSubMeshes();
  20556. this.subMeshes = submeshes;
  20557. return this;
  20558. };
  20559. /**
  20560. * Modifies the mesh geometry according to its own current World Matrix.
  20561. * The mesh World Matrix is then reset.
  20562. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20563. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20564. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20565. * Returns the Mesh.
  20566. */
  20567. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20568. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20569. this.scaling.copyFromFloats(1, 1, 1);
  20570. this.position.copyFromFloats(0, 0, 0);
  20571. this.rotation.copyFromFloats(0, 0, 0);
  20572. //only if quaternion is already set
  20573. if (this.rotationQuaternion) {
  20574. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20575. }
  20576. this._worldMatrix = BABYLON.Matrix.Identity();
  20577. return this;
  20578. };
  20579. Object.defineProperty(Mesh.prototype, "_positions", {
  20580. // Cache
  20581. get: function () {
  20582. if (this._geometry) {
  20583. return this._geometry._positions;
  20584. }
  20585. return null;
  20586. },
  20587. enumerable: true,
  20588. configurable: true
  20589. });
  20590. Mesh.prototype._resetPointsArrayCache = function () {
  20591. if (this._geometry) {
  20592. this._geometry._resetPointsArrayCache();
  20593. }
  20594. return this;
  20595. };
  20596. Mesh.prototype._generatePointsArray = function () {
  20597. if (this._geometry) {
  20598. return this._geometry._generatePointsArray();
  20599. }
  20600. return false;
  20601. };
  20602. /**
  20603. * Returns a new Mesh object generated from the current mesh properties.
  20604. * This method must not get confused with createInstance().
  20605. * The parameter `name` is a string, the name given to the new mesh.
  20606. * The optional parameter `newParent` can be any Node object (default `null`).
  20607. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20608. * 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.
  20609. */
  20610. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20611. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20612. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20613. };
  20614. /**
  20615. * Disposes the mesh.
  20616. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20617. */
  20618. Mesh.prototype.dispose = function (doNotRecurse) {
  20619. var _this = this;
  20620. this.morphTargetManager = undefined;
  20621. if (this._geometry) {
  20622. this._geometry.releaseForMesh(this, true);
  20623. }
  20624. // Sources
  20625. var meshes = this.getScene().meshes;
  20626. meshes.forEach(function (mesh) {
  20627. if (mesh._source && mesh._source === _this) {
  20628. mesh._source = null;
  20629. }
  20630. });
  20631. this._source = null;
  20632. // Instances
  20633. if (this._instancesBuffer) {
  20634. this._instancesBuffer.dispose();
  20635. this._instancesBuffer = null;
  20636. }
  20637. while (this.instances.length) {
  20638. this.instances[0].dispose();
  20639. }
  20640. // Highlight layers.
  20641. var highlightLayers = this.getScene().highlightLayers;
  20642. for (var i = 0; i < highlightLayers.length; i++) {
  20643. var highlightLayer = highlightLayers[i];
  20644. if (highlightLayer) {
  20645. highlightLayer.removeMesh(this);
  20646. highlightLayer.removeExcludedMesh(this);
  20647. }
  20648. }
  20649. _super.prototype.dispose.call(this, doNotRecurse);
  20650. };
  20651. /**
  20652. * Modifies the mesh geometry according to a displacement map.
  20653. * 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.
  20654. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20655. * This method returns nothing.
  20656. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20657. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20658. * 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.
  20659. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20660. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20661. *
  20662. * Returns the Mesh.
  20663. */
  20664. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20665. var _this = this;
  20666. var scene = this.getScene();
  20667. var onload = function (img) {
  20668. // Getting height map data
  20669. var canvas = document.createElement("canvas");
  20670. var context = canvas.getContext("2d");
  20671. var heightMapWidth = img.width;
  20672. var heightMapHeight = img.height;
  20673. canvas.width = heightMapWidth;
  20674. canvas.height = heightMapHeight;
  20675. context.drawImage(img, 0, 0);
  20676. // Create VertexData from map data
  20677. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20678. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20679. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20680. //execute success callback, if set
  20681. if (onSuccess) {
  20682. onSuccess(_this);
  20683. }
  20684. };
  20685. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20686. return this;
  20687. };
  20688. /**
  20689. * Modifies the mesh geometry according to a displacementMap buffer.
  20690. * 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.
  20691. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20692. * This method returns nothing.
  20693. * 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.
  20694. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20695. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20696. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20697. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20698. *
  20699. * Returns the Mesh.
  20700. */
  20701. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20702. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20703. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20704. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20705. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20706. return this;
  20707. }
  20708. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20709. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20710. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20711. var position = BABYLON.Vector3.Zero();
  20712. var normal = BABYLON.Vector3.Zero();
  20713. var uv = BABYLON.Vector2.Zero();
  20714. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20715. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20716. for (var index = 0; index < positions.length; index += 3) {
  20717. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20718. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20719. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20720. // Compute height
  20721. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20722. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20723. var pos = (u + v * heightMapWidth) * 4;
  20724. var r = buffer[pos] / 255.0;
  20725. var g = buffer[pos + 1] / 255.0;
  20726. var b = buffer[pos + 2] / 255.0;
  20727. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20728. normal.normalize();
  20729. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20730. position = position.add(normal);
  20731. position.toArray(positions, index);
  20732. }
  20733. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20734. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20735. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20736. return this;
  20737. };
  20738. /**
  20739. * Modify the mesh to get a flat shading rendering.
  20740. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20741. * This method returns the Mesh.
  20742. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20743. */
  20744. Mesh.prototype.convertToFlatShadedMesh = function () {
  20745. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20746. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20747. var kinds = this.getVerticesDataKinds();
  20748. var vbs = [];
  20749. var data = [];
  20750. var newdata = [];
  20751. var updatableNormals = false;
  20752. var kindIndex;
  20753. var kind;
  20754. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20755. kind = kinds[kindIndex];
  20756. var vertexBuffer = this.getVertexBuffer(kind);
  20757. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20758. updatableNormals = vertexBuffer.isUpdatable();
  20759. kinds.splice(kindIndex, 1);
  20760. kindIndex--;
  20761. continue;
  20762. }
  20763. vbs[kind] = vertexBuffer;
  20764. data[kind] = vbs[kind].getData();
  20765. newdata[kind] = [];
  20766. }
  20767. // Save previous submeshes
  20768. var previousSubmeshes = this.subMeshes.slice(0);
  20769. var indices = this.getIndices();
  20770. var totalIndices = this.getTotalIndices();
  20771. // Generating unique vertices per face
  20772. var index;
  20773. for (index = 0; index < totalIndices; index++) {
  20774. var vertexIndex = indices[index];
  20775. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20776. kind = kinds[kindIndex];
  20777. var stride = vbs[kind].getStrideSize();
  20778. for (var offset = 0; offset < stride; offset++) {
  20779. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20780. }
  20781. }
  20782. }
  20783. // Updating faces & normal
  20784. var normals = [];
  20785. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20786. for (index = 0; index < totalIndices; index += 3) {
  20787. indices[index] = index;
  20788. indices[index + 1] = index + 1;
  20789. indices[index + 2] = index + 2;
  20790. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20791. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20792. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20793. var p1p2 = p1.subtract(p2);
  20794. var p3p2 = p3.subtract(p2);
  20795. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20796. // Store same normals for every vertex
  20797. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20798. normals.push(normal.x);
  20799. normals.push(normal.y);
  20800. normals.push(normal.z);
  20801. }
  20802. }
  20803. this.setIndices(indices);
  20804. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20805. // Updating vertex buffers
  20806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20807. kind = kinds[kindIndex];
  20808. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20809. }
  20810. // Updating submeshes
  20811. this.releaseSubMeshes();
  20812. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20813. var previousOne = previousSubmeshes[submeshIndex];
  20814. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20815. }
  20816. this.synchronizeInstances();
  20817. return this;
  20818. };
  20819. /**
  20820. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20821. * In other words, more vertices, no more indices and a single bigger VBO.
  20822. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20823. * Returns the Mesh.
  20824. */
  20825. Mesh.prototype.convertToUnIndexedMesh = function () {
  20826. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20827. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20828. var kinds = this.getVerticesDataKinds();
  20829. var vbs = [];
  20830. var data = [];
  20831. var newdata = [];
  20832. var updatableNormals = false;
  20833. var kindIndex;
  20834. var kind;
  20835. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20836. kind = kinds[kindIndex];
  20837. var vertexBuffer = this.getVertexBuffer(kind);
  20838. vbs[kind] = vertexBuffer;
  20839. data[kind] = vbs[kind].getData();
  20840. newdata[kind] = [];
  20841. }
  20842. // Save previous submeshes
  20843. var previousSubmeshes = this.subMeshes.slice(0);
  20844. var indices = this.getIndices();
  20845. var totalIndices = this.getTotalIndices();
  20846. // Generating unique vertices per face
  20847. var index;
  20848. for (index = 0; index < totalIndices; index++) {
  20849. var vertexIndex = indices[index];
  20850. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20851. kind = kinds[kindIndex];
  20852. var stride = vbs[kind].getStrideSize();
  20853. for (var offset = 0; offset < stride; offset++) {
  20854. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20855. }
  20856. }
  20857. }
  20858. // Updating indices
  20859. for (index = 0; index < totalIndices; index += 3) {
  20860. indices[index] = index;
  20861. indices[index + 1] = index + 1;
  20862. indices[index + 2] = index + 2;
  20863. }
  20864. this.setIndices(indices);
  20865. // Updating vertex buffers
  20866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20867. kind = kinds[kindIndex];
  20868. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20869. }
  20870. // Updating submeshes
  20871. this.releaseSubMeshes();
  20872. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20873. var previousOne = previousSubmeshes[submeshIndex];
  20874. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20875. }
  20876. this._unIndexed = true;
  20877. this.synchronizeInstances();
  20878. return this;
  20879. };
  20880. /**
  20881. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20882. * This method returns the Mesh.
  20883. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20884. */
  20885. Mesh.prototype.flipFaces = function (flipNormals) {
  20886. if (flipNormals === void 0) { flipNormals = false; }
  20887. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20888. var i;
  20889. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20890. for (i = 0; i < vertex_data.normals.length; i++) {
  20891. vertex_data.normals[i] *= -1;
  20892. }
  20893. }
  20894. var temp;
  20895. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20896. // reassign indices
  20897. temp = vertex_data.indices[i + 1];
  20898. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20899. vertex_data.indices[i + 2] = temp;
  20900. }
  20901. vertex_data.applyToMesh(this);
  20902. return this;
  20903. };
  20904. // Instances
  20905. /**
  20906. * Creates a new InstancedMesh object from the mesh model.
  20907. * An instance shares the same properties and the same material than its model.
  20908. * Only these properties of each instance can then be set individually :
  20909. * - position
  20910. * - rotation
  20911. * - rotationQuaternion
  20912. * - setPivotMatrix
  20913. * - scaling
  20914. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20915. * Warning : this method is not supported for Line mesh and LineSystem
  20916. */
  20917. Mesh.prototype.createInstance = function (name) {
  20918. return new BABYLON.InstancedMesh(name, this);
  20919. };
  20920. /**
  20921. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20922. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20923. * This method returns the Mesh.
  20924. */
  20925. Mesh.prototype.synchronizeInstances = function () {
  20926. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20927. var instance = this.instances[instanceIndex];
  20928. instance._syncSubMeshes();
  20929. }
  20930. return this;
  20931. };
  20932. /**
  20933. * Simplify the mesh according to the given array of settings.
  20934. * Function will return immediately and will simplify async. It returns the Mesh.
  20935. * @param settings a collection of simplification settings.
  20936. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20937. * @param type the type of simplification to run.
  20938. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20939. */
  20940. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20941. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20942. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20943. this.getScene().simplificationQueue.addTask({
  20944. settings: settings,
  20945. parallelProcessing: parallelProcessing,
  20946. mesh: this,
  20947. simplificationType: simplificationType,
  20948. successCallback: successCallback
  20949. });
  20950. return this;
  20951. };
  20952. /**
  20953. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20954. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20955. * This should be used together with the simplification to avoid disappearing triangles.
  20956. * Returns the Mesh.
  20957. * @param successCallback an optional success callback to be called after the optimization finished.
  20958. */
  20959. Mesh.prototype.optimizeIndices = function (successCallback) {
  20960. var _this = this;
  20961. var indices = this.getIndices();
  20962. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20963. var vectorPositions = [];
  20964. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20965. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20966. }
  20967. var dupes = [];
  20968. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20969. var realPos = vectorPositions.length - 1 - iteration;
  20970. var testedPosition = vectorPositions[realPos];
  20971. for (var j = 0; j < realPos; ++j) {
  20972. var againstPosition = vectorPositions[j];
  20973. if (testedPosition.equals(againstPosition)) {
  20974. dupes[realPos] = j;
  20975. break;
  20976. }
  20977. }
  20978. }, function () {
  20979. for (var i = 0; i < indices.length; ++i) {
  20980. indices[i] = dupes[indices[i]] || indices[i];
  20981. }
  20982. //indices are now reordered
  20983. var originalSubMeshes = _this.subMeshes.slice(0);
  20984. _this.setIndices(indices);
  20985. _this.subMeshes = originalSubMeshes;
  20986. if (successCallback) {
  20987. successCallback(_this);
  20988. }
  20989. });
  20990. return this;
  20991. };
  20992. Mesh.prototype.serialize = function (serializationObject) {
  20993. serializationObject.name = this.name;
  20994. serializationObject.id = this.id;
  20995. serializationObject.type = this.getClassName();
  20996. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20997. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20998. }
  20999. serializationObject.position = this.position.asArray();
  21000. if (this.rotationQuaternion) {
  21001. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21002. }
  21003. else if (this.rotation) {
  21004. serializationObject.rotation = this.rotation.asArray();
  21005. }
  21006. serializationObject.scaling = this.scaling.asArray();
  21007. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21008. serializationObject.isEnabled = this.isEnabled();
  21009. serializationObject.isVisible = this.isVisible;
  21010. serializationObject.infiniteDistance = this.infiniteDistance;
  21011. serializationObject.pickable = this.isPickable;
  21012. serializationObject.receiveShadows = this.receiveShadows;
  21013. serializationObject.billboardMode = this.billboardMode;
  21014. serializationObject.visibility = this.visibility;
  21015. serializationObject.checkCollisions = this.checkCollisions;
  21016. serializationObject.isBlocker = this.isBlocker;
  21017. // Parent
  21018. if (this.parent) {
  21019. serializationObject.parentId = this.parent.id;
  21020. }
  21021. // Geometry
  21022. var geometry = this._geometry;
  21023. if (geometry) {
  21024. var geometryId = geometry.id;
  21025. serializationObject.geometryId = geometryId;
  21026. // SubMeshes
  21027. serializationObject.subMeshes = [];
  21028. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21029. var subMesh = this.subMeshes[subIndex];
  21030. serializationObject.subMeshes.push({
  21031. materialIndex: subMesh.materialIndex,
  21032. verticesStart: subMesh.verticesStart,
  21033. verticesCount: subMesh.verticesCount,
  21034. indexStart: subMesh.indexStart,
  21035. indexCount: subMesh.indexCount
  21036. });
  21037. }
  21038. }
  21039. // Material
  21040. if (this.material) {
  21041. serializationObject.materialId = this.material.id;
  21042. }
  21043. else {
  21044. this.material = null;
  21045. }
  21046. // Morph targets
  21047. if (this.morphTargetManager) {
  21048. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21049. }
  21050. // Skeleton
  21051. if (this.skeleton) {
  21052. serializationObject.skeletonId = this.skeleton.id;
  21053. }
  21054. // Physics
  21055. //TODO implement correct serialization for physics impostors.
  21056. if (this.getPhysicsImpostor()) {
  21057. var impostor = this.getPhysicsImpostor();
  21058. serializationObject.physicsMass = impostor.getParam("mass");
  21059. serializationObject.physicsFriction = impostor.getParam("friction");
  21060. serializationObject.physicsRestitution = impostor.getParam("mass");
  21061. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21062. }
  21063. // Metadata
  21064. if (this.metadata) {
  21065. serializationObject.metadata = this.metadata;
  21066. }
  21067. // Instances
  21068. serializationObject.instances = [];
  21069. for (var index = 0; index < this.instances.length; index++) {
  21070. var instance = this.instances[index];
  21071. var serializationInstance = {
  21072. name: instance.name,
  21073. position: instance.position.asArray(),
  21074. scaling: instance.scaling.asArray()
  21075. };
  21076. if (instance.rotationQuaternion) {
  21077. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21078. }
  21079. else if (instance.rotation) {
  21080. serializationInstance.rotation = instance.rotation.asArray();
  21081. }
  21082. serializationObject.instances.push(serializationInstance);
  21083. // Animations
  21084. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21085. serializationInstance.ranges = instance.serializeAnimationRanges();
  21086. }
  21087. //
  21088. // Animations
  21089. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21090. serializationObject.ranges = this.serializeAnimationRanges();
  21091. // Layer mask
  21092. serializationObject.layerMask = this.layerMask;
  21093. // Alpha
  21094. serializationObject.alphaIndex = this.alphaIndex;
  21095. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21096. // Overlay
  21097. serializationObject.overlayAlpha = this.overlayAlpha;
  21098. serializationObject.overlayColor = this.overlayColor.asArray();
  21099. serializationObject.renderOverlay = this.renderOverlay;
  21100. // Fog
  21101. serializationObject.applyFog = this.applyFog;
  21102. // Action Manager
  21103. if (this.actionManager) {
  21104. serializationObject.actions = this.actionManager.serialize(this.name);
  21105. }
  21106. };
  21107. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21108. if (!this.geometry) {
  21109. return;
  21110. }
  21111. this._markSubMeshesAsAttributesDirty();
  21112. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21113. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21114. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21115. this.morphTargetManager = undefined;
  21116. return;
  21117. }
  21118. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21119. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21120. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21121. if (morphTarget.hasNormals) {
  21122. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21123. }
  21124. if (morphTarget.hasTangents) {
  21125. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21126. }
  21127. }
  21128. }
  21129. else {
  21130. var index = 0;
  21131. // Positions
  21132. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21133. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21134. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21135. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21136. }
  21137. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21138. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21139. }
  21140. index++;
  21141. }
  21142. }
  21143. };
  21144. // Statics
  21145. /**
  21146. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21147. * The parameter `parsedMesh` is the mesh to be copied.
  21148. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21149. */
  21150. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21151. var mesh;
  21152. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21153. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21154. }
  21155. else {
  21156. mesh = new Mesh(parsedMesh.name, scene);
  21157. }
  21158. mesh.id = parsedMesh.id;
  21159. if (BABYLON.Tags) {
  21160. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21161. }
  21162. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21163. if (parsedMesh.metadata !== undefined) {
  21164. mesh.metadata = parsedMesh.metadata;
  21165. }
  21166. if (parsedMesh.rotationQuaternion) {
  21167. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21168. }
  21169. else if (parsedMesh.rotation) {
  21170. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21171. }
  21172. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21173. if (parsedMesh.localMatrix) {
  21174. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21175. }
  21176. else if (parsedMesh.pivotMatrix) {
  21177. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21178. }
  21179. mesh.setEnabled(parsedMesh.isEnabled);
  21180. mesh.isVisible = parsedMesh.isVisible;
  21181. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21182. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21183. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21184. if (parsedMesh.applyFog !== undefined) {
  21185. mesh.applyFog = parsedMesh.applyFog;
  21186. }
  21187. if (parsedMesh.pickable !== undefined) {
  21188. mesh.isPickable = parsedMesh.pickable;
  21189. }
  21190. if (parsedMesh.alphaIndex !== undefined) {
  21191. mesh.alphaIndex = parsedMesh.alphaIndex;
  21192. }
  21193. mesh.receiveShadows = parsedMesh.receiveShadows;
  21194. mesh.billboardMode = parsedMesh.billboardMode;
  21195. if (parsedMesh.visibility !== undefined) {
  21196. mesh.visibility = parsedMesh.visibility;
  21197. }
  21198. mesh.checkCollisions = parsedMesh.checkCollisions;
  21199. if (parsedMesh.isBlocker !== undefined) {
  21200. mesh.isBlocker = parsedMesh.isBlocker;
  21201. }
  21202. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21203. // freezeWorldMatrix
  21204. if (parsedMesh.freezeWorldMatrix) {
  21205. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21206. }
  21207. // Parent
  21208. if (parsedMesh.parentId) {
  21209. mesh._waitingParentId = parsedMesh.parentId;
  21210. }
  21211. // Actions
  21212. if (parsedMesh.actions !== undefined) {
  21213. mesh._waitingActions = parsedMesh.actions;
  21214. }
  21215. // Overlay
  21216. if (parsedMesh.overlayAlpha !== undefined) {
  21217. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21218. }
  21219. if (parsedMesh.overlayColor !== undefined) {
  21220. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21221. }
  21222. if (parsedMesh.renderOverlay !== undefined) {
  21223. mesh.renderOverlay = parsedMesh.renderOverlay;
  21224. }
  21225. // Geometry
  21226. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21227. if (parsedMesh.delayLoadingFile) {
  21228. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21229. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21230. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21231. if (parsedMesh._binaryInfo) {
  21232. mesh._binaryInfo = parsedMesh._binaryInfo;
  21233. }
  21234. mesh._delayInfo = [];
  21235. if (parsedMesh.hasUVs) {
  21236. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21237. }
  21238. if (parsedMesh.hasUVs2) {
  21239. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21240. }
  21241. if (parsedMesh.hasUVs3) {
  21242. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21243. }
  21244. if (parsedMesh.hasUVs4) {
  21245. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21246. }
  21247. if (parsedMesh.hasUVs5) {
  21248. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21249. }
  21250. if (parsedMesh.hasUVs6) {
  21251. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21252. }
  21253. if (parsedMesh.hasColors) {
  21254. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21255. }
  21256. if (parsedMesh.hasMatricesIndices) {
  21257. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21258. }
  21259. if (parsedMesh.hasMatricesWeights) {
  21260. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21261. }
  21262. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21263. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21264. mesh._checkDelayState();
  21265. }
  21266. }
  21267. else {
  21268. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21269. }
  21270. // Material
  21271. if (parsedMesh.materialId) {
  21272. mesh.setMaterialByID(parsedMesh.materialId);
  21273. }
  21274. else {
  21275. mesh.material = null;
  21276. }
  21277. // Morph targets
  21278. if (parsedMesh.morphTargetManagerId > -1) {
  21279. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21280. }
  21281. // Skeleton
  21282. if (parsedMesh.skeletonId > -1) {
  21283. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21284. if (parsedMesh.numBoneInfluencers) {
  21285. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21286. }
  21287. }
  21288. // Animations
  21289. if (parsedMesh.animations) {
  21290. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21291. var parsedAnimation = parsedMesh.animations[animationIndex];
  21292. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21293. }
  21294. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21295. }
  21296. if (parsedMesh.autoAnimate) {
  21297. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21298. }
  21299. // Layer Mask
  21300. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21301. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21302. }
  21303. else {
  21304. mesh.layerMask = 0x0FFFFFFF;
  21305. }
  21306. // Physics
  21307. if (parsedMesh.physicsImpostor) {
  21308. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21309. mass: parsedMesh.physicsMass,
  21310. friction: parsedMesh.physicsFriction,
  21311. restitution: parsedMesh.physicsRestitution
  21312. }, scene);
  21313. }
  21314. // Instances
  21315. if (parsedMesh.instances) {
  21316. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21317. var parsedInstance = parsedMesh.instances[index];
  21318. var instance = mesh.createInstance(parsedInstance.name);
  21319. if (BABYLON.Tags) {
  21320. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21321. }
  21322. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21323. if (parsedInstance.parentId) {
  21324. instance._waitingParentId = parsedInstance.parentId;
  21325. }
  21326. if (parsedInstance.rotationQuaternion) {
  21327. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21328. }
  21329. else if (parsedInstance.rotation) {
  21330. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21331. }
  21332. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21333. instance.checkCollisions = mesh.checkCollisions;
  21334. if (parsedMesh.animations) {
  21335. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21336. parsedAnimation = parsedMesh.animations[animationIndex];
  21337. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21338. }
  21339. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21340. }
  21341. }
  21342. }
  21343. return mesh;
  21344. };
  21345. /**
  21346. * Creates a ribbon mesh.
  21347. * Please consider using the same method from the MeshBuilder class instead.
  21348. * 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.
  21349. *
  21350. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21351. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21352. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21353. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21354. * 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.
  21355. * 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.
  21356. * 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
  21357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21358. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21360. */
  21361. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21362. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21363. pathArray: pathArray,
  21364. closeArray: closeArray,
  21365. closePath: closePath,
  21366. offset: offset,
  21367. updatable: updatable,
  21368. sideOrientation: sideOrientation,
  21369. instance: instance
  21370. }, scene);
  21371. };
  21372. /**
  21373. * Creates a plane polygonal mesh. By default, this is a disc.
  21374. * Please consider using the same method from the MeshBuilder class instead.
  21375. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21376. * 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.
  21377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21380. */
  21381. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21382. var options = {
  21383. radius: radius,
  21384. tessellation: tessellation,
  21385. sideOrientation: sideOrientation,
  21386. updatable: updatable
  21387. };
  21388. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21389. };
  21390. /**
  21391. * Creates a box mesh.
  21392. * Please consider using the same method from the MeshBuilder class instead.
  21393. * The parameter `size` sets the size (float) of each box side (default 1).
  21394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21397. */
  21398. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21399. var options = {
  21400. size: size,
  21401. sideOrientation: sideOrientation,
  21402. updatable: updatable
  21403. };
  21404. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21405. };
  21406. /**
  21407. * Creates a sphere mesh.
  21408. * Please consider using the same method from the MeshBuilder class instead.
  21409. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21410. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21411. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21414. */
  21415. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21416. var options = {
  21417. segments: segments,
  21418. diameterX: diameter,
  21419. diameterY: diameter,
  21420. diameterZ: diameter,
  21421. sideOrientation: sideOrientation,
  21422. updatable: updatable
  21423. };
  21424. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21425. };
  21426. /**
  21427. * Creates a cylinder or a cone mesh.
  21428. * Please consider using the same method from the MeshBuilder class instead.
  21429. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21430. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21431. * 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.
  21432. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21433. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21437. */
  21438. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21439. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21440. if (scene !== undefined) {
  21441. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21442. updatable = scene;
  21443. }
  21444. scene = subdivisions;
  21445. subdivisions = 1;
  21446. }
  21447. var options = {
  21448. height: height,
  21449. diameterTop: diameterTop,
  21450. diameterBottom: diameterBottom,
  21451. tessellation: tessellation,
  21452. subdivisions: subdivisions,
  21453. sideOrientation: sideOrientation,
  21454. updatable: updatable
  21455. };
  21456. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21457. };
  21458. // Torus (Code from SharpDX.org)
  21459. /**
  21460. * Creates a torus mesh.
  21461. * Please consider using the same method from the MeshBuilder class instead.
  21462. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21463. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21464. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21468. */
  21469. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21470. var options = {
  21471. diameter: diameter,
  21472. thickness: thickness,
  21473. tessellation: tessellation,
  21474. sideOrientation: sideOrientation,
  21475. updatable: updatable
  21476. };
  21477. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21478. };
  21479. /**
  21480. * Creates a torus knot mesh.
  21481. * Please consider using the same method from the MeshBuilder class instead.
  21482. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21483. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21484. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21485. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21489. */
  21490. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21491. var options = {
  21492. radius: radius,
  21493. tube: tube,
  21494. radialSegments: radialSegments,
  21495. tubularSegments: tubularSegments,
  21496. p: p,
  21497. q: q,
  21498. sideOrientation: sideOrientation,
  21499. updatable: updatable
  21500. };
  21501. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21502. };
  21503. /**
  21504. * Creates a line mesh.
  21505. * Please consider using the same method from the MeshBuilder class instead.
  21506. * 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.
  21507. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21508. * The parameter `points` is an array successive Vector3.
  21509. * 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
  21510. * When updating an instance, remember that only point positions can change, not the number of points.
  21511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21512. */
  21513. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21514. var options = {
  21515. points: points,
  21516. updatable: updatable,
  21517. instance: instance
  21518. };
  21519. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21520. };
  21521. /**
  21522. * Creates a dashed line mesh.
  21523. * Please consider using the same method from the MeshBuilder class instead.
  21524. * 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.
  21525. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21526. * The parameter `points` is an array successive Vector3.
  21527. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21528. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21529. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21530. * 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
  21531. * When updating an instance, remember that only point positions can change, not the number of points.
  21532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21533. */
  21534. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21535. var options = {
  21536. points: points,
  21537. dashSize: dashSize,
  21538. gapSize: gapSize,
  21539. dashNb: dashNb,
  21540. updatable: updatable,
  21541. instance: instance
  21542. };
  21543. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21544. };
  21545. /**
  21546. * Creates a polygon mesh.
  21547. * Please consider using the same method from the MeshBuilder class instead.
  21548. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21549. * 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.
  21550. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21552. * Remember you can only change the shape positions, not their number when updating a polygon.
  21553. */
  21554. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21555. var options = {
  21556. shape: shape,
  21557. holes: holes,
  21558. updatable: updatable,
  21559. sideOrientation: sideOrientation
  21560. };
  21561. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21562. };
  21563. /**
  21564. * Creates an extruded polygon mesh, with depth in the Y direction.
  21565. * Please consider using the same method from the MeshBuilder class instead.
  21566. */
  21567. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21568. var options = {
  21569. shape: shape,
  21570. holes: holes,
  21571. depth: depth,
  21572. updatable: updatable,
  21573. sideOrientation: sideOrientation
  21574. };
  21575. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21576. };
  21577. /**
  21578. * Creates an extruded shape mesh.
  21579. * 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.
  21580. * Please consider using the same method from the MeshBuilder class instead.
  21581. *
  21582. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21583. * 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
  21584. * extruded along the Z axis.
  21585. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21586. * 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.
  21587. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21588. * 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
  21589. * 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
  21590. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21594. */
  21595. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21596. var options = {
  21597. shape: shape,
  21598. path: path,
  21599. scale: scale,
  21600. rotation: rotation,
  21601. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21602. sideOrientation: sideOrientation,
  21603. instance: instance,
  21604. updatable: updatable
  21605. };
  21606. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21607. };
  21608. /**
  21609. * Creates an custom extruded shape mesh.
  21610. * 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.
  21611. * Please consider using the same method from the MeshBuilder class instead.
  21612. *
  21613. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21614. * 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
  21615. * extruded along the Z axis.
  21616. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21617. * 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
  21618. * and the distance of this point from the begining of the path :
  21619. * ```javascript
  21620. * var rotationFunction = function(i, distance) {
  21621. * // do things
  21622. * return rotationValue; }
  21623. * ```
  21624. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21625. * 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
  21626. * and the distance of this point from the begining of the path :
  21627. * ```javascript
  21628. * var scaleFunction = function(i, distance) {
  21629. * // do things
  21630. * return scaleValue;}
  21631. * ```
  21632. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21633. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21634. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21635. * 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
  21636. * 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
  21637. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21641. */
  21642. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21643. var options = {
  21644. shape: shape,
  21645. path: path,
  21646. scaleFunction: scaleFunction,
  21647. rotationFunction: rotationFunction,
  21648. ribbonCloseArray: ribbonCloseArray,
  21649. ribbonClosePath: ribbonClosePath,
  21650. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21651. sideOrientation: sideOrientation,
  21652. instance: instance,
  21653. updatable: updatable
  21654. };
  21655. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21656. };
  21657. /**
  21658. * Creates lathe mesh.
  21659. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21660. * Please consider using the same method from the MeshBuilder class instead.
  21661. * 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
  21662. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21663. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21664. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21668. */
  21669. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21670. var options = {
  21671. shape: shape,
  21672. radius: radius,
  21673. tessellation: tessellation,
  21674. sideOrientation: sideOrientation,
  21675. updatable: updatable
  21676. };
  21677. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21678. };
  21679. /**
  21680. * Creates a plane mesh.
  21681. * Please consider using the same method from the MeshBuilder class instead.
  21682. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21686. */
  21687. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21688. var options = {
  21689. size: size,
  21690. width: size,
  21691. height: size,
  21692. sideOrientation: sideOrientation,
  21693. updatable: updatable
  21694. };
  21695. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21696. };
  21697. /**
  21698. * Creates a ground mesh.
  21699. * Please consider using the same method from the MeshBuilder class instead.
  21700. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21701. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21703. */
  21704. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21705. var options = {
  21706. width: width,
  21707. height: height,
  21708. subdivisions: subdivisions,
  21709. updatable: updatable
  21710. };
  21711. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21712. };
  21713. /**
  21714. * Creates a tiled ground mesh.
  21715. * Please consider using the same method from the MeshBuilder class instead.
  21716. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21717. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21718. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21719. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21720. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21721. * numbers of subdivisions on the ground width and height of each tile.
  21722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21723. */
  21724. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21725. var options = {
  21726. xmin: xmin,
  21727. zmin: zmin,
  21728. xmax: xmax,
  21729. zmax: zmax,
  21730. subdivisions: subdivisions,
  21731. precision: precision,
  21732. updatable: updatable
  21733. };
  21734. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21735. };
  21736. /**
  21737. * Creates a ground mesh from a height map.
  21738. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21739. * Please consider using the same method from the MeshBuilder class instead.
  21740. * The parameter `url` sets the URL of the height map image resource.
  21741. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21742. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21743. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21744. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21745. * 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).
  21746. * This function is passed the newly built mesh :
  21747. * ```javascript
  21748. * function(mesh) { // do things
  21749. * return; }
  21750. * ```
  21751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21752. */
  21753. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21754. var options = {
  21755. width: width,
  21756. height: height,
  21757. subdivisions: subdivisions,
  21758. minHeight: minHeight,
  21759. maxHeight: maxHeight,
  21760. updatable: updatable,
  21761. onReady: onReady
  21762. };
  21763. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21764. };
  21765. /**
  21766. * Creates a tube mesh.
  21767. * 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.
  21768. * Please consider using the same method from the MeshBuilder class instead.
  21769. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21770. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21771. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21772. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21773. * 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.
  21774. * It must return a radius value (positive float) :
  21775. * ```javascript
  21776. * var radiusFunction = function(i, distance) {
  21777. * // do things
  21778. * return radius; }
  21779. * ```
  21780. * 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
  21781. * 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
  21782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21785. */
  21786. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21787. var options = {
  21788. path: path,
  21789. radius: radius,
  21790. tessellation: tessellation,
  21791. radiusFunction: radiusFunction,
  21792. arc: 1,
  21793. cap: cap,
  21794. updatable: updatable,
  21795. sideOrientation: sideOrientation,
  21796. instance: instance
  21797. };
  21798. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21799. };
  21800. /**
  21801. * Creates a polyhedron mesh.
  21802. * Please consider using the same method from the MeshBuilder class instead.
  21803. * 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
  21804. * to choose the wanted type.
  21805. * The parameter `size` (positive float, default 1) sets the polygon size.
  21806. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21807. * 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`.
  21808. * 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
  21809. * 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)`).
  21810. * 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
  21811. * 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.
  21812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21813. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21815. */
  21816. Mesh.CreatePolyhedron = function (name, options, scene) {
  21817. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21818. };
  21819. /**
  21820. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21821. * Please consider using the same method from the MeshBuilder class instead.
  21822. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21823. * 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`).
  21824. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21825. * 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.
  21826. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21829. */
  21830. Mesh.CreateIcoSphere = function (name, options, scene) {
  21831. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21832. };
  21833. /**
  21834. * Creates a decal mesh.
  21835. * Please consider using the same method from the MeshBuilder class instead.
  21836. * 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.
  21837. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21838. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21839. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21840. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21841. */
  21842. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21843. var options = {
  21844. position: position,
  21845. normal: normal,
  21846. size: size,
  21847. angle: angle
  21848. };
  21849. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21850. };
  21851. // Skeletons
  21852. /**
  21853. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21854. */
  21855. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21856. var source;
  21857. if (!this._sourcePositions) {
  21858. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21859. this._sourcePositions = new Float32Array(source);
  21860. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21861. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21862. }
  21863. }
  21864. return this._sourcePositions;
  21865. };
  21866. /**
  21867. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21868. */
  21869. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21870. var source;
  21871. if (!this._sourceNormals) {
  21872. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21873. this._sourceNormals = new Float32Array(source);
  21874. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21875. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21876. }
  21877. }
  21878. return this._sourceNormals;
  21879. };
  21880. /**
  21881. * Updates the vertex buffer by applying transformation from the bones.
  21882. * Returns the Mesh.
  21883. *
  21884. * @param {skeleton} skeleton to apply
  21885. */
  21886. Mesh.prototype.applySkeleton = function (skeleton) {
  21887. if (!this.geometry) {
  21888. return this;
  21889. }
  21890. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21891. return this;
  21892. }
  21893. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21894. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21895. return this;
  21896. }
  21897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21898. return this;
  21899. }
  21900. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21901. return this;
  21902. }
  21903. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21904. return this;
  21905. }
  21906. if (!this._sourcePositions) {
  21907. var submeshes = this.subMeshes.slice();
  21908. this.setPositionsForCPUSkinning();
  21909. this.subMeshes = submeshes;
  21910. }
  21911. if (!this._sourceNormals) {
  21912. this.setNormalsForCPUSkinning();
  21913. }
  21914. // positionsData checks for not being Float32Array will only pass at most once
  21915. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21916. if (!(positionsData instanceof Float32Array)) {
  21917. positionsData = new Float32Array(positionsData);
  21918. }
  21919. // normalsData checks for not being Float32Array will only pass at most once
  21920. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21921. if (!(normalsData instanceof Float32Array)) {
  21922. normalsData = new Float32Array(normalsData);
  21923. }
  21924. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21925. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21926. var needExtras = this.numBoneInfluencers > 4;
  21927. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21928. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21929. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21930. var tempVector3 = BABYLON.Vector3.Zero();
  21931. var finalMatrix = new BABYLON.Matrix();
  21932. var tempMatrix = new BABYLON.Matrix();
  21933. var matWeightIdx = 0;
  21934. var inf;
  21935. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21936. var weight;
  21937. for (inf = 0; inf < 4; inf++) {
  21938. weight = matricesWeightsData[matWeightIdx + inf];
  21939. if (weight > 0) {
  21940. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21941. finalMatrix.addToSelf(tempMatrix);
  21942. }
  21943. else
  21944. break;
  21945. }
  21946. if (needExtras) {
  21947. for (inf = 0; inf < 4; inf++) {
  21948. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21949. if (weight > 0) {
  21950. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21951. finalMatrix.addToSelf(tempMatrix);
  21952. }
  21953. else
  21954. break;
  21955. }
  21956. }
  21957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21958. tempVector3.toArray(positionsData, index);
  21959. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21960. tempVector3.toArray(normalsData, index);
  21961. finalMatrix.reset();
  21962. }
  21963. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21964. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21965. return this;
  21966. };
  21967. // Tools
  21968. /**
  21969. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21970. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21971. */
  21972. Mesh.MinMax = function (meshes) {
  21973. var minVector = null;
  21974. var maxVector = null;
  21975. meshes.forEach(function (mesh, index, array) {
  21976. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21977. if (!minVector) {
  21978. minVector = boundingBox.minimumWorld;
  21979. maxVector = boundingBox.maximumWorld;
  21980. }
  21981. else {
  21982. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21983. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21984. }
  21985. });
  21986. return {
  21987. min: minVector,
  21988. max: maxVector
  21989. };
  21990. };
  21991. /**
  21992. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21993. */
  21994. Mesh.Center = function (meshesOrMinMaxVector) {
  21995. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21996. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21997. };
  21998. /**
  21999. * Merge the array of meshes into a single mesh for performance reasons.
  22000. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22001. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22002. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22003. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22004. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22005. */
  22006. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22007. if (disposeSource === void 0) { disposeSource = true; }
  22008. var index;
  22009. if (!allow32BitsIndices) {
  22010. var totalVertices = 0;
  22011. // Counting vertices
  22012. for (index = 0; index < meshes.length; index++) {
  22013. if (meshes[index]) {
  22014. totalVertices += meshes[index].getTotalVertices();
  22015. if (totalVertices > 65536) {
  22016. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22017. return null;
  22018. }
  22019. }
  22020. }
  22021. }
  22022. // Merge
  22023. var vertexData;
  22024. var otherVertexData;
  22025. var indiceArray = new Array();
  22026. var source;
  22027. for (index = 0; index < meshes.length; index++) {
  22028. if (meshes[index]) {
  22029. meshes[index].computeWorldMatrix(true);
  22030. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22031. otherVertexData.transform(meshes[index].getWorldMatrix());
  22032. if (vertexData) {
  22033. vertexData.merge(otherVertexData);
  22034. }
  22035. else {
  22036. vertexData = otherVertexData;
  22037. source = meshes[index];
  22038. }
  22039. if (subdivideWithSubMeshes) {
  22040. indiceArray.push(meshes[index].getTotalIndices());
  22041. }
  22042. }
  22043. }
  22044. if (!meshSubclass) {
  22045. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22046. }
  22047. vertexData.applyToMesh(meshSubclass);
  22048. // Setting properties
  22049. meshSubclass.material = source.material;
  22050. meshSubclass.checkCollisions = source.checkCollisions;
  22051. // Cleaning
  22052. if (disposeSource) {
  22053. for (index = 0; index < meshes.length; index++) {
  22054. if (meshes[index]) {
  22055. meshes[index].dispose();
  22056. }
  22057. }
  22058. }
  22059. // Subdivide
  22060. if (subdivideWithSubMeshes) {
  22061. //-- Suppresions du submesh global
  22062. meshSubclass.releaseSubMeshes();
  22063. index = 0;
  22064. var offset = 0;
  22065. //-- aplique la subdivision en fonction du tableau d'indices
  22066. while (index < indiceArray.length) {
  22067. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22068. offset += indiceArray[index];
  22069. index++;
  22070. }
  22071. }
  22072. return meshSubclass;
  22073. };
  22074. return Mesh;
  22075. }(BABYLON.AbstractMesh));
  22076. // Consts
  22077. Mesh._FRONTSIDE = 0;
  22078. Mesh._BACKSIDE = 1;
  22079. Mesh._DOUBLESIDE = 2;
  22080. Mesh._DEFAULTSIDE = 0;
  22081. Mesh._NO_CAP = 0;
  22082. Mesh._CAP_START = 1;
  22083. Mesh._CAP_END = 2;
  22084. Mesh._CAP_ALL = 3;
  22085. BABYLON.Mesh = Mesh;
  22086. })(BABYLON || (BABYLON = {}));
  22087. //# sourceMappingURL=babylon.mesh.js.map
  22088. var BABYLON;
  22089. (function (BABYLON) {
  22090. var SubMesh = (function () {
  22091. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22092. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22093. this.materialIndex = materialIndex;
  22094. this.verticesStart = verticesStart;
  22095. this.verticesCount = verticesCount;
  22096. this.indexStart = indexStart;
  22097. this.indexCount = indexCount;
  22098. this._renderId = 0;
  22099. this._mesh = mesh;
  22100. this._renderingMesh = renderingMesh || mesh;
  22101. mesh.subMeshes.push(this);
  22102. this._trianglePlanes = [];
  22103. this._id = mesh.subMeshes.length - 1;
  22104. if (createBoundingBox) {
  22105. this.refreshBoundingInfo();
  22106. mesh.computeWorldMatrix(true);
  22107. }
  22108. }
  22109. Object.defineProperty(SubMesh.prototype, "effect", {
  22110. get: function () {
  22111. return this._materialEffect;
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. SubMesh.prototype.setEffect = function (effect, defines) {
  22117. if (this._materialEffect === effect) {
  22118. return;
  22119. }
  22120. this._materialDefines = defines;
  22121. this._materialEffect = effect;
  22122. };
  22123. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22124. get: function () {
  22125. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. /**
  22131. * Returns the submesh BoudingInfo object.
  22132. */
  22133. SubMesh.prototype.getBoundingInfo = function () {
  22134. if (this.IsGlobal) {
  22135. return this._mesh.getBoundingInfo();
  22136. }
  22137. return this._boundingInfo;
  22138. };
  22139. /**
  22140. * Sets the submesh BoundingInfo.
  22141. * Return the SubMesh.
  22142. */
  22143. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22144. this._boundingInfo = boundingInfo;
  22145. return this;
  22146. };
  22147. /**
  22148. * Returns the mesh of the current submesh.
  22149. */
  22150. SubMesh.prototype.getMesh = function () {
  22151. return this._mesh;
  22152. };
  22153. /**
  22154. * Returns the rendering mesh of the submesh.
  22155. */
  22156. SubMesh.prototype.getRenderingMesh = function () {
  22157. return this._renderingMesh;
  22158. };
  22159. /**
  22160. * Returns the submesh material.
  22161. */
  22162. SubMesh.prototype.getMaterial = function () {
  22163. var rootMaterial = this._renderingMesh.material;
  22164. if (rootMaterial && rootMaterial.getSubMaterial) {
  22165. var multiMaterial = rootMaterial;
  22166. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22167. if (this._currentMaterial !== effectiveMaterial) {
  22168. this._currentMaterial = effectiveMaterial;
  22169. if (this._materialDefines) {
  22170. this._materialDefines.markAllAsDirty();
  22171. }
  22172. }
  22173. return effectiveMaterial;
  22174. }
  22175. if (!rootMaterial) {
  22176. return this._mesh.getScene().defaultMaterial;
  22177. }
  22178. return rootMaterial;
  22179. };
  22180. // Methods
  22181. /**
  22182. * Sets a new updated BoundingInfo object to the submesh.
  22183. * Returns the SubMesh.
  22184. */
  22185. SubMesh.prototype.refreshBoundingInfo = function () {
  22186. this._lastColliderWorldVertices = null;
  22187. if (this.IsGlobal) {
  22188. return;
  22189. }
  22190. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22191. if (!data) {
  22192. this._boundingInfo = this._mesh._boundingInfo;
  22193. return;
  22194. }
  22195. var indices = this._renderingMesh.getIndices();
  22196. var extend;
  22197. //is this the only submesh?
  22198. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22199. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22200. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22201. }
  22202. else {
  22203. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22204. }
  22205. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22206. return this;
  22207. };
  22208. SubMesh.prototype._checkCollision = function (collider) {
  22209. return this.getBoundingInfo()._checkCollision(collider);
  22210. };
  22211. /**
  22212. * Updates the submesh BoundingInfo.
  22213. * Returns the Submesh.
  22214. */
  22215. SubMesh.prototype.updateBoundingInfo = function (world) {
  22216. if (!this.getBoundingInfo()) {
  22217. this.refreshBoundingInfo();
  22218. }
  22219. this.getBoundingInfo().update(world);
  22220. return this;
  22221. };
  22222. /**
  22223. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22224. * Boolean returned.
  22225. */
  22226. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22227. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22228. };
  22229. /**
  22230. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22231. * Boolean returned.
  22232. */
  22233. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22234. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22235. };
  22236. /**
  22237. * Renders the submesh.
  22238. * Returns it.
  22239. */
  22240. SubMesh.prototype.render = function (enableAlphaMode) {
  22241. this._renderingMesh.render(this, enableAlphaMode);
  22242. return this;
  22243. };
  22244. /**
  22245. * Returns a new Index Buffer.
  22246. * Type returned : WebGLBuffer.
  22247. */
  22248. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22249. if (!this._linesIndexBuffer) {
  22250. var linesIndices = [];
  22251. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22252. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22253. }
  22254. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22255. this.linesIndexCount = linesIndices.length;
  22256. }
  22257. return this._linesIndexBuffer;
  22258. };
  22259. /**
  22260. * True is the passed Ray intersects the submesh bounding box.
  22261. * Boolean returned.
  22262. */
  22263. SubMesh.prototype.canIntersects = function (ray) {
  22264. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22265. };
  22266. /**
  22267. * Returns an object IntersectionInfo.
  22268. */
  22269. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22270. var intersectInfo = null;
  22271. // LineMesh first as it's also a Mesh...
  22272. if (this._mesh instanceof BABYLON.LinesMesh) {
  22273. var lineMesh = this._mesh;
  22274. // Line test
  22275. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22276. var p0 = positions[indices[index]];
  22277. var p1 = positions[indices[index + 1]];
  22278. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22279. if (length < 0) {
  22280. continue;
  22281. }
  22282. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22283. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22284. if (fastCheck) {
  22285. break;
  22286. }
  22287. }
  22288. }
  22289. }
  22290. else {
  22291. // Triangles test
  22292. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22293. var p0 = positions[indices[index]];
  22294. var p1 = positions[indices[index + 1]];
  22295. var p2 = positions[indices[index + 2]];
  22296. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22297. if (currentIntersectInfo) {
  22298. if (currentIntersectInfo.distance < 0) {
  22299. continue;
  22300. }
  22301. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22302. intersectInfo = currentIntersectInfo;
  22303. intersectInfo.faceId = index / 3;
  22304. if (fastCheck) {
  22305. break;
  22306. }
  22307. }
  22308. }
  22309. }
  22310. }
  22311. return intersectInfo;
  22312. };
  22313. // Clone
  22314. /**
  22315. * Creates a new Submesh from the passed Mesh.
  22316. */
  22317. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22318. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22319. if (!this.IsGlobal) {
  22320. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22321. }
  22322. return result;
  22323. };
  22324. // Dispose
  22325. /**
  22326. * Disposes the Submesh.
  22327. * Returns nothing.
  22328. */
  22329. SubMesh.prototype.dispose = function () {
  22330. if (this._linesIndexBuffer) {
  22331. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22332. this._linesIndexBuffer = null;
  22333. }
  22334. // Remove from mesh
  22335. var index = this._mesh.subMeshes.indexOf(this);
  22336. this._mesh.subMeshes.splice(index, 1);
  22337. };
  22338. // Statics
  22339. /**
  22340. * Creates a new Submesh from the passed parameters :
  22341. * - materialIndex (integer) : the index of the main mesh material.
  22342. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22343. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22344. * - mesh (Mesh) : the main mesh to create the submesh from.
  22345. * - renderingMesh (optional Mesh) : rendering mesh.
  22346. */
  22347. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22348. var minVertexIndex = Number.MAX_VALUE;
  22349. var maxVertexIndex = -Number.MAX_VALUE;
  22350. renderingMesh = renderingMesh || mesh;
  22351. var indices = renderingMesh.getIndices();
  22352. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22353. var vertexIndex = indices[index];
  22354. if (vertexIndex < minVertexIndex)
  22355. minVertexIndex = vertexIndex;
  22356. if (vertexIndex > maxVertexIndex)
  22357. maxVertexIndex = vertexIndex;
  22358. }
  22359. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22360. };
  22361. return SubMesh;
  22362. }());
  22363. BABYLON.SubMesh = SubMesh;
  22364. })(BABYLON || (BABYLON = {}));
  22365. //# sourceMappingURL=babylon.subMesh.js.map
  22366. var BABYLON;
  22367. (function (BABYLON) {
  22368. var EffectFallbacks = (function () {
  22369. function EffectFallbacks() {
  22370. this._defines = {};
  22371. this._currentRank = 32;
  22372. this._maxRank = -1;
  22373. }
  22374. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22375. if (!this._defines[rank]) {
  22376. if (rank < this._currentRank) {
  22377. this._currentRank = rank;
  22378. }
  22379. if (rank > this._maxRank) {
  22380. this._maxRank = rank;
  22381. }
  22382. this._defines[rank] = new Array();
  22383. }
  22384. this._defines[rank].push(define);
  22385. };
  22386. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22387. this._meshRank = rank;
  22388. this._mesh = mesh;
  22389. if (rank < this._currentRank) {
  22390. this._currentRank = rank;
  22391. }
  22392. if (rank > this._maxRank) {
  22393. this._maxRank = rank;
  22394. }
  22395. };
  22396. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22397. get: function () {
  22398. return this._currentRank <= this._maxRank;
  22399. },
  22400. enumerable: true,
  22401. configurable: true
  22402. });
  22403. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22404. // First we try to switch to CPU skinning
  22405. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22406. this._mesh.computeBonesUsingShaders = false;
  22407. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22408. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22409. var scene = this._mesh.getScene();
  22410. for (var index = 0; index < scene.meshes.length; index++) {
  22411. var otherMesh = scene.meshes[index];
  22412. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22413. otherMesh.computeBonesUsingShaders = false;
  22414. }
  22415. }
  22416. }
  22417. else {
  22418. var currentFallbacks = this._defines[this._currentRank];
  22419. if (currentFallbacks) {
  22420. for (var index = 0; index < currentFallbacks.length; index++) {
  22421. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22422. }
  22423. }
  22424. this._currentRank++;
  22425. }
  22426. return currentDefines;
  22427. };
  22428. return EffectFallbacks;
  22429. }());
  22430. BABYLON.EffectFallbacks = EffectFallbacks;
  22431. var EffectCreationOptions = (function () {
  22432. function EffectCreationOptions() {
  22433. }
  22434. return EffectCreationOptions;
  22435. }());
  22436. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22437. var Effect = (function () {
  22438. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22439. var _this = this;
  22440. this.uniqueId = 0;
  22441. this._uniformBuffersNames = {};
  22442. this._isReady = false;
  22443. this._compilationError = "";
  22444. this._valueCache = {};
  22445. this.name = baseName;
  22446. if (attributesNamesOrOptions.attributes) {
  22447. var options = attributesNamesOrOptions;
  22448. this._engine = uniformsNamesOrEngine;
  22449. this._attributesNames = options.attributes;
  22450. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22451. this._samplers = options.samplers;
  22452. this.defines = options.defines;
  22453. this.onError = options.onError;
  22454. this.onCompiled = options.onCompiled;
  22455. this._fallbacks = options.fallbacks;
  22456. this._indexParameters = options.indexParameters;
  22457. if (options.uniformBuffersNames) {
  22458. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22459. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22460. }
  22461. }
  22462. }
  22463. else {
  22464. this._engine = engine;
  22465. this.defines = defines;
  22466. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22467. this._samplers = samplers;
  22468. this._attributesNames = attributesNamesOrOptions;
  22469. this.onError = onError;
  22470. this.onCompiled = onCompiled;
  22471. this._indexParameters = indexParameters;
  22472. this._fallbacks = fallbacks;
  22473. }
  22474. this.uniqueId = Effect._uniqueIdSeed++;
  22475. var vertexSource;
  22476. var fragmentSource;
  22477. if (baseName.vertexElement) {
  22478. vertexSource = document.getElementById(baseName.vertexElement);
  22479. if (!vertexSource) {
  22480. vertexSource = baseName.vertexElement;
  22481. }
  22482. }
  22483. else {
  22484. vertexSource = baseName.vertex || baseName;
  22485. }
  22486. if (baseName.fragmentElement) {
  22487. fragmentSource = document.getElementById(baseName.fragmentElement);
  22488. if (!fragmentSource) {
  22489. fragmentSource = baseName.fragmentElement;
  22490. }
  22491. }
  22492. else {
  22493. fragmentSource = baseName.fragment || baseName;
  22494. }
  22495. this._loadVertexShader(vertexSource, function (vertexCode) {
  22496. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22497. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22498. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22499. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22500. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22501. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22502. });
  22503. });
  22504. });
  22505. });
  22506. });
  22507. });
  22508. }
  22509. Object.defineProperty(Effect.prototype, "key", {
  22510. get: function () {
  22511. return this._key;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. // Properties
  22517. Effect.prototype.isReady = function () {
  22518. return this._isReady;
  22519. };
  22520. Effect.prototype.getProgram = function () {
  22521. return this._program;
  22522. };
  22523. Effect.prototype.getAttributesNames = function () {
  22524. return this._attributesNames;
  22525. };
  22526. Effect.prototype.getAttributeLocation = function (index) {
  22527. return this._attributes[index];
  22528. };
  22529. Effect.prototype.getAttributeLocationByName = function (name) {
  22530. var index = this._attributesNames.indexOf(name);
  22531. return this._attributes[index];
  22532. };
  22533. Effect.prototype.getAttributesCount = function () {
  22534. return this._attributes.length;
  22535. };
  22536. Effect.prototype.getUniformIndex = function (uniformName) {
  22537. return this._uniformsNames.indexOf(uniformName);
  22538. };
  22539. Effect.prototype.getUniform = function (uniformName) {
  22540. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22541. };
  22542. Effect.prototype.getSamplers = function () {
  22543. return this._samplers;
  22544. };
  22545. Effect.prototype.getCompilationError = function () {
  22546. return this._compilationError;
  22547. };
  22548. Effect.prototype.getVertexShaderSource = function () {
  22549. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22550. };
  22551. Effect.prototype.getFragmentShaderSource = function () {
  22552. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22553. };
  22554. // Methods
  22555. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22556. // DOM element ?
  22557. if (vertex instanceof HTMLElement) {
  22558. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22559. callback(vertexCode);
  22560. return;
  22561. }
  22562. // Base64 encoded ?
  22563. if (vertex.substr(0, 7) === "base64:") {
  22564. var vertexBinary = window.atob(vertex.substr(7));
  22565. callback(vertexBinary);
  22566. return;
  22567. }
  22568. // Is in local store ?
  22569. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22570. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22571. return;
  22572. }
  22573. var vertexShaderUrl;
  22574. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22575. vertexShaderUrl = vertex;
  22576. }
  22577. else {
  22578. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22579. }
  22580. // Vertex shader
  22581. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22582. };
  22583. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22584. // DOM element ?
  22585. if (fragment instanceof HTMLElement) {
  22586. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22587. callback(fragmentCode);
  22588. return;
  22589. }
  22590. // Base64 encoded ?
  22591. if (fragment.substr(0, 7) === "base64:") {
  22592. var fragmentBinary = window.atob(fragment.substr(7));
  22593. callback(fragmentBinary);
  22594. return;
  22595. }
  22596. // Is in local store ?
  22597. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22598. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22599. return;
  22600. }
  22601. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22602. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22603. return;
  22604. }
  22605. var fragmentShaderUrl;
  22606. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22607. fragmentShaderUrl = fragment;
  22608. }
  22609. else {
  22610. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22611. }
  22612. // Fragment shader
  22613. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22614. };
  22615. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22616. // Rebuild shaders source code
  22617. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22618. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22619. vertexCode = prefix + vertexCode;
  22620. fragmentCode = prefix + fragmentCode;
  22621. // Number lines of shaders source code
  22622. var i = 2;
  22623. var regex = /\n/gm;
  22624. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22625. i = 2;
  22626. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22627. // Dump shaders name and formatted source code
  22628. if (this.name.vertexElement) {
  22629. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22630. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22631. }
  22632. else if (this.name.vertex) {
  22633. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22634. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22635. }
  22636. else {
  22637. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22638. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22639. }
  22640. };
  22641. ;
  22642. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22643. var preparedSourceCode = this._processPrecision(sourceCode);
  22644. if (this._engine.webGLVersion == 1) {
  22645. callback(preparedSourceCode);
  22646. return;
  22647. }
  22648. // Already converted
  22649. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22650. callback(preparedSourceCode.replace("#version 300 es", ""));
  22651. return;
  22652. }
  22653. // Remove extensions
  22654. // #extension GL_OES_standard_derivatives : enable
  22655. // #extension GL_EXT_shader_texture_lod : enable
  22656. // #extension GL_EXT_frag_depth : enable
  22657. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22658. var result = preparedSourceCode.replace(regex, "");
  22659. // Migrate to GLSL v300
  22660. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22661. result = result.replace(/attribute[ \t]/g, "in ");
  22662. result = result.replace(/[ \t]attribute/g, " in");
  22663. if (isFragment) {
  22664. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22665. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22666. result = result.replace(/texture2D\(/g, "texture(");
  22667. result = result.replace(/textureCube\(/g, "texture(");
  22668. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22669. result = result.replace(/gl_FragColor/g, "glFragColor");
  22670. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22671. }
  22672. callback(result);
  22673. };
  22674. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22675. var _this = this;
  22676. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22677. var match = regex.exec(sourceCode);
  22678. var returnValue = new String(sourceCode);
  22679. while (match != null) {
  22680. var includeFile = match[1];
  22681. // Uniform declaration
  22682. if (includeFile.indexOf("__decl__") !== -1) {
  22683. includeFile = includeFile.replace(/__decl__/, "");
  22684. if (this._engine.webGLVersion != 1) {
  22685. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22686. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22687. }
  22688. includeFile = includeFile + "Declaration";
  22689. }
  22690. if (Effect.IncludesShadersStore[includeFile]) {
  22691. // Substitution
  22692. var includeContent = Effect.IncludesShadersStore[includeFile];
  22693. if (match[2]) {
  22694. var splits = match[3].split(",");
  22695. for (var index = 0; index < splits.length; index += 2) {
  22696. var source = new RegExp(splits[index], "g");
  22697. var dest = splits[index + 1];
  22698. includeContent = includeContent.replace(source, dest);
  22699. }
  22700. }
  22701. if (match[4]) {
  22702. var indexString = match[5];
  22703. if (indexString.indexOf("..") !== -1) {
  22704. var indexSplits = indexString.split("..");
  22705. var minIndex = parseInt(indexSplits[0]);
  22706. var maxIndex = parseInt(indexSplits[1]);
  22707. var sourceIncludeContent = includeContent.slice(0);
  22708. includeContent = "";
  22709. if (isNaN(maxIndex)) {
  22710. maxIndex = this._indexParameters[indexSplits[1]];
  22711. }
  22712. for (var i = minIndex; i < maxIndex; i++) {
  22713. if (this._engine.webGLVersion === 1) {
  22714. // Ubo replacement
  22715. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22716. return p1 + "{X}";
  22717. });
  22718. }
  22719. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22720. }
  22721. }
  22722. else {
  22723. if (this._engine.webGLVersion === 1) {
  22724. // Ubo replacement
  22725. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22726. return p1 + "{X}";
  22727. });
  22728. }
  22729. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22730. }
  22731. }
  22732. // Replace
  22733. returnValue = returnValue.replace(match[0], includeContent);
  22734. }
  22735. else {
  22736. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22737. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22738. Effect.IncludesShadersStore[includeFile] = fileContent;
  22739. _this._processIncludes(returnValue, callback);
  22740. });
  22741. return;
  22742. }
  22743. match = regex.exec(sourceCode);
  22744. }
  22745. callback(returnValue);
  22746. };
  22747. Effect.prototype._processPrecision = function (source) {
  22748. if (source.indexOf("precision highp float") === -1) {
  22749. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22750. source = "precision mediump float;\n" + source;
  22751. }
  22752. else {
  22753. source = "precision highp float;\n" + source;
  22754. }
  22755. }
  22756. else {
  22757. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22758. source = source.replace("precision highp float", "precision mediump float");
  22759. }
  22760. }
  22761. return source;
  22762. };
  22763. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22764. try {
  22765. var engine = this._engine;
  22766. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22767. if (engine.webGLVersion > 1) {
  22768. for (var name in this._uniformBuffersNames) {
  22769. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22770. }
  22771. }
  22772. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22773. this._attributes = engine.getAttributes(this._program, attributesNames);
  22774. var index;
  22775. for (index = 0; index < this._samplers.length; index++) {
  22776. var sampler = this.getUniform(this._samplers[index]);
  22777. if (sampler == null) {
  22778. this._samplers.splice(index, 1);
  22779. index--;
  22780. }
  22781. }
  22782. engine.bindSamplers(this);
  22783. this._compilationError = "";
  22784. this._isReady = true;
  22785. if (this.onCompiled) {
  22786. this.onCompiled(this);
  22787. }
  22788. }
  22789. catch (e) {
  22790. this._compilationError = e.message;
  22791. // Let's go through fallbacks then
  22792. BABYLON.Tools.Error("Unable to compile effect:");
  22793. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22794. return " " + uniform;
  22795. }));
  22796. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22797. return " " + attribute;
  22798. }));
  22799. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22800. BABYLON.Tools.Error("Error: " + this._compilationError);
  22801. if (fallbacks && fallbacks.isMoreFallbacks) {
  22802. BABYLON.Tools.Error("Trying next fallback.");
  22803. defines = fallbacks.reduce(defines);
  22804. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22805. }
  22806. else {
  22807. if (this.onError) {
  22808. this.onError(this, this._compilationError);
  22809. }
  22810. }
  22811. }
  22812. };
  22813. Object.defineProperty(Effect.prototype, "isSupported", {
  22814. get: function () {
  22815. return this._compilationError === "";
  22816. },
  22817. enumerable: true,
  22818. configurable: true
  22819. });
  22820. Effect.prototype._bindTexture = function (channel, texture) {
  22821. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22822. };
  22823. Effect.prototype.setTexture = function (channel, texture) {
  22824. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22825. };
  22826. Effect.prototype.setTextureArray = function (channel, textures) {
  22827. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22828. var initialPos = this._samplers.indexOf(channel);
  22829. for (var index = 1; index < textures.length; index++) {
  22830. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22831. }
  22832. }
  22833. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22834. };
  22835. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22836. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22837. };
  22838. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22839. var cache = this._valueCache[uniformName];
  22840. var flag = matrix.updateFlag;
  22841. if (cache !== undefined && cache === flag) {
  22842. return false;
  22843. }
  22844. this._valueCache[uniformName] = flag;
  22845. return true;
  22846. };
  22847. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22848. var cache = this._valueCache[uniformName];
  22849. if (!cache) {
  22850. cache = [x, y];
  22851. this._valueCache[uniformName] = cache;
  22852. return true;
  22853. }
  22854. var changed = false;
  22855. if (cache[0] !== x) {
  22856. cache[0] = x;
  22857. changed = true;
  22858. }
  22859. if (cache[1] !== y) {
  22860. cache[1] = y;
  22861. changed = true;
  22862. }
  22863. return changed;
  22864. };
  22865. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22866. var cache = this._valueCache[uniformName];
  22867. if (!cache) {
  22868. cache = [x, y, z];
  22869. this._valueCache[uniformName] = cache;
  22870. return true;
  22871. }
  22872. var changed = false;
  22873. if (cache[0] !== x) {
  22874. cache[0] = x;
  22875. changed = true;
  22876. }
  22877. if (cache[1] !== y) {
  22878. cache[1] = y;
  22879. changed = true;
  22880. }
  22881. if (cache[2] !== z) {
  22882. cache[2] = z;
  22883. changed = true;
  22884. }
  22885. return changed;
  22886. };
  22887. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22888. var cache = this._valueCache[uniformName];
  22889. if (!cache) {
  22890. cache = [x, y, z, w];
  22891. this._valueCache[uniformName] = cache;
  22892. return true;
  22893. }
  22894. var changed = false;
  22895. if (cache[0] !== x) {
  22896. cache[0] = x;
  22897. changed = true;
  22898. }
  22899. if (cache[1] !== y) {
  22900. cache[1] = y;
  22901. changed = true;
  22902. }
  22903. if (cache[2] !== z) {
  22904. cache[2] = z;
  22905. changed = true;
  22906. }
  22907. if (cache[3] !== w) {
  22908. cache[3] = w;
  22909. changed = true;
  22910. }
  22911. return changed;
  22912. };
  22913. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22914. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22915. return;
  22916. }
  22917. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22918. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22919. };
  22920. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22921. this._engine.bindUniformBlock(this._program, blockName, index);
  22922. };
  22923. Effect.prototype.setIntArray = function (uniformName, array) {
  22924. this._valueCache[uniformName] = null;
  22925. this._engine.setIntArray(this.getUniform(uniformName), array);
  22926. return this;
  22927. };
  22928. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22929. this._valueCache[uniformName] = null;
  22930. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22931. return this;
  22932. };
  22933. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22934. this._valueCache[uniformName] = null;
  22935. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22936. return this;
  22937. };
  22938. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22939. this._valueCache[uniformName] = null;
  22940. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22941. return this;
  22942. };
  22943. Effect.prototype.setFloatArray = function (uniformName, array) {
  22944. this._valueCache[uniformName] = null;
  22945. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22946. return this;
  22947. };
  22948. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22949. this._valueCache[uniformName] = null;
  22950. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22951. return this;
  22952. };
  22953. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22954. this._valueCache[uniformName] = null;
  22955. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22956. return this;
  22957. };
  22958. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22959. this._valueCache[uniformName] = null;
  22960. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22961. return this;
  22962. };
  22963. Effect.prototype.setArray = function (uniformName, array) {
  22964. this._valueCache[uniformName] = null;
  22965. this._engine.setArray(this.getUniform(uniformName), array);
  22966. return this;
  22967. };
  22968. Effect.prototype.setArray2 = function (uniformName, array) {
  22969. this._valueCache[uniformName] = null;
  22970. this._engine.setArray2(this.getUniform(uniformName), array);
  22971. return this;
  22972. };
  22973. Effect.prototype.setArray3 = function (uniformName, array) {
  22974. this._valueCache[uniformName] = null;
  22975. this._engine.setArray3(this.getUniform(uniformName), array);
  22976. return this;
  22977. };
  22978. Effect.prototype.setArray4 = function (uniformName, array) {
  22979. this._valueCache[uniformName] = null;
  22980. this._engine.setArray4(this.getUniform(uniformName), array);
  22981. return this;
  22982. };
  22983. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22984. if (!matrices) {
  22985. return;
  22986. }
  22987. this._valueCache[uniformName] = null;
  22988. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22989. return this;
  22990. };
  22991. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22992. if (this._cacheMatrix(uniformName, matrix)) {
  22993. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22994. }
  22995. return this;
  22996. };
  22997. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22998. this._valueCache[uniformName] = null;
  22999. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23000. return this;
  23001. };
  23002. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23003. this._valueCache[uniformName] = null;
  23004. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23005. return this;
  23006. };
  23007. Effect.prototype.setFloat = function (uniformName, value) {
  23008. var cache = this._valueCache[uniformName];
  23009. if (cache !== undefined && cache === value)
  23010. return this;
  23011. this._valueCache[uniformName] = value;
  23012. this._engine.setFloat(this.getUniform(uniformName), value);
  23013. return this;
  23014. };
  23015. Effect.prototype.setBool = function (uniformName, bool) {
  23016. var cache = this._valueCache[uniformName];
  23017. if (cache !== undefined && cache === bool)
  23018. return this;
  23019. this._valueCache[uniformName] = bool;
  23020. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23021. return this;
  23022. };
  23023. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23024. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23025. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23026. }
  23027. return this;
  23028. };
  23029. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23030. if (this._cacheFloat2(uniformName, x, y)) {
  23031. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23032. }
  23033. return this;
  23034. };
  23035. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23036. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23037. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23038. }
  23039. return this;
  23040. };
  23041. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23042. if (this._cacheFloat3(uniformName, x, y, z)) {
  23043. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23044. }
  23045. return this;
  23046. };
  23047. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23048. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23049. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23050. }
  23051. return this;
  23052. };
  23053. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23054. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23055. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23056. }
  23057. return this;
  23058. };
  23059. Effect.prototype.setColor3 = function (uniformName, color3) {
  23060. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23061. this._engine.setColor3(this.getUniform(uniformName), color3);
  23062. }
  23063. return this;
  23064. };
  23065. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23066. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23067. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23068. }
  23069. return this;
  23070. };
  23071. Effect.prototype._recombineShader = function (node) {
  23072. if (node.define) {
  23073. if (node.condition) {
  23074. var defineIndex = this.defines.indexOf("#define " + node.define);
  23075. if (defineIndex === -1) {
  23076. return null;
  23077. }
  23078. var nextComma = this.defines.indexOf("\n", defineIndex);
  23079. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23080. var condition = defineValue + node.condition;
  23081. if (!eval(condition)) {
  23082. return null;
  23083. }
  23084. }
  23085. else if (node.ndef) {
  23086. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23087. return null;
  23088. }
  23089. }
  23090. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23091. return null;
  23092. }
  23093. }
  23094. var result = "";
  23095. for (var index = 0; index < node.children.length; index++) {
  23096. var line = node.children[index];
  23097. if (line.children) {
  23098. var combined = this._recombineShader(line);
  23099. if (combined !== null) {
  23100. result += combined + "\r\n";
  23101. }
  23102. continue;
  23103. }
  23104. if (line.length > 0) {
  23105. result += line + "\r\n";
  23106. }
  23107. }
  23108. return result;
  23109. };
  23110. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23111. var root = {
  23112. children: []
  23113. };
  23114. var currentNode = root;
  23115. var lines = shaderString.split("\n");
  23116. for (var index = 0; index < lines.length; index++) {
  23117. var line = lines[index].trim();
  23118. // #ifdef
  23119. var pos = line.indexOf("#ifdef ");
  23120. if (pos !== -1) {
  23121. var define = line.substr(pos + 7);
  23122. var newNode = {
  23123. condition: null,
  23124. ndef: false,
  23125. define: define,
  23126. children: [],
  23127. parent: currentNode
  23128. };
  23129. currentNode.children.push(newNode);
  23130. currentNode = newNode;
  23131. continue;
  23132. }
  23133. // #ifndef
  23134. var pos = line.indexOf("#ifndef ");
  23135. if (pos !== -1) {
  23136. var define = line.substr(pos + 8);
  23137. newNode = {
  23138. condition: null,
  23139. define: define,
  23140. ndef: true,
  23141. children: [],
  23142. parent: currentNode
  23143. };
  23144. currentNode.children.push(newNode);
  23145. currentNode = newNode;
  23146. continue;
  23147. }
  23148. // #if
  23149. var pos = line.indexOf("#if ");
  23150. if (pos !== -1) {
  23151. var define = line.substr(pos + 4).trim();
  23152. var conditionPos = define.indexOf(" ");
  23153. newNode = {
  23154. condition: define.substr(conditionPos + 1),
  23155. define: define.substr(0, conditionPos),
  23156. ndef: false,
  23157. children: [],
  23158. parent: currentNode
  23159. };
  23160. currentNode.children.push(newNode);
  23161. currentNode = newNode;
  23162. continue;
  23163. }
  23164. // #endif
  23165. pos = line.indexOf("#endif");
  23166. if (pos !== -1) {
  23167. currentNode = currentNode.parent;
  23168. continue;
  23169. }
  23170. currentNode.children.push(line);
  23171. }
  23172. // Recombine
  23173. return this._recombineShader(root);
  23174. };
  23175. return Effect;
  23176. }());
  23177. Effect._uniqueIdSeed = 0;
  23178. Effect._baseCache = {};
  23179. // Statics
  23180. Effect.ShadersStore = {};
  23181. Effect.IncludesShadersStore = {};
  23182. BABYLON.Effect = Effect;
  23183. })(BABYLON || (BABYLON = {}));
  23184. //# sourceMappingURL=babylon.effect.js.map
  23185. var BABYLON;
  23186. (function (BABYLON) {
  23187. var MaterialHelper = (function () {
  23188. function MaterialHelper() {
  23189. }
  23190. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23191. if (defines._areMiscDirty) {
  23192. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23193. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23194. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23195. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23196. }
  23197. };
  23198. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  23199. var changed = false;
  23200. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23201. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23202. changed = true;
  23203. }
  23204. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  23205. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23206. changed = true;
  23207. }
  23208. if (defines["INSTANCES"] !== useInstances) {
  23209. defines["INSTANCES"] = useInstances;
  23210. changed = true;
  23211. }
  23212. if (changed) {
  23213. defines.markAsUnprocessed();
  23214. }
  23215. };
  23216. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23217. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23218. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23219. return;
  23220. }
  23221. defines._normals = defines._needNormals;
  23222. defines._uvs = defines._needUVs;
  23223. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23224. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23225. defines["TANGENT"] = true;
  23226. }
  23227. if (defines._needUVs) {
  23228. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23229. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23230. }
  23231. else {
  23232. defines["UV1"] = false;
  23233. defines["UV2"] = false;
  23234. }
  23235. if (useVertexColor) {
  23236. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23237. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23238. }
  23239. if (useBones) {
  23240. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23241. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23242. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23243. }
  23244. else {
  23245. defines["NUM_BONE_INFLUENCERS"] = 0;
  23246. defines["BonesPerMesh"] = 0;
  23247. }
  23248. }
  23249. if (useMorphTargets) {
  23250. if (mesh.morphTargetManager) {
  23251. var manager = mesh.morphTargetManager;
  23252. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23253. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23254. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23255. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23256. }
  23257. else {
  23258. defines["MORPHTARGETS_TANGENT"] = false;
  23259. defines["MORPHTARGETS_NORMAL"] = false;
  23260. defines["MORPHTARGETS"] = false;
  23261. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23262. }
  23263. }
  23264. };
  23265. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23266. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23267. if (disableLighting === void 0) { disableLighting = false; }
  23268. if (!defines._areLightsDirty) {
  23269. return defines._needNormals;
  23270. }
  23271. var lightIndex = 0;
  23272. var needNormals = false;
  23273. var needRebuild = false;
  23274. var lightmapMode = false;
  23275. var shadowEnabled = false;
  23276. var specularEnabled = false;
  23277. if (scene.lightsEnabled && !disableLighting) {
  23278. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23279. var light = _a[_i];
  23280. needNormals = true;
  23281. if (defines["LIGHT" + lightIndex] === undefined) {
  23282. needRebuild = true;
  23283. }
  23284. defines["LIGHT" + lightIndex] = true;
  23285. defines["SPOTLIGHT" + lightIndex] = false;
  23286. defines["HEMILIGHT" + lightIndex] = false;
  23287. defines["POINTLIGHT" + lightIndex] = false;
  23288. defines["DIRLIGHT" + lightIndex] = false;
  23289. var type;
  23290. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23291. type = "SPOTLIGHT" + lightIndex;
  23292. }
  23293. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23294. type = "HEMILIGHT" + lightIndex;
  23295. }
  23296. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23297. type = "POINTLIGHT" + lightIndex;
  23298. }
  23299. else {
  23300. type = "DIRLIGHT" + lightIndex;
  23301. }
  23302. defines[type] = true;
  23303. // Specular
  23304. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23305. specularEnabled = true;
  23306. }
  23307. // Shadows
  23308. defines["SHADOW" + lightIndex] = false;
  23309. defines["SHADOWPCF" + lightIndex] = false;
  23310. defines["SHADOWESM" + lightIndex] = false;
  23311. defines["SHADOWCUBE" + lightIndex] = false;
  23312. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23313. var shadowGenerator = light.getShadowGenerator();
  23314. if (shadowGenerator) {
  23315. shadowEnabled = true;
  23316. shadowGenerator.prepareDefines(defines, lightIndex);
  23317. }
  23318. }
  23319. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23320. lightmapMode = true;
  23321. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23322. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23323. }
  23324. else {
  23325. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23326. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23327. }
  23328. lightIndex++;
  23329. if (lightIndex === maxSimultaneousLights)
  23330. break;
  23331. }
  23332. }
  23333. defines["SPECULARTERM"] = specularEnabled;
  23334. defines["SHADOWS"] = shadowEnabled;
  23335. // Resetting all other lights if any
  23336. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23337. if (defines["LIGHT" + index] !== undefined) {
  23338. defines["LIGHT" + index] = false;
  23339. }
  23340. }
  23341. var caps = scene.getEngine().getCaps();
  23342. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23343. needRebuild = true;
  23344. }
  23345. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  23346. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23347. if (needRebuild) {
  23348. defines.rebuild();
  23349. }
  23350. return needNormals;
  23351. };
  23352. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23353. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23354. var uniformsList, uniformBuffersList, samplersList, defines;
  23355. if (uniformsListOrOptions.uniformsNames) {
  23356. var options = uniformsListOrOptions;
  23357. uniformsList = options.uniformsNames;
  23358. uniformBuffersList = options.uniformBuffersNames;
  23359. samplersList = options.samplers;
  23360. defines = options.defines;
  23361. maxSimultaneousLights = options.maxSimultaneousLights;
  23362. }
  23363. else {
  23364. uniformsList = uniformsListOrOptions;
  23365. }
  23366. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23367. if (!defines["LIGHT" + lightIndex]) {
  23368. break;
  23369. }
  23370. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23371. if (uniformBuffersList) {
  23372. uniformBuffersList.push("Light" + lightIndex);
  23373. }
  23374. samplersList.push("shadowSampler" + lightIndex);
  23375. }
  23376. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23377. uniformsList.push("morphTargetInfluences");
  23378. }
  23379. };
  23380. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23381. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23382. if (!defines["SHADOWS"]) {
  23383. return;
  23384. }
  23385. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23386. if (!defines["LIGHT" + lightIndex]) {
  23387. break;
  23388. }
  23389. if (lightIndex > 0) {
  23390. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23391. }
  23392. if (defines["SHADOW" + lightIndex]) {
  23393. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23394. }
  23395. if (defines["SHADOWPCF" + lightIndex]) {
  23396. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23397. }
  23398. if (defines["SHADOWESM" + lightIndex]) {
  23399. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23400. }
  23401. }
  23402. };
  23403. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23404. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23405. if (influencers > 0) {
  23406. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23407. var manager = mesh.morphTargetManager;
  23408. var normal = manager.supportsNormals && defines["NORMAL"];
  23409. var tangent = manager.supportsTangents && defines["TANGENT"];
  23410. for (var index = 0; index < influencers; index++) {
  23411. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23412. if (normal) {
  23413. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23414. }
  23415. if (tangent) {
  23416. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23417. }
  23418. if (attribs.length > maxAttributesCount) {
  23419. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23420. }
  23421. }
  23422. }
  23423. };
  23424. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23425. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23426. fallbacks.addCPUSkinningFallback(0, mesh);
  23427. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23428. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23429. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23430. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23431. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23432. }
  23433. }
  23434. };
  23435. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23436. if (defines["INSTANCES"]) {
  23437. attribs.push("world0");
  23438. attribs.push("world1");
  23439. attribs.push("world2");
  23440. attribs.push("world3");
  23441. }
  23442. };
  23443. // Bindings
  23444. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23445. if (light.shadowEnabled && mesh.receiveShadows) {
  23446. var shadowGenerator = light.getShadowGenerator();
  23447. if (shadowGenerator) {
  23448. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23449. }
  23450. }
  23451. return depthValuesAlreadySet;
  23452. };
  23453. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23454. light.transferToEffect(effect, lightIndex + "");
  23455. };
  23456. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23457. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23458. var lightIndex = 0;
  23459. var depthValuesAlreadySet = false;
  23460. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23461. var light = _a[_i];
  23462. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23463. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23464. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23465. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23466. if (defines["SPECULARTERM"]) {
  23467. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23468. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23469. }
  23470. // Shadows
  23471. if (scene.shadowsEnabled) {
  23472. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23473. }
  23474. light._uniformBuffer.update();
  23475. lightIndex++;
  23476. if (lightIndex === maxSimultaneousLights)
  23477. break;
  23478. }
  23479. };
  23480. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23481. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23482. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23483. effect.setColor3("vFogColor", scene.fogColor);
  23484. }
  23485. };
  23486. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23487. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23488. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23489. if (matrices) {
  23490. effect.setMatrices("mBones", matrices);
  23491. }
  23492. }
  23493. };
  23494. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23495. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23496. return;
  23497. }
  23498. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23499. };
  23500. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23501. if (defines["LOGARITHMICDEPTH"]) {
  23502. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23503. }
  23504. };
  23505. MaterialHelper.BindClipPlane = function (effect, scene) {
  23506. if (scene.clipPlane) {
  23507. var clipPlane = scene.clipPlane;
  23508. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23509. }
  23510. };
  23511. return MaterialHelper;
  23512. }());
  23513. BABYLON.MaterialHelper = MaterialHelper;
  23514. })(BABYLON || (BABYLON = {}));
  23515. //# sourceMappingURL=babylon.materialHelper.js.map
  23516. var BABYLON;
  23517. (function (BABYLON) {
  23518. var MaterialDefines = (function () {
  23519. function MaterialDefines() {
  23520. this._isDirty = true;
  23521. this._areLightsDirty = true;
  23522. this._areAttributesDirty = true;
  23523. this._areTexturesDirty = true;
  23524. this._areFresnelDirty = true;
  23525. this._areMiscDirty = true;
  23526. this._normals = false;
  23527. this._uvs = false;
  23528. this._needNormals = false;
  23529. this._needUVs = false;
  23530. }
  23531. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23532. get: function () {
  23533. return this._isDirty;
  23534. },
  23535. enumerable: true,
  23536. configurable: true
  23537. });
  23538. MaterialDefines.prototype.markAsProcessed = function () {
  23539. this._isDirty = false;
  23540. this._areAttributesDirty = false;
  23541. this._areTexturesDirty = false;
  23542. this._areFresnelDirty = false;
  23543. this._areLightsDirty = false;
  23544. this._areMiscDirty = false;
  23545. };
  23546. MaterialDefines.prototype.markAsUnprocessed = function () {
  23547. this._isDirty = true;
  23548. };
  23549. MaterialDefines.prototype.markAllAsDirty = function () {
  23550. this._areTexturesDirty = true;
  23551. this._areAttributesDirty = true;
  23552. this._areLightsDirty = true;
  23553. this._areFresnelDirty = true;
  23554. this._areMiscDirty = true;
  23555. this._isDirty = true;
  23556. };
  23557. MaterialDefines.prototype.markAsLightDirty = function () {
  23558. this._areLightsDirty = true;
  23559. this._isDirty = true;
  23560. };
  23561. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23562. this._areAttributesDirty = true;
  23563. this._isDirty = true;
  23564. };
  23565. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23566. this._areTexturesDirty = true;
  23567. this._isDirty = true;
  23568. };
  23569. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23570. this._areFresnelDirty = true;
  23571. this._isDirty = true;
  23572. };
  23573. MaterialDefines.prototype.markAsMiscDirty = function () {
  23574. this._areMiscDirty = true;
  23575. this._isDirty = true;
  23576. };
  23577. MaterialDefines.prototype.rebuild = function () {
  23578. if (this._keys) {
  23579. delete this._keys;
  23580. }
  23581. this._keys = [];
  23582. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23583. var key = _a[_i];
  23584. if (key[0] === "_") {
  23585. continue;
  23586. }
  23587. this._keys.push(key);
  23588. }
  23589. };
  23590. MaterialDefines.prototype.isEqual = function (other) {
  23591. if (this._keys.length !== other._keys.length) {
  23592. return false;
  23593. }
  23594. for (var index = 0; index < this._keys.length; index++) {
  23595. var prop = this._keys[index];
  23596. if (this[prop] !== other[prop]) {
  23597. return false;
  23598. }
  23599. }
  23600. return true;
  23601. };
  23602. MaterialDefines.prototype.cloneTo = function (other) {
  23603. if (this._keys.length !== other._keys.length) {
  23604. other._keys = this._keys.slice(0);
  23605. }
  23606. for (var index = 0; index < this._keys.length; index++) {
  23607. var prop = this._keys[index];
  23608. other[prop] = this[prop];
  23609. }
  23610. };
  23611. MaterialDefines.prototype.reset = function () {
  23612. for (var index = 0; index < this._keys.length; index++) {
  23613. var prop = this._keys[index];
  23614. if (typeof (this[prop]) === "number") {
  23615. this[prop] = 0;
  23616. }
  23617. else {
  23618. this[prop] = false;
  23619. }
  23620. }
  23621. };
  23622. MaterialDefines.prototype.toString = function () {
  23623. var result = "";
  23624. for (var index = 0; index < this._keys.length; index++) {
  23625. var prop = this._keys[index];
  23626. var value = this[prop];
  23627. if (typeof (value) === "number") {
  23628. result += "#define " + prop + " " + this[prop] + "\n";
  23629. }
  23630. else if (value) {
  23631. result += "#define " + prop + "\n";
  23632. }
  23633. }
  23634. return result;
  23635. };
  23636. return MaterialDefines;
  23637. }());
  23638. BABYLON.MaterialDefines = MaterialDefines;
  23639. var Material = (function () {
  23640. function Material(name, scene, doNotAdd) {
  23641. this.checkReadyOnEveryCall = false;
  23642. this.checkReadyOnlyOnce = false;
  23643. this.state = "";
  23644. this.alpha = 1.0;
  23645. this._backFaceCulling = true;
  23646. this.doNotSerialize = false;
  23647. this.storeEffectOnSubMeshes = false;
  23648. /**
  23649. * An event triggered when the material is disposed.
  23650. * @type {BABYLON.Observable}
  23651. */
  23652. this.onDisposeObservable = new BABYLON.Observable();
  23653. /**
  23654. * An event triggered when the material is bound.
  23655. * @type {BABYLON.Observable}
  23656. */
  23657. this.onBindObservable = new BABYLON.Observable();
  23658. /**
  23659. * An event triggered when the material is unbound.
  23660. * @type {BABYLON.Observable}
  23661. */
  23662. this.onUnBindObservable = new BABYLON.Observable();
  23663. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23664. this.disableDepthWrite = false;
  23665. this._fogEnabled = true;
  23666. this.pointSize = 1.0;
  23667. this.zOffset = 0;
  23668. this._wasPreviouslyReady = false;
  23669. this._fillMode = Material.TriangleFillMode;
  23670. this.name = name;
  23671. this.id = name;
  23672. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23673. if (this._scene.useRightHandedSystem) {
  23674. this.sideOrientation = Material.ClockWiseSideOrientation;
  23675. }
  23676. else {
  23677. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23678. }
  23679. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23680. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23681. if (!doNotAdd) {
  23682. this._scene.materials.push(this);
  23683. }
  23684. }
  23685. Object.defineProperty(Material, "TriangleFillMode", {
  23686. get: function () {
  23687. return Material._TriangleFillMode;
  23688. },
  23689. enumerable: true,
  23690. configurable: true
  23691. });
  23692. Object.defineProperty(Material, "WireFrameFillMode", {
  23693. get: function () {
  23694. return Material._WireFrameFillMode;
  23695. },
  23696. enumerable: true,
  23697. configurable: true
  23698. });
  23699. Object.defineProperty(Material, "PointFillMode", {
  23700. get: function () {
  23701. return Material._PointFillMode;
  23702. },
  23703. enumerable: true,
  23704. configurable: true
  23705. });
  23706. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23707. get: function () {
  23708. return Material._ClockWiseSideOrientation;
  23709. },
  23710. enumerable: true,
  23711. configurable: true
  23712. });
  23713. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23714. get: function () {
  23715. return Material._CounterClockWiseSideOrientation;
  23716. },
  23717. enumerable: true,
  23718. configurable: true
  23719. });
  23720. Object.defineProperty(Material, "TextureDirtyFlag", {
  23721. get: function () {
  23722. return Material._TextureDirtyFlag;
  23723. },
  23724. enumerable: true,
  23725. configurable: true
  23726. });
  23727. Object.defineProperty(Material, "LightDirtyFlag", {
  23728. get: function () {
  23729. return Material._LightDirtyFlag;
  23730. },
  23731. enumerable: true,
  23732. configurable: true
  23733. });
  23734. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23735. get: function () {
  23736. return Material._FresnelDirtyFlag;
  23737. },
  23738. enumerable: true,
  23739. configurable: true
  23740. });
  23741. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23742. get: function () {
  23743. return Material._AttributesDirtyFlag;
  23744. },
  23745. enumerable: true,
  23746. configurable: true
  23747. });
  23748. Object.defineProperty(Material, "MiscDirtyFlag", {
  23749. get: function () {
  23750. return Material._MiscDirtyFlag;
  23751. },
  23752. enumerable: true,
  23753. configurable: true
  23754. });
  23755. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23756. get: function () {
  23757. return this._backFaceCulling;
  23758. },
  23759. set: function (value) {
  23760. if (this._backFaceCulling === value) {
  23761. return;
  23762. }
  23763. this._backFaceCulling = value;
  23764. this.markAsDirty(Material.TextureDirtyFlag);
  23765. },
  23766. enumerable: true,
  23767. configurable: true
  23768. });
  23769. Object.defineProperty(Material.prototype, "onDispose", {
  23770. set: function (callback) {
  23771. if (this._onDisposeObserver) {
  23772. this.onDisposeObservable.remove(this._onDisposeObserver);
  23773. }
  23774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23775. },
  23776. enumerable: true,
  23777. configurable: true
  23778. });
  23779. Object.defineProperty(Material.prototype, "onBind", {
  23780. set: function (callback) {
  23781. if (this._onBindObserver) {
  23782. this.onBindObservable.remove(this._onBindObserver);
  23783. }
  23784. this._onBindObserver = this.onBindObservable.add(callback);
  23785. },
  23786. enumerable: true,
  23787. configurable: true
  23788. });
  23789. Object.defineProperty(Material.prototype, "fogEnabled", {
  23790. get: function () {
  23791. return this._fogEnabled;
  23792. },
  23793. set: function (value) {
  23794. if (this._fogEnabled === value) {
  23795. return;
  23796. }
  23797. this._fogEnabled = value;
  23798. this.markAsDirty(Material.MiscDirtyFlag);
  23799. },
  23800. enumerable: true,
  23801. configurable: true
  23802. });
  23803. Object.defineProperty(Material.prototype, "wireframe", {
  23804. get: function () {
  23805. return this._fillMode === Material.WireFrameFillMode;
  23806. },
  23807. set: function (value) {
  23808. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. Object.defineProperty(Material.prototype, "pointsCloud", {
  23814. get: function () {
  23815. return this._fillMode === Material.PointFillMode;
  23816. },
  23817. set: function (value) {
  23818. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23819. },
  23820. enumerable: true,
  23821. configurable: true
  23822. });
  23823. Object.defineProperty(Material.prototype, "fillMode", {
  23824. get: function () {
  23825. return this._fillMode;
  23826. },
  23827. set: function (value) {
  23828. if (this._fillMode === value) {
  23829. return;
  23830. }
  23831. this._fillMode = value;
  23832. this.markAsDirty(Material.MiscDirtyFlag);
  23833. },
  23834. enumerable: true,
  23835. configurable: true
  23836. });
  23837. /**
  23838. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23839. * subclasses should override adding information pertainent to themselves
  23840. */
  23841. Material.prototype.toString = function (fullDetails) {
  23842. var ret = "Name: " + this.name;
  23843. if (fullDetails) {
  23844. }
  23845. return ret;
  23846. };
  23847. /**
  23848. * Child classes can use it to update shaders
  23849. */
  23850. Material.prototype.markAsDirty = function (flag) {
  23851. };
  23852. Material.prototype.getClassName = function () {
  23853. return "Material";
  23854. };
  23855. Object.defineProperty(Material.prototype, "isFrozen", {
  23856. get: function () {
  23857. return this.checkReadyOnlyOnce;
  23858. },
  23859. enumerable: true,
  23860. configurable: true
  23861. });
  23862. Material.prototype.freeze = function () {
  23863. this.checkReadyOnlyOnce = true;
  23864. };
  23865. Material.prototype.unfreeze = function () {
  23866. this.checkReadyOnlyOnce = false;
  23867. };
  23868. Material.prototype.isReady = function (mesh, useInstances) {
  23869. return true;
  23870. };
  23871. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23872. return false;
  23873. };
  23874. Material.prototype.getEffect = function () {
  23875. return this._effect;
  23876. };
  23877. Material.prototype.getScene = function () {
  23878. return this._scene;
  23879. };
  23880. Material.prototype.needAlphaBlending = function () {
  23881. return (this.alpha < 1.0);
  23882. };
  23883. Material.prototype.needAlphaTesting = function () {
  23884. return false;
  23885. };
  23886. Material.prototype.getAlphaTestTexture = function () {
  23887. return null;
  23888. };
  23889. Material.prototype.markDirty = function () {
  23890. this._wasPreviouslyReady = false;
  23891. };
  23892. Material.prototype._preBind = function (effect) {
  23893. var engine = this._scene.getEngine();
  23894. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23895. engine.enableEffect(effect ? effect : this._effect);
  23896. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23897. };
  23898. Material.prototype.bind = function (world, mesh) {
  23899. };
  23900. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23901. };
  23902. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23903. };
  23904. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23905. sceneUbo.bindToEffect(effect, "Scene");
  23906. };
  23907. Material.prototype.bindView = function (effect) {
  23908. if (!this._useUBO) {
  23909. effect.setMatrix("view", this.getScene().getViewMatrix());
  23910. }
  23911. else {
  23912. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23913. }
  23914. };
  23915. Material.prototype.bindViewProjection = function (effect) {
  23916. if (!this._useUBO) {
  23917. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23918. }
  23919. else {
  23920. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23921. }
  23922. };
  23923. Material.prototype._afterBind = function (mesh) {
  23924. this._scene._cachedMaterial = this;
  23925. this.onBindObservable.notifyObservers(mesh);
  23926. if (this.disableDepthWrite) {
  23927. var engine = this._scene.getEngine();
  23928. this._cachedDepthWriteState = engine.getDepthWrite();
  23929. engine.setDepthWrite(false);
  23930. }
  23931. };
  23932. Material.prototype.unbind = function () {
  23933. this.onUnBindObservable.notifyObservers(this);
  23934. if (this.disableDepthWrite) {
  23935. var engine = this._scene.getEngine();
  23936. engine.setDepthWrite(this._cachedDepthWriteState);
  23937. }
  23938. };
  23939. Material.prototype.clone = function (name) {
  23940. return null;
  23941. };
  23942. Material.prototype.getBindedMeshes = function () {
  23943. var result = new Array();
  23944. for (var index = 0; index < this._scene.meshes.length; index++) {
  23945. var mesh = this._scene.meshes[index];
  23946. if (mesh.material === this) {
  23947. result.push(mesh);
  23948. }
  23949. }
  23950. return result;
  23951. };
  23952. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23953. // Animations
  23954. this.getScene().stopAnimation(this);
  23955. // Remove from scene
  23956. var index = this._scene.materials.indexOf(this);
  23957. if (index >= 0) {
  23958. this._scene.materials.splice(index, 1);
  23959. }
  23960. // Remove from meshes
  23961. for (index = 0; index < this._scene.meshes.length; index++) {
  23962. var mesh = this._scene.meshes[index];
  23963. if (mesh.material === this) {
  23964. mesh.material = null;
  23965. if (mesh.geometry) {
  23966. var geometry = mesh.geometry;
  23967. if (this.storeEffectOnSubMeshes) {
  23968. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23969. var subMesh = _a[_i];
  23970. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23971. }
  23972. }
  23973. else {
  23974. geometry._releaseVertexArrayObject(this._effect);
  23975. }
  23976. }
  23977. }
  23978. }
  23979. this._uniformBuffer.dispose();
  23980. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23981. if (forceDisposeEffect && this._effect) {
  23982. if (this.storeEffectOnSubMeshes) {
  23983. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23984. var subMesh = _c[_b];
  23985. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  23986. }
  23987. }
  23988. else {
  23989. this._scene.getEngine()._releaseEffect(this._effect);
  23990. }
  23991. this._effect = null;
  23992. }
  23993. // Callback
  23994. this.onDisposeObservable.notifyObservers(this);
  23995. this.onDisposeObservable.clear();
  23996. this.onBindObservable.clear();
  23997. this.onUnBindObservable.clear();
  23998. };
  23999. Material.prototype.serialize = function () {
  24000. return BABYLON.SerializationHelper.Serialize(this);
  24001. };
  24002. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24003. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24004. multiMaterial.id = parsedMultiMaterial.id;
  24005. if (BABYLON.Tags) {
  24006. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24007. }
  24008. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24009. var subMatId = parsedMultiMaterial.materials[matIndex];
  24010. if (subMatId) {
  24011. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24012. }
  24013. else {
  24014. multiMaterial.subMaterials.push(null);
  24015. }
  24016. }
  24017. return multiMaterial;
  24018. };
  24019. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24020. if (!parsedMaterial.customType) {
  24021. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24022. }
  24023. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  24024. parsedMaterial.customType === "BABYLON.legacyPBRMaterial";
  24025. if (!BABYLON.legacyPBRMaterial) {
  24026. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24027. return;
  24028. }
  24029. }
  24030. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24031. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24032. ;
  24033. };
  24034. return Material;
  24035. }());
  24036. Material._TriangleFillMode = 0;
  24037. Material._WireFrameFillMode = 1;
  24038. Material._PointFillMode = 2;
  24039. Material._ClockWiseSideOrientation = 0;
  24040. Material._CounterClockWiseSideOrientation = 1;
  24041. Material._TextureDirtyFlag = 1;
  24042. Material._LightDirtyFlag = 2;
  24043. Material._FresnelDirtyFlag = 4;
  24044. Material._AttributesDirtyFlag = 8;
  24045. Material._MiscDirtyFlag = 16;
  24046. __decorate([
  24047. BABYLON.serialize()
  24048. ], Material.prototype, "id", void 0);
  24049. __decorate([
  24050. BABYLON.serialize()
  24051. ], Material.prototype, "name", void 0);
  24052. __decorate([
  24053. BABYLON.serialize()
  24054. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24055. __decorate([
  24056. BABYLON.serialize()
  24057. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24058. __decorate([
  24059. BABYLON.serialize()
  24060. ], Material.prototype, "state", void 0);
  24061. __decorate([
  24062. BABYLON.serialize()
  24063. ], Material.prototype, "alpha", void 0);
  24064. __decorate([
  24065. BABYLON.serialize("backFaceCulling")
  24066. ], Material.prototype, "_backFaceCulling", void 0);
  24067. __decorate([
  24068. BABYLON.serialize()
  24069. ], Material.prototype, "sideOrientation", void 0);
  24070. __decorate([
  24071. BABYLON.serialize()
  24072. ], Material.prototype, "alphaMode", void 0);
  24073. __decorate([
  24074. BABYLON.serialize()
  24075. ], Material.prototype, "disableDepthWrite", void 0);
  24076. __decorate([
  24077. BABYLON.serialize("fogEnabled")
  24078. ], Material.prototype, "_fogEnabled", void 0);
  24079. __decorate([
  24080. BABYLON.serialize()
  24081. ], Material.prototype, "pointSize", void 0);
  24082. __decorate([
  24083. BABYLON.serialize()
  24084. ], Material.prototype, "zOffset", void 0);
  24085. __decorate([
  24086. BABYLON.serialize()
  24087. ], Material.prototype, "wireframe", null);
  24088. __decorate([
  24089. BABYLON.serialize()
  24090. ], Material.prototype, "pointsCloud", null);
  24091. __decorate([
  24092. BABYLON.serialize()
  24093. ], Material.prototype, "fillMode", null);
  24094. BABYLON.Material = Material;
  24095. })(BABYLON || (BABYLON = {}));
  24096. //# sourceMappingURL=babylon.material.js.map
  24097. var BABYLON;
  24098. (function (BABYLON) {
  24099. var UniformBuffer = (function () {
  24100. /**
  24101. * Uniform buffer objects.
  24102. *
  24103. * Handles blocks of uniform on the GPU.
  24104. *
  24105. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24106. *
  24107. * For more information, please refer to :
  24108. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24109. */
  24110. function UniformBuffer(engine, data, dynamic) {
  24111. this._engine = engine;
  24112. this._noUBO = engine.webGLVersion === 1;
  24113. this._dynamic = dynamic;
  24114. this._data = data || [];
  24115. this._uniformLocations = {};
  24116. this._uniformSizes = {};
  24117. this._uniformLocationPointer = 0;
  24118. this._needSync = false;
  24119. if (this._noUBO) {
  24120. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24121. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24122. this.updateFloat = this._updateFloatForEffect;
  24123. this.updateFloat2 = this._updateFloat2ForEffect;
  24124. this.updateFloat3 = this._updateFloat3ForEffect;
  24125. this.updateFloat4 = this._updateFloat4ForEffect;
  24126. this.updateMatrix = this._updateMatrixForEffect;
  24127. this.updateVector3 = this._updateVector3ForEffect;
  24128. this.updateVector4 = this._updateVector4ForEffect;
  24129. this.updateColor3 = this._updateColor3ForEffect;
  24130. this.updateColor4 = this._updateColor4ForEffect;
  24131. }
  24132. else {
  24133. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24134. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24135. this.updateFloat = this._updateFloatForUniform;
  24136. this.updateFloat2 = this._updateFloat2ForUniform;
  24137. this.updateFloat3 = this._updateFloat3ForUniform;
  24138. this.updateFloat4 = this._updateFloat4ForUniform;
  24139. this.updateMatrix = this._updateMatrixForUniform;
  24140. this.updateVector3 = this._updateVector3ForUniform;
  24141. this.updateVector4 = this._updateVector4ForUniform;
  24142. this.updateColor3 = this._updateColor3ForUniform;
  24143. this.updateColor4 = this._updateColor4ForUniform;
  24144. }
  24145. }
  24146. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24147. // Properties
  24148. /**
  24149. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24150. * or just falling back on setUniformXXX calls.
  24151. */
  24152. get: function () {
  24153. return !this._noUBO;
  24154. },
  24155. enumerable: true,
  24156. configurable: true
  24157. });
  24158. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24159. /**
  24160. * Indicates if the WebGL underlying uniform buffer is in sync
  24161. * with the javascript cache data.
  24162. */
  24163. get: function () {
  24164. return !this._needSync;
  24165. },
  24166. enumerable: true,
  24167. configurable: true
  24168. });
  24169. /**
  24170. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24171. * Also, a dynamic UniformBuffer will disable cache verification and always
  24172. * update the underlying WebGL uniform buffer to the GPU.
  24173. */
  24174. UniformBuffer.prototype.isDynamic = function () {
  24175. return this._dynamic;
  24176. };
  24177. /**
  24178. * The data cache on JS side.
  24179. */
  24180. UniformBuffer.prototype.getData = function () {
  24181. return this._bufferData;
  24182. };
  24183. /**
  24184. * The underlying WebGL Uniform buffer.
  24185. */
  24186. UniformBuffer.prototype.getBuffer = function () {
  24187. return this._buffer;
  24188. };
  24189. /**
  24190. * std140 layout specifies how to align data within an UBO structure.
  24191. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24192. * for specs.
  24193. */
  24194. UniformBuffer.prototype._fillAlignment = function (size) {
  24195. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24196. // and 4x4 matrices
  24197. // TODO : change if other types are used
  24198. var alignment;
  24199. if (size <= 2) {
  24200. alignment = size;
  24201. }
  24202. else {
  24203. alignment = 4;
  24204. }
  24205. if ((this._uniformLocationPointer % alignment) !== 0) {
  24206. var oldPointer = this._uniformLocationPointer;
  24207. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24208. var diff = this._uniformLocationPointer - oldPointer;
  24209. for (var i = 0; i < diff; i++) {
  24210. this._data.push(0);
  24211. }
  24212. }
  24213. };
  24214. /**
  24215. * Adds an uniform in the buffer.
  24216. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24217. * for the layout to be correct !
  24218. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24219. * @param {number|number[]} size Data size, or data directly.
  24220. */
  24221. UniformBuffer.prototype.addUniform = function (name, size) {
  24222. if (this._noUBO) {
  24223. return;
  24224. }
  24225. if (this._uniformLocations[name] !== undefined) {
  24226. // Already existing uniform
  24227. return;
  24228. }
  24229. // This function must be called in the order of the shader layout !
  24230. // size can be the size of the uniform, or data directly
  24231. var data;
  24232. if (size instanceof Array) {
  24233. data = size;
  24234. size = data.length;
  24235. }
  24236. else {
  24237. size = size;
  24238. data = [];
  24239. // Fill with zeros
  24240. for (var i = 0; i < size; i++) {
  24241. data.push(0);
  24242. }
  24243. }
  24244. this._fillAlignment(size);
  24245. this._uniformSizes[name] = size;
  24246. this._uniformLocations[name] = this._uniformLocationPointer;
  24247. this._uniformLocationPointer += size;
  24248. for (var i = 0; i < size; i++) {
  24249. this._data.push(data[i]);
  24250. }
  24251. this._needSync = true;
  24252. };
  24253. /**
  24254. * Wrapper for addUniform.
  24255. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24256. * @param {Matrix} mat A 4x4 matrix.
  24257. */
  24258. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24259. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24260. };
  24261. /**
  24262. * Wrapper for addUniform.
  24263. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24264. * @param {number} x
  24265. * @param {number} y
  24266. */
  24267. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24268. var temp = [x, y];
  24269. this.addUniform(name, temp);
  24270. };
  24271. /**
  24272. * Wrapper for addUniform.
  24273. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24274. * @param {number} x
  24275. * @param {number} y
  24276. * @param {number} z
  24277. */
  24278. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24279. var temp = [x, y, z];
  24280. this.addUniform(name, temp);
  24281. };
  24282. /**
  24283. * Wrapper for addUniform.
  24284. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24285. * @param {Color3} color
  24286. */
  24287. UniformBuffer.prototype.addColor3 = function (name, color) {
  24288. var temp = [];
  24289. color.toArray(temp);
  24290. this.addUniform(name, temp);
  24291. };
  24292. /**
  24293. * Wrapper for addUniform.
  24294. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24295. * @param {Color3} color
  24296. * @param {number} alpha
  24297. */
  24298. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24299. var temp = [];
  24300. color.toArray(temp);
  24301. temp.push(alpha);
  24302. this.addUniform(name, temp);
  24303. };
  24304. /**
  24305. * Wrapper for addUniform.
  24306. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24307. * @param {Vector3} vector
  24308. */
  24309. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24310. var temp = [];
  24311. vector.toArray(temp);
  24312. this.addUniform(name, temp);
  24313. };
  24314. /**
  24315. * Wrapper for addUniform.
  24316. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24317. */
  24318. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24319. this.addUniform(name, 12);
  24320. };
  24321. /**
  24322. * Wrapper for addUniform.
  24323. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24324. */
  24325. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24326. this.addUniform(name, 8);
  24327. };
  24328. /**
  24329. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24330. */
  24331. UniformBuffer.prototype.create = function () {
  24332. if (this._noUBO) {
  24333. return;
  24334. }
  24335. if (this._buffer) {
  24336. return; // nothing to do
  24337. }
  24338. // See spec, alignment must be filled as a vec4
  24339. this._fillAlignment(4);
  24340. this._bufferData = new Float32Array(this._data);
  24341. if (this._dynamic) {
  24342. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24343. }
  24344. else {
  24345. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24346. }
  24347. this._needSync = true;
  24348. };
  24349. /**
  24350. * Updates the WebGL Uniform Buffer on the GPU.
  24351. * If the `dynamic` flag is set to true, no cache comparison is done.
  24352. * Otherwise, the buffer will be updated only if the cache differs.
  24353. */
  24354. UniformBuffer.prototype.update = function () {
  24355. if (!this._buffer) {
  24356. this.create();
  24357. return;
  24358. }
  24359. if (!this._dynamic && !this._needSync) {
  24360. return;
  24361. }
  24362. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24363. this._needSync = false;
  24364. };
  24365. /**
  24366. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24367. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24368. * @param {number[]|Float32Array} data Flattened data
  24369. * @param {number} size Size of the data.
  24370. */
  24371. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24372. var location = this._uniformLocations[uniformName];
  24373. if (location === undefined) {
  24374. if (this._buffer) {
  24375. // Cannot add an uniform if the buffer is already created
  24376. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24377. return;
  24378. }
  24379. this.addUniform(uniformName, size);
  24380. location = this._uniformLocations[uniformName];
  24381. }
  24382. if (!this._buffer) {
  24383. this.create();
  24384. }
  24385. if (!this._dynamic) {
  24386. // Cache for static uniform buffers
  24387. var changed = false;
  24388. for (var i = 0; i < size; i++) {
  24389. if (this._bufferData[location + i] !== data[i]) {
  24390. changed = true;
  24391. this._bufferData[location + i] = data[i];
  24392. }
  24393. }
  24394. this._needSync = this._needSync || changed;
  24395. }
  24396. else {
  24397. // No cache for dynamic
  24398. for (var i = 0; i < size; i++) {
  24399. this._bufferData[location + i] = data[i];
  24400. }
  24401. }
  24402. };
  24403. // Update methods
  24404. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24405. // To match std140, matrix must be realigned
  24406. for (var i = 0; i < 3; i++) {
  24407. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24408. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24409. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24410. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24411. }
  24412. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24413. };
  24414. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24415. this._currentEffect.setMatrix3x3(name, matrix);
  24416. };
  24417. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24418. this._currentEffect.setMatrix2x2(name, matrix);
  24419. };
  24420. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24421. // To match std140, matrix must be realigned
  24422. for (var i = 0; i < 2; i++) {
  24423. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24424. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24425. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24426. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24427. }
  24428. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24429. };
  24430. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24431. this._currentEffect.setFloat(name, x);
  24432. };
  24433. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24434. UniformBuffer._tempBuffer[0] = x;
  24435. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24436. };
  24437. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24438. this._currentEffect.setFloat2(name, x, y);
  24439. };
  24440. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24441. UniformBuffer._tempBuffer[0] = x;
  24442. UniformBuffer._tempBuffer[1] = y;
  24443. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24444. };
  24445. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24446. if (suffix === void 0) { suffix = ""; }
  24447. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24448. };
  24449. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24450. if (suffix === void 0) { suffix = ""; }
  24451. UniformBuffer._tempBuffer[0] = x;
  24452. UniformBuffer._tempBuffer[1] = y;
  24453. UniformBuffer._tempBuffer[2] = z;
  24454. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24455. };
  24456. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24457. if (suffix === void 0) { suffix = ""; }
  24458. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24459. };
  24460. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24461. if (suffix === void 0) { suffix = ""; }
  24462. UniformBuffer._tempBuffer[0] = x;
  24463. UniformBuffer._tempBuffer[1] = y;
  24464. UniformBuffer._tempBuffer[2] = z;
  24465. UniformBuffer._tempBuffer[3] = w;
  24466. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24467. };
  24468. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24469. this._currentEffect.setMatrix(name, mat);
  24470. };
  24471. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24472. this.updateUniform(name, mat.toArray(), 16);
  24473. };
  24474. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24475. this._currentEffect.setVector3(name, vector);
  24476. };
  24477. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24478. vector.toArray(UniformBuffer._tempBuffer);
  24479. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24480. };
  24481. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24482. this._currentEffect.setVector4(name, vector);
  24483. };
  24484. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24485. vector.toArray(UniformBuffer._tempBuffer);
  24486. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24487. };
  24488. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24489. if (suffix === void 0) { suffix = ""; }
  24490. this._currentEffect.setColor3(name + suffix, color);
  24491. };
  24492. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24493. if (suffix === void 0) { suffix = ""; }
  24494. color.toArray(UniformBuffer._tempBuffer);
  24495. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24496. };
  24497. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24498. if (suffix === void 0) { suffix = ""; }
  24499. this._currentEffect.setColor4(name + suffix, color, alpha);
  24500. };
  24501. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24502. if (suffix === void 0) { suffix = ""; }
  24503. color.toArray(UniformBuffer._tempBuffer);
  24504. UniformBuffer._tempBuffer[3] = alpha;
  24505. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24506. };
  24507. /**
  24508. * Sets a sampler uniform on the effect.
  24509. * @param {string} name Name of the sampler.
  24510. * @param {Texture} texture
  24511. */
  24512. UniformBuffer.prototype.setTexture = function (name, texture) {
  24513. this._currentEffect.setTexture(name, texture);
  24514. };
  24515. /**
  24516. * Directly updates the value of the uniform in the cache AND on the GPU.
  24517. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24518. * @param {number[]|Float32Array} data Flattened data
  24519. */
  24520. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24521. this.updateUniform(uniformName, data, data.length);
  24522. this.update();
  24523. };
  24524. /**
  24525. * Binds this uniform buffer to an effect.
  24526. * @param {Effect} effect
  24527. * @param {string} name Name of the uniform block in the shader.
  24528. */
  24529. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24530. this._currentEffect = effect;
  24531. if (this._noUBO) {
  24532. return;
  24533. }
  24534. effect.bindUniformBuffer(this._buffer, name);
  24535. };
  24536. /**
  24537. * Disposes the uniform buffer.
  24538. */
  24539. UniformBuffer.prototype.dispose = function () {
  24540. if (!this._buffer) {
  24541. return;
  24542. }
  24543. if (this._engine._releaseBuffer(this._buffer)) {
  24544. this._buffer = null;
  24545. }
  24546. };
  24547. return UniformBuffer;
  24548. }());
  24549. // Pool for avoiding memory leaks
  24550. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24551. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24552. BABYLON.UniformBuffer = UniformBuffer;
  24553. })(BABYLON || (BABYLON = {}));
  24554. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24555. var BABYLON;
  24556. (function (BABYLON) {
  24557. var PushMaterial = (function (_super) {
  24558. __extends(PushMaterial, _super);
  24559. function PushMaterial(name, scene) {
  24560. var _this = _super.call(this, name, scene) || this;
  24561. _this.storeEffectOnSubMeshes = true;
  24562. return _this;
  24563. }
  24564. PushMaterial.prototype.getEffect = function () {
  24565. return this._activeEffect;
  24566. };
  24567. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24568. if (!mesh) {
  24569. return false;
  24570. }
  24571. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24572. return true;
  24573. }
  24574. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24575. };
  24576. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24577. this._activeEffect.setMatrix("world", world);
  24578. };
  24579. PushMaterial.prototype.bind = function (world, mesh) {
  24580. if (!mesh) {
  24581. return;
  24582. }
  24583. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24584. };
  24585. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24586. _super.prototype._afterBind.call(this, mesh);
  24587. this.getScene()._cachedEffect = effect;
  24588. };
  24589. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24590. if (visibility === void 0) { visibility = 0; }
  24591. return scene.isCachedMaterialValid(this, effect, visibility);
  24592. };
  24593. PushMaterial.prototype.markAsDirty = function (flag) {
  24594. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24595. this._markAllSubMeshesAsTexturesDirty();
  24596. }
  24597. if (flag & BABYLON.Material.LightDirtyFlag) {
  24598. this._markAllSubMeshesAsLightsDirty();
  24599. }
  24600. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24601. this._markAllSubMeshesAsFresnelDirty();
  24602. }
  24603. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24604. this._markAllSubMeshesAsAttributesDirty();
  24605. }
  24606. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24607. this._markAllSubMeshesAsMiscDirty();
  24608. }
  24609. };
  24610. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24611. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24612. var mesh = _a[_i];
  24613. if (!mesh.subMeshes) {
  24614. continue;
  24615. }
  24616. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24617. var subMesh = _c[_b];
  24618. if (subMesh.getMaterial() !== this) {
  24619. continue;
  24620. }
  24621. if (!subMesh._materialDefines) {
  24622. return;
  24623. }
  24624. func(subMesh._materialDefines);
  24625. }
  24626. }
  24627. };
  24628. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24629. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24630. };
  24631. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24632. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24633. };
  24634. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24635. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24636. };
  24637. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24638. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24639. };
  24640. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24641. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24642. };
  24643. return PushMaterial;
  24644. }(BABYLON.Material));
  24645. BABYLON.PushMaterial = PushMaterial;
  24646. })(BABYLON || (BABYLON = {}));
  24647. //# sourceMappingURL=babylon.pushMaterial.js.map
  24648. var BABYLON;
  24649. (function (BABYLON) {
  24650. var VertexData = (function () {
  24651. function VertexData() {
  24652. }
  24653. VertexData.prototype.set = function (data, kind) {
  24654. switch (kind) {
  24655. case BABYLON.VertexBuffer.PositionKind:
  24656. this.positions = data;
  24657. break;
  24658. case BABYLON.VertexBuffer.NormalKind:
  24659. this.normals = data;
  24660. break;
  24661. case BABYLON.VertexBuffer.TangentKind:
  24662. this.tangents = data;
  24663. break;
  24664. case BABYLON.VertexBuffer.UVKind:
  24665. this.uvs = data;
  24666. break;
  24667. case BABYLON.VertexBuffer.UV2Kind:
  24668. this.uvs2 = data;
  24669. break;
  24670. case BABYLON.VertexBuffer.UV3Kind:
  24671. this.uvs3 = data;
  24672. break;
  24673. case BABYLON.VertexBuffer.UV4Kind:
  24674. this.uvs4 = data;
  24675. break;
  24676. case BABYLON.VertexBuffer.UV5Kind:
  24677. this.uvs5 = data;
  24678. break;
  24679. case BABYLON.VertexBuffer.UV6Kind:
  24680. this.uvs6 = data;
  24681. break;
  24682. case BABYLON.VertexBuffer.ColorKind:
  24683. this.colors = data;
  24684. break;
  24685. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24686. this.matricesIndices = data;
  24687. break;
  24688. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24689. this.matricesWeights = data;
  24690. break;
  24691. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24692. this.matricesIndicesExtra = data;
  24693. break;
  24694. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24695. this.matricesWeightsExtra = data;
  24696. break;
  24697. }
  24698. };
  24699. /**
  24700. * Associates the vertexData to the passed Mesh.
  24701. * Sets it as updatable or not (default `false`).
  24702. * Returns the VertexData.
  24703. */
  24704. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24705. this._applyTo(mesh, updatable);
  24706. return this;
  24707. };
  24708. /**
  24709. * Associates the vertexData to the passed Geometry.
  24710. * Sets it as updatable or not (default `false`).
  24711. * Returns the VertexData.
  24712. */
  24713. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24714. this._applyTo(geometry, updatable);
  24715. return this;
  24716. };
  24717. /**
  24718. * Updates the associated mesh.
  24719. * Returns the VertexData.
  24720. */
  24721. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24722. this._update(mesh);
  24723. return this;
  24724. };
  24725. /**
  24726. * Updates the associated geometry.
  24727. * Returns the VertexData.
  24728. */
  24729. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24730. this._update(geometry);
  24731. return this;
  24732. };
  24733. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24734. if (this.positions) {
  24735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24736. }
  24737. if (this.normals) {
  24738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24739. }
  24740. if (this.tangents) {
  24741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24742. }
  24743. if (this.uvs) {
  24744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24745. }
  24746. if (this.uvs2) {
  24747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24748. }
  24749. if (this.uvs3) {
  24750. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24751. }
  24752. if (this.uvs4) {
  24753. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24754. }
  24755. if (this.uvs5) {
  24756. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24757. }
  24758. if (this.uvs6) {
  24759. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24760. }
  24761. if (this.colors) {
  24762. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24763. }
  24764. if (this.matricesIndices) {
  24765. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24766. }
  24767. if (this.matricesWeights) {
  24768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24769. }
  24770. if (this.matricesIndicesExtra) {
  24771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24772. }
  24773. if (this.matricesWeightsExtra) {
  24774. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24775. }
  24776. if (this.indices) {
  24777. meshOrGeometry.setIndices(this.indices);
  24778. }
  24779. return this;
  24780. };
  24781. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24782. if (this.positions) {
  24783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24784. }
  24785. if (this.normals) {
  24786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24787. }
  24788. if (this.tangents) {
  24789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24790. }
  24791. if (this.uvs) {
  24792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24793. }
  24794. if (this.uvs2) {
  24795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24796. }
  24797. if (this.uvs3) {
  24798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24799. }
  24800. if (this.uvs4) {
  24801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24802. }
  24803. if (this.uvs5) {
  24804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24805. }
  24806. if (this.uvs6) {
  24807. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24808. }
  24809. if (this.colors) {
  24810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24811. }
  24812. if (this.matricesIndices) {
  24813. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24814. }
  24815. if (this.matricesWeights) {
  24816. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24817. }
  24818. if (this.matricesIndicesExtra) {
  24819. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24820. }
  24821. if (this.matricesWeightsExtra) {
  24822. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24823. }
  24824. if (this.indices) {
  24825. meshOrGeometry.setIndices(this.indices);
  24826. }
  24827. return this;
  24828. };
  24829. /**
  24830. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24831. * Returns the VertexData.
  24832. */
  24833. VertexData.prototype.transform = function (matrix) {
  24834. var transformed = BABYLON.Vector3.Zero();
  24835. var index;
  24836. if (this.positions) {
  24837. var position = BABYLON.Vector3.Zero();
  24838. for (index = 0; index < this.positions.length; index += 3) {
  24839. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24840. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24841. this.positions[index] = transformed.x;
  24842. this.positions[index + 1] = transformed.y;
  24843. this.positions[index + 2] = transformed.z;
  24844. }
  24845. }
  24846. if (this.normals) {
  24847. var normal = BABYLON.Vector3.Zero();
  24848. for (index = 0; index < this.normals.length; index += 3) {
  24849. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24850. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24851. this.normals[index] = transformed.x;
  24852. this.normals[index + 1] = transformed.y;
  24853. this.normals[index + 2] = transformed.z;
  24854. }
  24855. }
  24856. if (this.tangents) {
  24857. var tangent = BABYLON.Vector4.Zero();
  24858. var tangentTransformed = BABYLON.Vector4.Zero();
  24859. for (index = 0; index < this.tangents.length; index += 4) {
  24860. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24861. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24862. this.tangents[index] = tangentTransformed.x;
  24863. this.tangents[index + 1] = tangentTransformed.y;
  24864. this.tangents[index + 2] = tangentTransformed.z;
  24865. this.tangents[index + 3] = tangentTransformed.w;
  24866. }
  24867. }
  24868. return this;
  24869. };
  24870. /**
  24871. * Merges the passed VertexData into the current one.
  24872. * Returns the modified VertexData.
  24873. */
  24874. VertexData.prototype.merge = function (other) {
  24875. if (other.indices) {
  24876. if (!this.indices) {
  24877. this.indices = [];
  24878. }
  24879. var offset = this.positions ? this.positions.length / 3 : 0;
  24880. for (var index = 0; index < other.indices.length; index++) {
  24881. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24882. this.indices.push(other.indices[index] + offset);
  24883. }
  24884. }
  24885. this.positions = this._mergeElement(this.positions, other.positions);
  24886. this.normals = this._mergeElement(this.normals, other.normals);
  24887. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24888. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24889. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24890. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24891. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24892. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24893. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24894. this.colors = this._mergeElement(this.colors, other.colors);
  24895. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24896. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24897. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24898. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24899. return this;
  24900. };
  24901. VertexData.prototype._mergeElement = function (source, other) {
  24902. if (!other)
  24903. return source;
  24904. if (!source)
  24905. return other;
  24906. var len = other.length + source.length;
  24907. var isSrcTypedArray = source instanceof Float32Array;
  24908. var isOthTypedArray = other instanceof Float32Array;
  24909. // use non-loop method when the source is Float32Array
  24910. if (isSrcTypedArray) {
  24911. var ret32 = new Float32Array(len);
  24912. ret32.set(source);
  24913. ret32.set(other, source.length);
  24914. return ret32;
  24915. // source is number[], when other is also use concat
  24916. }
  24917. else if (!isOthTypedArray) {
  24918. return source.concat(other);
  24919. // source is a number[], but other is a Float32Array, loop required
  24920. }
  24921. else {
  24922. var ret = source.slice(0); // copy source to a separate array
  24923. for (var i = 0, len = other.length; i < len; i++) {
  24924. ret.push(other[i]);
  24925. }
  24926. return ret;
  24927. }
  24928. };
  24929. /**
  24930. * Serializes the VertexData.
  24931. * Returns a serialized object.
  24932. */
  24933. VertexData.prototype.serialize = function () {
  24934. var serializationObject = this.serialize();
  24935. if (this.positions) {
  24936. serializationObject.positions = this.positions;
  24937. }
  24938. if (this.normals) {
  24939. serializationObject.normals = this.normals;
  24940. }
  24941. if (this.tangents) {
  24942. serializationObject.tangents = this.tangents;
  24943. }
  24944. if (this.uvs) {
  24945. serializationObject.uvs = this.uvs;
  24946. }
  24947. if (this.uvs2) {
  24948. serializationObject.uvs2 = this.uvs2;
  24949. }
  24950. if (this.uvs3) {
  24951. serializationObject.uvs3 = this.uvs3;
  24952. }
  24953. if (this.uvs4) {
  24954. serializationObject.uvs4 = this.uvs4;
  24955. }
  24956. if (this.uvs5) {
  24957. serializationObject.uvs5 = this.uvs5;
  24958. }
  24959. if (this.uvs6) {
  24960. serializationObject.uvs6 = this.uvs6;
  24961. }
  24962. if (this.colors) {
  24963. serializationObject.colors = this.colors;
  24964. }
  24965. if (this.matricesIndices) {
  24966. serializationObject.matricesIndices = this.matricesIndices;
  24967. serializationObject.matricesIndices._isExpanded = true;
  24968. }
  24969. if (this.matricesWeights) {
  24970. serializationObject.matricesWeights = this.matricesWeights;
  24971. }
  24972. if (this.matricesIndicesExtra) {
  24973. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24974. serializationObject.matricesIndicesExtra._isExpanded = true;
  24975. }
  24976. if (this.matricesWeightsExtra) {
  24977. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24978. }
  24979. serializationObject.indices = this.indices;
  24980. return serializationObject;
  24981. };
  24982. // Statics
  24983. /**
  24984. * Returns the object VertexData associated to the passed mesh.
  24985. */
  24986. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  24987. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  24988. };
  24989. /**
  24990. * Returns the object VertexData associated to the passed geometry.
  24991. */
  24992. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  24993. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  24994. };
  24995. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  24996. var result = new VertexData();
  24997. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24998. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  24999. }
  25000. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25001. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25002. }
  25003. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25004. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25005. }
  25006. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25007. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25008. }
  25009. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25010. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25011. }
  25012. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25013. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25014. }
  25015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25016. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25017. }
  25018. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25019. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25020. }
  25021. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25022. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25023. }
  25024. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25025. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25026. }
  25027. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25028. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25029. }
  25030. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25031. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25032. }
  25033. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25034. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25035. }
  25036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25037. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25038. }
  25039. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25040. return result;
  25041. };
  25042. /**
  25043. * Creates the vertexData of the Ribbon.
  25044. */
  25045. VertexData.CreateRibbon = function (options) {
  25046. var pathArray = options.pathArray;
  25047. var closeArray = options.closeArray || false;
  25048. var closePath = options.closePath || false;
  25049. var invertUV = options.invertUV || false;
  25050. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25051. var offset = options.offset || defaultOffset;
  25052. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25053. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25054. var customUV = options.uvs;
  25055. var customColors = options.colors;
  25056. var positions = [];
  25057. var indices = [];
  25058. var normals = [];
  25059. var uvs = [];
  25060. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25061. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25062. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25063. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25064. var minlg; // minimal length among all paths from pathArray
  25065. var lg = []; // array of path lengths : nb of vertex per path
  25066. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25067. var p; // path iterator
  25068. var i; // point iterator
  25069. var j; // point iterator
  25070. // if single path in pathArray
  25071. if (pathArray.length < 2) {
  25072. var ar1 = [];
  25073. var ar2 = [];
  25074. for (i = 0; i < pathArray[0].length - offset; i++) {
  25075. ar1.push(pathArray[0][i]);
  25076. ar2.push(pathArray[0][i + offset]);
  25077. }
  25078. pathArray = [ar1, ar2];
  25079. }
  25080. // positions and horizontal distances (u)
  25081. var idc = 0;
  25082. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25083. var path;
  25084. var l;
  25085. minlg = pathArray[0].length;
  25086. var vectlg;
  25087. var dist;
  25088. for (p = 0; p < pathArray.length; p++) {
  25089. uTotalDistance[p] = 0;
  25090. us[p] = [0];
  25091. path = pathArray[p];
  25092. l = path.length;
  25093. minlg = (minlg < l) ? minlg : l;
  25094. j = 0;
  25095. while (j < l) {
  25096. positions.push(path[j].x, path[j].y, path[j].z);
  25097. if (j > 0) {
  25098. vectlg = path[j].subtract(path[j - 1]).length();
  25099. dist = vectlg + uTotalDistance[p];
  25100. us[p].push(dist);
  25101. uTotalDistance[p] = dist;
  25102. }
  25103. j++;
  25104. }
  25105. if (closePath) {
  25106. j--;
  25107. positions.push(path[0].x, path[0].y, path[0].z);
  25108. vectlg = path[j].subtract(path[0]).length();
  25109. dist = vectlg + uTotalDistance[p];
  25110. us[p].push(dist);
  25111. uTotalDistance[p] = dist;
  25112. }
  25113. lg[p] = l + closePathCorr;
  25114. idx[p] = idc;
  25115. idc += (l + closePathCorr);
  25116. }
  25117. // vertical distances (v)
  25118. var path1;
  25119. var path2;
  25120. var vertex1;
  25121. var vertex2;
  25122. for (i = 0; i < minlg + closePathCorr; i++) {
  25123. vTotalDistance[i] = 0;
  25124. vs[i] = [0];
  25125. for (p = 0; p < pathArray.length - 1; p++) {
  25126. path1 = pathArray[p];
  25127. path2 = pathArray[p + 1];
  25128. if (i === minlg) {
  25129. vertex1 = path1[0];
  25130. vertex2 = path2[0];
  25131. }
  25132. else {
  25133. vertex1 = path1[i];
  25134. vertex2 = path2[i];
  25135. }
  25136. vectlg = vertex2.subtract(vertex1).length();
  25137. dist = vectlg + vTotalDistance[i];
  25138. vs[i].push(dist);
  25139. vTotalDistance[i] = dist;
  25140. }
  25141. if (closeArray) {
  25142. path1 = pathArray[p];
  25143. path2 = pathArray[0];
  25144. if (i === minlg) {
  25145. vertex2 = path2[0];
  25146. }
  25147. vectlg = vertex2.subtract(vertex1).length();
  25148. dist = vectlg + vTotalDistance[i];
  25149. vTotalDistance[i] = dist;
  25150. }
  25151. }
  25152. // uvs
  25153. var u;
  25154. var v;
  25155. if (customUV) {
  25156. for (p = 0; p < customUV.length; p++) {
  25157. uvs.push(customUV[p].x, customUV[p].y);
  25158. }
  25159. }
  25160. else {
  25161. for (p = 0; p < pathArray.length; p++) {
  25162. for (i = 0; i < minlg + closePathCorr; i++) {
  25163. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25164. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25165. if (invertUV) {
  25166. uvs.push(v, u);
  25167. }
  25168. else {
  25169. uvs.push(u, v);
  25170. }
  25171. }
  25172. }
  25173. }
  25174. // indices
  25175. p = 0; // path index
  25176. var pi = 0; // positions array index
  25177. var l1 = lg[p] - 1; // path1 length
  25178. var l2 = lg[p + 1] - 1; // path2 length
  25179. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25180. var shft = idx[1] - idx[0]; // shift
  25181. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25182. while (pi <= min && p < path1nb) {
  25183. // 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
  25184. indices.push(pi, pi + shft, pi + 1);
  25185. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25186. pi += 1;
  25187. if (pi === min) {
  25188. p++;
  25189. if (p === lg.length - 1) {
  25190. shft = idx[0] - idx[p];
  25191. l1 = lg[p] - 1;
  25192. l2 = lg[0] - 1;
  25193. }
  25194. else {
  25195. shft = idx[p + 1] - idx[p];
  25196. l1 = lg[p] - 1;
  25197. l2 = lg[p + 1] - 1;
  25198. }
  25199. pi = idx[p];
  25200. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25201. }
  25202. }
  25203. // normals
  25204. VertexData.ComputeNormals(positions, indices, normals);
  25205. if (closePath) {
  25206. var indexFirst = 0;
  25207. var indexLast = 0;
  25208. for (p = 0; p < pathArray.length; p++) {
  25209. indexFirst = idx[p] * 3;
  25210. if (p + 1 < pathArray.length) {
  25211. indexLast = (idx[p + 1] - 1) * 3;
  25212. }
  25213. else {
  25214. indexLast = normals.length - 3;
  25215. }
  25216. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25217. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25218. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25219. normals[indexLast] = normals[indexFirst];
  25220. normals[indexLast + 1] = normals[indexFirst + 1];
  25221. normals[indexLast + 2] = normals[indexFirst + 2];
  25222. }
  25223. }
  25224. // sides
  25225. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25226. // Colors
  25227. if (customColors) {
  25228. var colors = new Float32Array(customColors.length * 4);
  25229. for (var c = 0; c < customColors.length; c++) {
  25230. colors[c * 4] = customColors[c].r;
  25231. colors[c * 4 + 1] = customColors[c].g;
  25232. colors[c * 4 + 2] = customColors[c].b;
  25233. colors[c * 4 + 3] = customColors[c].a;
  25234. }
  25235. }
  25236. // Result
  25237. var vertexData = new VertexData();
  25238. var positions32 = new Float32Array(positions);
  25239. var normals32 = new Float32Array(normals);
  25240. var uvs32 = new Float32Array(uvs);
  25241. vertexData.indices = indices;
  25242. vertexData.positions = positions32;
  25243. vertexData.normals = normals32;
  25244. vertexData.uvs = uvs32;
  25245. if (customColors) {
  25246. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25247. }
  25248. if (closePath) {
  25249. vertexData._idx = idx;
  25250. }
  25251. return vertexData;
  25252. };
  25253. /**
  25254. * Creates the VertexData of the Box.
  25255. */
  25256. VertexData.CreateBox = function (options) {
  25257. var normalsSource = [
  25258. new BABYLON.Vector3(0, 0, 1),
  25259. new BABYLON.Vector3(0, 0, -1),
  25260. new BABYLON.Vector3(1, 0, 0),
  25261. new BABYLON.Vector3(-1, 0, 0),
  25262. new BABYLON.Vector3(0, 1, 0),
  25263. new BABYLON.Vector3(0, -1, 0)
  25264. ];
  25265. var indices = [];
  25266. var positions = [];
  25267. var normals = [];
  25268. var uvs = [];
  25269. var width = options.width || options.size || 1;
  25270. var height = options.height || options.size || 1;
  25271. var depth = options.depth || options.size || 1;
  25272. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25273. var faceUV = options.faceUV || new Array(6);
  25274. var faceColors = options.faceColors;
  25275. var colors = [];
  25276. // default face colors and UV if undefined
  25277. for (var f = 0; f < 6; f++) {
  25278. if (faceUV[f] === undefined) {
  25279. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25280. }
  25281. if (faceColors && faceColors[f] === undefined) {
  25282. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25283. }
  25284. }
  25285. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25286. // Create each face in turn.
  25287. for (var index = 0; index < normalsSource.length; index++) {
  25288. var normal = normalsSource[index];
  25289. // Get two vectors perpendicular to the face normal and to each other.
  25290. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25291. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25292. // Six indices (two triangles) per face.
  25293. var verticesLength = positions.length / 3;
  25294. indices.push(verticesLength);
  25295. indices.push(verticesLength + 1);
  25296. indices.push(verticesLength + 2);
  25297. indices.push(verticesLength);
  25298. indices.push(verticesLength + 2);
  25299. indices.push(verticesLength + 3);
  25300. // Four vertices per face.
  25301. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25302. positions.push(vertex.x, vertex.y, vertex.z);
  25303. normals.push(normal.x, normal.y, normal.z);
  25304. uvs.push(faceUV[index].z, faceUV[index].w);
  25305. if (faceColors) {
  25306. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25307. }
  25308. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25309. positions.push(vertex.x, vertex.y, vertex.z);
  25310. normals.push(normal.x, normal.y, normal.z);
  25311. uvs.push(faceUV[index].x, faceUV[index].w);
  25312. if (faceColors) {
  25313. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25314. }
  25315. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25316. positions.push(vertex.x, vertex.y, vertex.z);
  25317. normals.push(normal.x, normal.y, normal.z);
  25318. uvs.push(faceUV[index].x, faceUV[index].y);
  25319. if (faceColors) {
  25320. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25321. }
  25322. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25323. positions.push(vertex.x, vertex.y, vertex.z);
  25324. normals.push(normal.x, normal.y, normal.z);
  25325. uvs.push(faceUV[index].z, faceUV[index].y);
  25326. if (faceColors) {
  25327. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25328. }
  25329. }
  25330. // sides
  25331. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25332. // Result
  25333. var vertexData = new VertexData();
  25334. vertexData.indices = indices;
  25335. vertexData.positions = positions;
  25336. vertexData.normals = normals;
  25337. vertexData.uvs = uvs;
  25338. if (faceColors) {
  25339. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25340. vertexData.colors = totalColors;
  25341. }
  25342. return vertexData;
  25343. };
  25344. /**
  25345. * Creates the VertexData of the Sphere.
  25346. */
  25347. VertexData.CreateSphere = function (options) {
  25348. var segments = options.segments || 32;
  25349. var diameterX = options.diameterX || options.diameter || 1;
  25350. var diameterY = options.diameterY || options.diameter || 1;
  25351. var diameterZ = options.diameterZ || options.diameter || 1;
  25352. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25353. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25354. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25355. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25356. var totalZRotationSteps = 2 + segments;
  25357. var totalYRotationSteps = 2 * totalZRotationSteps;
  25358. var indices = [];
  25359. var positions = [];
  25360. var normals = [];
  25361. var uvs = [];
  25362. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25363. var normalizedZ = zRotationStep / totalZRotationSteps;
  25364. var angleZ = normalizedZ * Math.PI * slice;
  25365. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25366. var normalizedY = yRotationStep / totalYRotationSteps;
  25367. var angleY = normalizedY * Math.PI * 2 * arc;
  25368. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25369. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25370. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25371. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25372. var vertex = complete.multiply(radius);
  25373. var normal = complete.divide(radius).normalize();
  25374. positions.push(vertex.x, vertex.y, vertex.z);
  25375. normals.push(normal.x, normal.y, normal.z);
  25376. uvs.push(normalizedY, normalizedZ);
  25377. }
  25378. if (zRotationStep > 0) {
  25379. var verticesCount = positions.length / 3;
  25380. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25381. indices.push((firstIndex));
  25382. indices.push((firstIndex + 1));
  25383. indices.push(firstIndex + totalYRotationSteps + 1);
  25384. indices.push((firstIndex + totalYRotationSteps + 1));
  25385. indices.push((firstIndex + 1));
  25386. indices.push((firstIndex + totalYRotationSteps + 2));
  25387. }
  25388. }
  25389. }
  25390. // Sides
  25391. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25392. // Result
  25393. var vertexData = new VertexData();
  25394. vertexData.indices = indices;
  25395. vertexData.positions = positions;
  25396. vertexData.normals = normals;
  25397. vertexData.uvs = uvs;
  25398. return vertexData;
  25399. };
  25400. /**
  25401. * Creates the VertexData of the Cylinder or Cone.
  25402. */
  25403. VertexData.CreateCylinder = function (options) {
  25404. var height = options.height || 2;
  25405. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25406. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25407. var tessellation = options.tessellation || 24;
  25408. var subdivisions = options.subdivisions || 1;
  25409. var hasRings = options.hasRings;
  25410. var enclose = options.enclose;
  25411. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25413. var faceUV = options.faceUV || new Array(3);
  25414. var faceColors = options.faceColors;
  25415. // default face colors and UV if undefined
  25416. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25417. var ringNb = (hasRings) ? subdivisions : 1;
  25418. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25419. var f;
  25420. for (f = 0; f < surfaceNb; f++) {
  25421. if (faceColors && faceColors[f] === undefined) {
  25422. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25423. }
  25424. }
  25425. for (f = 0; f < surfaceNb; f++) {
  25426. if (faceUV && faceUV[f] === undefined) {
  25427. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25428. }
  25429. }
  25430. var indices = [];
  25431. var positions = [];
  25432. var normals = [];
  25433. var uvs = [];
  25434. var colors = [];
  25435. var angle_step = Math.PI * 2 * arc / tessellation;
  25436. var angle;
  25437. var h;
  25438. var radius;
  25439. var tan = (diameterBottom - diameterTop) / 2 / height;
  25440. var ringVertex = BABYLON.Vector3.Zero();
  25441. var ringNormal = BABYLON.Vector3.Zero();
  25442. var ringFirstVertex = BABYLON.Vector3.Zero();
  25443. var ringFirstNormal = BABYLON.Vector3.Zero();
  25444. var quadNormal = BABYLON.Vector3.Zero();
  25445. var Y = BABYLON.Axis.Y;
  25446. // positions, normals, uvs
  25447. var i;
  25448. var j;
  25449. var r;
  25450. var ringIdx = 1;
  25451. var s = 1; // surface index
  25452. var cs = 0;
  25453. var v = 0;
  25454. for (i = 0; i <= subdivisions; i++) {
  25455. h = i / subdivisions;
  25456. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25457. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25458. for (r = 0; r < ringIdx; r++) {
  25459. if (hasRings) {
  25460. s += r;
  25461. }
  25462. if (enclose) {
  25463. s += 2 * r;
  25464. }
  25465. for (j = 0; j <= tessellation; j++) {
  25466. angle = j * angle_step;
  25467. // position
  25468. ringVertex.x = Math.cos(-angle) * radius;
  25469. ringVertex.y = -height / 2 + h * height;
  25470. ringVertex.z = Math.sin(-angle) * radius;
  25471. // normal
  25472. if (diameterTop === 0 && i === subdivisions) {
  25473. // if no top cap, reuse former normals
  25474. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25475. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25476. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25477. }
  25478. else {
  25479. ringNormal.x = ringVertex.x;
  25480. ringNormal.z = ringVertex.z;
  25481. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25482. ringNormal.normalize();
  25483. }
  25484. // keep first ring vertex values for enclose
  25485. if (j === 0) {
  25486. ringFirstVertex.copyFrom(ringVertex);
  25487. ringFirstNormal.copyFrom(ringNormal);
  25488. }
  25489. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25490. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25491. if (hasRings) {
  25492. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25493. }
  25494. else {
  25495. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25496. }
  25497. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25498. if (faceColors) {
  25499. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25500. }
  25501. }
  25502. // if enclose, add four vertices and their dedicated normals
  25503. if (arc !== 1 && enclose) {
  25504. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25505. positions.push(0, ringVertex.y, 0);
  25506. positions.push(0, ringVertex.y, 0);
  25507. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25508. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25509. quadNormal.normalize();
  25510. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25511. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25512. quadNormal.normalize();
  25513. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25514. if (hasRings) {
  25515. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25516. }
  25517. else {
  25518. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25519. }
  25520. uvs.push(faceUV[s + 1].x, v);
  25521. uvs.push(faceUV[s + 1].z, v);
  25522. if (hasRings) {
  25523. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25524. }
  25525. else {
  25526. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25527. }
  25528. uvs.push(faceUV[s + 2].x, v);
  25529. uvs.push(faceUV[s + 2].z, v);
  25530. if (faceColors) {
  25531. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25532. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25533. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25534. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25535. }
  25536. }
  25537. if (cs !== s) {
  25538. cs = s;
  25539. }
  25540. }
  25541. }
  25542. // indices
  25543. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25544. var s;
  25545. i = 0;
  25546. for (s = 0; s < subdivisions; s++) {
  25547. for (j = 0; j < tessellation; j++) {
  25548. var i0 = i * (e + 1) + j;
  25549. var i1 = (i + 1) * (e + 1) + j;
  25550. var i2 = i * (e + 1) + (j + 1);
  25551. var i3 = (i + 1) * (e + 1) + (j + 1);
  25552. indices.push(i0, i1, i2);
  25553. indices.push(i3, i2, i1);
  25554. }
  25555. if (arc !== 1 && enclose) {
  25556. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25557. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25558. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25559. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25560. }
  25561. i = (hasRings) ? (i + 2) : (i + 1);
  25562. }
  25563. // Caps
  25564. var createCylinderCap = function (isTop) {
  25565. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25566. if (radius === 0) {
  25567. return;
  25568. }
  25569. // Cap positions, normals & uvs
  25570. var angle;
  25571. var circleVector;
  25572. var i;
  25573. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25574. var c;
  25575. if (faceColors) {
  25576. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25577. }
  25578. // cap center
  25579. var vbase = positions.length / 3;
  25580. var offset = isTop ? height / 2 : -height / 2;
  25581. var center = new BABYLON.Vector3(0, offset, 0);
  25582. positions.push(center.x, center.y, center.z);
  25583. normals.push(0, isTop ? 1 : -1, 0);
  25584. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25585. if (faceColors) {
  25586. colors.push(c.r, c.g, c.b, c.a);
  25587. }
  25588. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25589. for (i = 0; i <= tessellation; i++) {
  25590. angle = Math.PI * 2 * i * arc / tessellation;
  25591. var cos = Math.cos(-angle);
  25592. var sin = Math.sin(-angle);
  25593. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25594. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25595. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25596. normals.push(0, isTop ? 1 : -1, 0);
  25597. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25598. if (faceColors) {
  25599. colors.push(c.r, c.g, c.b, c.a);
  25600. }
  25601. }
  25602. // Cap indices
  25603. for (i = 0; i < tessellation; i++) {
  25604. if (!isTop) {
  25605. indices.push(vbase);
  25606. indices.push(vbase + (i + 1));
  25607. indices.push(vbase + (i + 2));
  25608. }
  25609. else {
  25610. indices.push(vbase);
  25611. indices.push(vbase + (i + 2));
  25612. indices.push(vbase + (i + 1));
  25613. }
  25614. }
  25615. };
  25616. // add caps to geometry
  25617. createCylinderCap(false);
  25618. createCylinderCap(true);
  25619. // Sides
  25620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25621. var vertexData = new VertexData();
  25622. vertexData.indices = indices;
  25623. vertexData.positions = positions;
  25624. vertexData.normals = normals;
  25625. vertexData.uvs = uvs;
  25626. if (faceColors) {
  25627. vertexData.colors = colors;
  25628. }
  25629. return vertexData;
  25630. };
  25631. /**
  25632. * Creates the VertexData of the Torus.
  25633. */
  25634. VertexData.CreateTorus = function (options) {
  25635. var indices = [];
  25636. var positions = [];
  25637. var normals = [];
  25638. var uvs = [];
  25639. var diameter = options.diameter || 1;
  25640. var thickness = options.thickness || 0.5;
  25641. var tessellation = options.tessellation || 16;
  25642. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25643. var stride = tessellation + 1;
  25644. for (var i = 0; i <= tessellation; i++) {
  25645. var u = i / tessellation;
  25646. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25647. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25648. for (var j = 0; j <= tessellation; j++) {
  25649. var v = 1 - j / tessellation;
  25650. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25651. var dx = Math.cos(innerAngle);
  25652. var dy = Math.sin(innerAngle);
  25653. // Create a vertex.
  25654. var normal = new BABYLON.Vector3(dx, dy, 0);
  25655. var position = normal.scale(thickness / 2);
  25656. var textureCoordinate = new BABYLON.Vector2(u, v);
  25657. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25658. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25659. positions.push(position.x, position.y, position.z);
  25660. normals.push(normal.x, normal.y, normal.z);
  25661. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25662. // And create indices for two triangles.
  25663. var nextI = (i + 1) % stride;
  25664. var nextJ = (j + 1) % stride;
  25665. indices.push(i * stride + j);
  25666. indices.push(i * stride + nextJ);
  25667. indices.push(nextI * stride + j);
  25668. indices.push(i * stride + nextJ);
  25669. indices.push(nextI * stride + nextJ);
  25670. indices.push(nextI * stride + j);
  25671. }
  25672. }
  25673. // Sides
  25674. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25675. // Result
  25676. var vertexData = new VertexData();
  25677. vertexData.indices = indices;
  25678. vertexData.positions = positions;
  25679. vertexData.normals = normals;
  25680. vertexData.uvs = uvs;
  25681. return vertexData;
  25682. };
  25683. /**
  25684. * Creates the VertexData of the LineSystem.
  25685. */
  25686. VertexData.CreateLineSystem = function (options) {
  25687. var indices = [];
  25688. var positions = [];
  25689. var lines = options.lines;
  25690. var idx = 0;
  25691. for (var l = 0; l < lines.length; l++) {
  25692. var points = lines[l];
  25693. for (var index = 0; index < points.length; index++) {
  25694. positions.push(points[index].x, points[index].y, points[index].z);
  25695. if (index > 0) {
  25696. indices.push(idx - 1);
  25697. indices.push(idx);
  25698. }
  25699. idx++;
  25700. }
  25701. }
  25702. var vertexData = new VertexData();
  25703. vertexData.indices = indices;
  25704. vertexData.positions = positions;
  25705. return vertexData;
  25706. };
  25707. /**
  25708. * Create the VertexData of the DashedLines.
  25709. */
  25710. VertexData.CreateDashedLines = function (options) {
  25711. var dashSize = options.dashSize || 3;
  25712. var gapSize = options.gapSize || 1;
  25713. var dashNb = options.dashNb || 200;
  25714. var points = options.points;
  25715. var positions = new Array();
  25716. var indices = new Array();
  25717. var curvect = BABYLON.Vector3.Zero();
  25718. var lg = 0;
  25719. var nb = 0;
  25720. var shft = 0;
  25721. var dashshft = 0;
  25722. var curshft = 0;
  25723. var idx = 0;
  25724. var i = 0;
  25725. for (i = 0; i < points.length - 1; i++) {
  25726. points[i + 1].subtractToRef(points[i], curvect);
  25727. lg += curvect.length();
  25728. }
  25729. shft = lg / dashNb;
  25730. dashshft = dashSize * shft / (dashSize + gapSize);
  25731. for (i = 0; i < points.length - 1; i++) {
  25732. points[i + 1].subtractToRef(points[i], curvect);
  25733. nb = Math.floor(curvect.length() / shft);
  25734. curvect.normalize();
  25735. for (var j = 0; j < nb; j++) {
  25736. curshft = shft * j;
  25737. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25738. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25739. indices.push(idx, idx + 1);
  25740. idx += 2;
  25741. }
  25742. }
  25743. // Result
  25744. var vertexData = new VertexData();
  25745. vertexData.positions = positions;
  25746. vertexData.indices = indices;
  25747. return vertexData;
  25748. };
  25749. /**
  25750. * Creates the VertexData of the Ground.
  25751. */
  25752. VertexData.CreateGround = function (options) {
  25753. var indices = [];
  25754. var positions = [];
  25755. var normals = [];
  25756. var uvs = [];
  25757. var row, col;
  25758. var width = options.width || 1;
  25759. var height = options.height || 1;
  25760. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25761. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25762. for (row = 0; row <= subdivisionsY; row++) {
  25763. for (col = 0; col <= subdivisionsX; col++) {
  25764. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25765. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25766. positions.push(position.x, position.y, position.z);
  25767. normals.push(normal.x, normal.y, normal.z);
  25768. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25769. }
  25770. }
  25771. for (row = 0; row < subdivisionsY; row++) {
  25772. for (col = 0; col < subdivisionsX; col++) {
  25773. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25774. indices.push(col + 1 + row * (subdivisionsX + 1));
  25775. indices.push(col + row * (subdivisionsX + 1));
  25776. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25777. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25778. indices.push(col + row * (subdivisionsX + 1));
  25779. }
  25780. }
  25781. // Result
  25782. var vertexData = new VertexData();
  25783. vertexData.indices = indices;
  25784. vertexData.positions = positions;
  25785. vertexData.normals = normals;
  25786. vertexData.uvs = uvs;
  25787. return vertexData;
  25788. };
  25789. /**
  25790. * Creates the VertexData of the TiledGround.
  25791. */
  25792. VertexData.CreateTiledGround = function (options) {
  25793. var xmin = options.xmin || -1.0;
  25794. var zmin = options.zmin || -1.0;
  25795. var xmax = options.xmax || 1.0;
  25796. var zmax = options.zmax || 1.0;
  25797. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25798. var precision = options.precision || { w: 1, h: 1 };
  25799. var indices = [];
  25800. var positions = [];
  25801. var normals = [];
  25802. var uvs = [];
  25803. var row, col, tileRow, tileCol;
  25804. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25805. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25806. precision.w = (precision.w < 1) ? 1 : precision.w;
  25807. precision.h = (precision.h < 1) ? 1 : precision.h;
  25808. var tileSize = {
  25809. 'w': (xmax - xmin) / subdivisions.w,
  25810. 'h': (zmax - zmin) / subdivisions.h
  25811. };
  25812. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25813. // Indices
  25814. var base = positions.length / 3;
  25815. var rowLength = precision.w + 1;
  25816. for (row = 0; row < precision.h; row++) {
  25817. for (col = 0; col < precision.w; col++) {
  25818. var square = [
  25819. base + col + row * rowLength,
  25820. base + (col + 1) + row * rowLength,
  25821. base + (col + 1) + (row + 1) * rowLength,
  25822. base + col + (row + 1) * rowLength
  25823. ];
  25824. indices.push(square[1]);
  25825. indices.push(square[2]);
  25826. indices.push(square[3]);
  25827. indices.push(square[0]);
  25828. indices.push(square[1]);
  25829. indices.push(square[3]);
  25830. }
  25831. }
  25832. // Position, normals and uvs
  25833. var position = BABYLON.Vector3.Zero();
  25834. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25835. for (row = 0; row <= precision.h; row++) {
  25836. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25837. for (col = 0; col <= precision.w; col++) {
  25838. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25839. position.y = 0;
  25840. positions.push(position.x, position.y, position.z);
  25841. normals.push(normal.x, normal.y, normal.z);
  25842. uvs.push(col / precision.w, row / precision.h);
  25843. }
  25844. }
  25845. }
  25846. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25847. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25848. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25849. }
  25850. }
  25851. // Result
  25852. var vertexData = new VertexData();
  25853. vertexData.indices = indices;
  25854. vertexData.positions = positions;
  25855. vertexData.normals = normals;
  25856. vertexData.uvs = uvs;
  25857. return vertexData;
  25858. };
  25859. /**
  25860. * Creates the VertexData of the Ground designed from a heightmap.
  25861. */
  25862. VertexData.CreateGroundFromHeightMap = function (options) {
  25863. var indices = [];
  25864. var positions = [];
  25865. var normals = [];
  25866. var uvs = [];
  25867. var row, col;
  25868. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25869. // Vertices
  25870. for (row = 0; row <= options.subdivisions; row++) {
  25871. for (col = 0; col <= options.subdivisions; col++) {
  25872. 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));
  25873. // Compute height
  25874. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25875. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25876. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25877. var r = options.buffer[pos] / 255.0;
  25878. var g = options.buffer[pos + 1] / 255.0;
  25879. var b = options.buffer[pos + 2] / 255.0;
  25880. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25881. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25882. // Add vertex
  25883. positions.push(position.x, position.y, position.z);
  25884. normals.push(0, 0, 0);
  25885. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25886. }
  25887. }
  25888. // Indices
  25889. for (row = 0; row < options.subdivisions; row++) {
  25890. for (col = 0; col < options.subdivisions; col++) {
  25891. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25892. indices.push(col + 1 + row * (options.subdivisions + 1));
  25893. indices.push(col + row * (options.subdivisions + 1));
  25894. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25895. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25896. indices.push(col + row * (options.subdivisions + 1));
  25897. }
  25898. }
  25899. // Normals
  25900. VertexData.ComputeNormals(positions, indices, normals);
  25901. // Result
  25902. var vertexData = new VertexData();
  25903. vertexData.indices = indices;
  25904. vertexData.positions = positions;
  25905. vertexData.normals = normals;
  25906. vertexData.uvs = uvs;
  25907. return vertexData;
  25908. };
  25909. /**
  25910. * Creates the VertexData of the Plane.
  25911. */
  25912. VertexData.CreatePlane = function (options) {
  25913. var indices = [];
  25914. var positions = [];
  25915. var normals = [];
  25916. var uvs = [];
  25917. var width = options.width || options.size || 1;
  25918. var height = options.height || options.size || 1;
  25919. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25920. // Vertices
  25921. var halfWidth = width / 2.0;
  25922. var halfHeight = height / 2.0;
  25923. positions.push(-halfWidth, -halfHeight, 0);
  25924. normals.push(0, 0, -1.0);
  25925. uvs.push(0.0, 0.0);
  25926. positions.push(halfWidth, -halfHeight, 0);
  25927. normals.push(0, 0, -1.0);
  25928. uvs.push(1.0, 0.0);
  25929. positions.push(halfWidth, halfHeight, 0);
  25930. normals.push(0, 0, -1.0);
  25931. uvs.push(1.0, 1.0);
  25932. positions.push(-halfWidth, halfHeight, 0);
  25933. normals.push(0, 0, -1.0);
  25934. uvs.push(0.0, 1.0);
  25935. // Indices
  25936. indices.push(0);
  25937. indices.push(1);
  25938. indices.push(2);
  25939. indices.push(0);
  25940. indices.push(2);
  25941. indices.push(3);
  25942. // Sides
  25943. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25944. // Result
  25945. var vertexData = new VertexData();
  25946. vertexData.indices = indices;
  25947. vertexData.positions = positions;
  25948. vertexData.normals = normals;
  25949. vertexData.uvs = uvs;
  25950. return vertexData;
  25951. };
  25952. /**
  25953. * Creates the VertexData of the Disc or regular Polygon.
  25954. */
  25955. VertexData.CreateDisc = function (options) {
  25956. var positions = [];
  25957. var indices = [];
  25958. var normals = [];
  25959. var uvs = [];
  25960. var radius = options.radius || 0.5;
  25961. var tessellation = options.tessellation || 64;
  25962. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25963. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25964. // positions and uvs
  25965. positions.push(0, 0, 0); // disc center first
  25966. uvs.push(0.5, 0.5);
  25967. var theta = Math.PI * 2 * arc;
  25968. var step = theta / tessellation;
  25969. for (var a = 0; a < theta; a += step) {
  25970. var x = Math.cos(a);
  25971. var y = Math.sin(a);
  25972. var u = (x + 1) / 2;
  25973. var v = (1 - y) / 2;
  25974. positions.push(radius * x, radius * y, 0);
  25975. uvs.push(u, v);
  25976. }
  25977. if (arc === 1) {
  25978. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25979. uvs.push(uvs[2], uvs[3]);
  25980. }
  25981. //indices
  25982. var vertexNb = positions.length / 3;
  25983. for (var i = 1; i < vertexNb - 1; i++) {
  25984. indices.push(i + 1, 0, i);
  25985. }
  25986. // result
  25987. VertexData.ComputeNormals(positions, indices, normals);
  25988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25989. var vertexData = new VertexData();
  25990. vertexData.indices = indices;
  25991. vertexData.positions = positions;
  25992. vertexData.normals = normals;
  25993. vertexData.uvs = uvs;
  25994. return vertexData;
  25995. };
  25996. /**
  25997. * Re-creates the VertexData of the Polygon for sideOrientation.
  25998. */
  25999. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26000. var faceUV = fUV || new Array(3);
  26001. var faceColors = fColors;
  26002. var colors = [];
  26003. // default face colors and UV if undefined
  26004. for (var f = 0; f < 3; f++) {
  26005. if (faceUV[f] === undefined) {
  26006. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26007. }
  26008. if (faceColors && faceColors[f] === undefined) {
  26009. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26010. }
  26011. }
  26012. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26013. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26014. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26015. var indices = polygon.getIndices();
  26016. // set face colours and textures
  26017. var idx = 0;
  26018. var face = 0;
  26019. for (var index = 0; index < normals.length; index += 3) {
  26020. //Edge Face no. 1
  26021. if (Math.abs(normals[index + 1]) == 0) {
  26022. face = 1;
  26023. }
  26024. //Top Face no. 0
  26025. if (normals[index + 1] == 1) {
  26026. face = 0;
  26027. }
  26028. //Bottom Face no. 2
  26029. if (normals[index + 1] == -1) {
  26030. face = 2;
  26031. }
  26032. idx = index / 3;
  26033. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26034. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26035. if (faceColors) {
  26036. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26037. }
  26038. }
  26039. // sides
  26040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26041. // Result
  26042. var vertexData = new VertexData();
  26043. vertexData.indices = indices;
  26044. vertexData.positions = positions;
  26045. vertexData.normals = normals;
  26046. vertexData.uvs = uvs;
  26047. if (faceColors) {
  26048. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26049. vertexData.colors = totalColors;
  26050. }
  26051. return vertexData;
  26052. };
  26053. /**
  26054. * Creates the VertexData of the IcoSphere.
  26055. */
  26056. VertexData.CreateIcoSphere = function (options) {
  26057. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26058. var radius = options.radius || 1;
  26059. var flat = (options.flat === undefined) ? true : options.flat;
  26060. var subdivisions = options.subdivisions || 4;
  26061. var radiusX = options.radiusX || radius;
  26062. var radiusY = options.radiusY || radius;
  26063. var radiusZ = options.radiusZ || radius;
  26064. var t = (1 + Math.sqrt(5)) / 2;
  26065. // 12 vertex x,y,z
  26066. var ico_vertices = [
  26067. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26068. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26069. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26070. ];
  26071. // index of 3 vertex makes a face of icopshere
  26072. var ico_indices = [
  26073. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26074. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26075. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26076. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26077. ];
  26078. // vertex for uv have aliased position, not for UV
  26079. var vertices_unalias_id = [
  26080. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26081. // vertex alias
  26082. 0,
  26083. 2,
  26084. 3,
  26085. 3,
  26086. 3,
  26087. 4,
  26088. 7,
  26089. 8,
  26090. 9,
  26091. 9,
  26092. 10,
  26093. 11 // 23: B + 12
  26094. ];
  26095. // uv as integer step (not pixels !)
  26096. var ico_vertexuv = [
  26097. 5, 1, 3, 1, 6, 4, 0, 0,
  26098. 5, 3, 4, 2, 2, 2, 4, 0,
  26099. 2, 0, 1, 1, 6, 0, 6, 2,
  26100. // vertex alias (for same vertex on different faces)
  26101. 0, 4,
  26102. 3, 3,
  26103. 4, 4,
  26104. 3, 1,
  26105. 4, 2,
  26106. 4, 4,
  26107. 0, 2,
  26108. 1, 1,
  26109. 2, 2,
  26110. 3, 3,
  26111. 1, 3,
  26112. 2, 4 // 23: B + 12
  26113. ];
  26114. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26115. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26116. // First island of uv mapping
  26117. // v = 4h 3+ 2
  26118. // v = 3h 9+ 4
  26119. // v = 2h 9+ 5 B
  26120. // v = 1h 9 1 0
  26121. // v = 0h 3 8 7 A
  26122. // u = 0 1 2 3 4 5 6 *a
  26123. // Second island of uv mapping
  26124. // v = 4h 0+ B+ 4+
  26125. // v = 3h A+ 2+
  26126. // v = 2h 7+ 6 3+
  26127. // v = 1h 8+ 3+
  26128. // v = 0h
  26129. // u = 0 1 2 3 4 5 6 *a
  26130. // Face layout on texture UV mapping
  26131. // ============
  26132. // \ 4 /\ 16 / ======
  26133. // \ / \ / /\ 11 /
  26134. // \/ 7 \/ / \ /
  26135. // ======= / 10 \/
  26136. // /\ 17 /\ =======
  26137. // / \ / \ \ 15 /\
  26138. // / 8 \/ 12 \ \ / \
  26139. // ============ \/ 6 \
  26140. // \ 18 /\ ============
  26141. // \ / \ \ 5 /\ 0 /
  26142. // \/ 13 \ \ / \ /
  26143. // ======= \/ 1 \/
  26144. // =============
  26145. // /\ 19 /\ 2 /\
  26146. // / \ / \ / \
  26147. // / 14 \/ 9 \/ 3 \
  26148. // ===================
  26149. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26150. var ustep = 138 / 1024;
  26151. var vstep = 239 / 1024;
  26152. var uoffset = 60 / 1024;
  26153. var voffset = 26 / 1024;
  26154. // Second island should have margin, not to touch the first island
  26155. // avoid any borderline artefact in pixel rounding
  26156. var island_u_offset = -40 / 1024;
  26157. var island_v_offset = +20 / 1024;
  26158. // face is either island 0 or 1 :
  26159. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26160. var island = [
  26161. 0, 0, 0, 0, 1,
  26162. 0, 0, 1, 1, 0,
  26163. 0, 0, 1, 1, 0,
  26164. 0, 1, 1, 1, 0 // 15 - 19
  26165. ];
  26166. var indices = [];
  26167. var positions = [];
  26168. var normals = [];
  26169. var uvs = [];
  26170. var current_indice = 0;
  26171. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26172. var face_vertex_pos = new Array(3);
  26173. var face_vertex_uv = new Array(3);
  26174. var v012;
  26175. for (v012 = 0; v012 < 3; v012++) {
  26176. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26177. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26178. }
  26179. // create all with normals
  26180. for (var face = 0; face < 20; face++) {
  26181. // 3 vertex per face
  26182. for (v012 = 0; v012 < 3; v012++) {
  26183. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26184. var v_id = ico_indices[3 * face + v012];
  26185. // vertex have 3D position (x,y,z)
  26186. 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]);
  26187. // Normalize to get normal, then scale to radius
  26188. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26189. // uv Coordinates from vertex ID
  26190. 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);
  26191. }
  26192. // Subdivide the face (interpolate pos, norm, uv)
  26193. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26194. // - norm is linear interpolation of vertex corner normal
  26195. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26196. // - uv is linear interpolation
  26197. //
  26198. // Topology is as below for sub-divide by 2
  26199. // vertex shown as v0,v1,v2
  26200. // interp index is i1 to progress in range [v0,v1[
  26201. // interp index is i2 to progress in range [v0,v2[
  26202. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26203. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26204. //
  26205. //
  26206. // i2 v2
  26207. // ^ ^
  26208. // / / \
  26209. // / / \
  26210. // / / \
  26211. // / / (0,1) \
  26212. // / #---------\
  26213. // / / \ (0,0)'/ \
  26214. // / / \ / \
  26215. // / / \ / \
  26216. // / / (0,0) \ / (1,0) \
  26217. // / #---------#---------\
  26218. // v0 v1
  26219. //
  26220. // --------------------> i1
  26221. //
  26222. // interp of (i1,i2):
  26223. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26224. // along i1 : lerp(x0,x1, i1/(S-i2))
  26225. //
  26226. // centroid of triangle is needed to get help normal computation
  26227. // (c1,c2) are used for centroid location
  26228. var interp_vertex = function (i1, i2, c1, c2) {
  26229. // vertex is interpolated from
  26230. // - face_vertex_pos[0..2]
  26231. // - face_vertex_uv[0..2]
  26232. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26233. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26234. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26235. pos_interp.normalize();
  26236. var vertex_normal;
  26237. if (flat) {
  26238. // in flat mode, recalculate normal as face centroid normal
  26239. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26240. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26241. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26242. }
  26243. else {
  26244. // in smooth mode, recalculate normal from each single vertex position
  26245. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26246. }
  26247. // Vertex normal need correction due to X,Y,Z radius scaling
  26248. vertex_normal.x /= radiusX;
  26249. vertex_normal.y /= radiusY;
  26250. vertex_normal.z /= radiusZ;
  26251. vertex_normal.normalize();
  26252. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26253. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26254. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26255. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26256. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26257. uvs.push(uv_interp.x, uv_interp.y);
  26258. // push each vertex has member of a face
  26259. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26260. indices.push(current_indice);
  26261. current_indice++;
  26262. };
  26263. for (var i2 = 0; i2 < subdivisions; i2++) {
  26264. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26265. // face : (i1,i2) for /\ :
  26266. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26267. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26268. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26269. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26270. if (i1 + i2 + 1 < subdivisions) {
  26271. // face : (i1,i2)' for \/ :
  26272. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26273. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26274. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26275. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26276. }
  26277. }
  26278. }
  26279. }
  26280. // Sides
  26281. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26282. // Result
  26283. var vertexData = new VertexData();
  26284. vertexData.indices = indices;
  26285. vertexData.positions = positions;
  26286. vertexData.normals = normals;
  26287. vertexData.uvs = uvs;
  26288. return vertexData;
  26289. };
  26290. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26291. /**
  26292. * Creates the VertexData of the Polyhedron.
  26293. */
  26294. VertexData.CreatePolyhedron = function (options) {
  26295. // provided polyhedron types :
  26296. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26297. // 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)
  26298. var polyhedra = [];
  26299. 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]] };
  26300. 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]] };
  26301. polyhedra[2] = {
  26302. 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]],
  26303. 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]]
  26304. };
  26305. polyhedra[3] = {
  26306. 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]],
  26307. 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]]
  26308. };
  26309. polyhedra[4] = {
  26310. 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]],
  26311. 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]]
  26312. };
  26313. 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]] };
  26314. 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]] };
  26315. 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]] };
  26316. 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]] };
  26317. 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]] };
  26318. 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]] };
  26319. 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]] };
  26320. 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]] };
  26321. 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]] };
  26322. polyhedra[14] = {
  26323. 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]],
  26324. 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]]
  26325. };
  26326. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26327. var size = options.size;
  26328. var sizeX = options.sizeX || size || 1;
  26329. var sizeY = options.sizeY || size || 1;
  26330. var sizeZ = options.sizeZ || size || 1;
  26331. var data = options.custom || polyhedra[type];
  26332. var nbfaces = data.face.length;
  26333. var faceUV = options.faceUV || new Array(nbfaces);
  26334. var faceColors = options.faceColors;
  26335. var flat = (options.flat === undefined) ? true : options.flat;
  26336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26337. var positions = [];
  26338. var indices = [];
  26339. var normals = [];
  26340. var uvs = [];
  26341. var colors = [];
  26342. var index = 0;
  26343. var faceIdx = 0; // face cursor in the array "indexes"
  26344. var indexes = [];
  26345. var i = 0;
  26346. var f = 0;
  26347. var u, v, ang, x, y, tmp;
  26348. // default face colors and UV if undefined
  26349. if (flat) {
  26350. for (f = 0; f < nbfaces; f++) {
  26351. if (faceColors && faceColors[f] === undefined) {
  26352. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26353. }
  26354. if (faceUV && faceUV[f] === undefined) {
  26355. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26356. }
  26357. }
  26358. }
  26359. if (!flat) {
  26360. for (i = 0; i < data.vertex.length; i++) {
  26361. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26362. uvs.push(0, 0);
  26363. }
  26364. for (f = 0; f < nbfaces; f++) {
  26365. for (i = 0; i < data.face[f].length - 2; i++) {
  26366. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26367. }
  26368. }
  26369. }
  26370. else {
  26371. for (f = 0; f < nbfaces; f++) {
  26372. var fl = data.face[f].length; // number of vertices of the current face
  26373. ang = 2 * Math.PI / fl;
  26374. x = 0.5 * Math.tan(ang / 2);
  26375. y = 0.5;
  26376. // positions, uvs, colors
  26377. for (i = 0; i < fl; i++) {
  26378. // positions
  26379. 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);
  26380. indexes.push(index);
  26381. index++;
  26382. // uvs
  26383. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26384. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26385. uvs.push(u, v);
  26386. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26387. y = x * Math.sin(ang) + y * Math.cos(ang);
  26388. x = tmp;
  26389. // colors
  26390. if (faceColors) {
  26391. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26392. }
  26393. }
  26394. // indices from indexes
  26395. for (i = 0; i < fl - 2; i++) {
  26396. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26397. }
  26398. faceIdx += fl;
  26399. }
  26400. }
  26401. VertexData.ComputeNormals(positions, indices, normals);
  26402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26403. var vertexData = new VertexData();
  26404. vertexData.positions = positions;
  26405. vertexData.indices = indices;
  26406. vertexData.normals = normals;
  26407. vertexData.uvs = uvs;
  26408. if (faceColors && flat) {
  26409. vertexData.colors = colors;
  26410. }
  26411. return vertexData;
  26412. };
  26413. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26414. /**
  26415. * Creates the VertexData of the Torus Knot.
  26416. */
  26417. VertexData.CreateTorusKnot = function (options) {
  26418. var indices = [];
  26419. var positions = [];
  26420. var normals = [];
  26421. var uvs = [];
  26422. var radius = options.radius || 2;
  26423. var tube = options.tube || 0.5;
  26424. var radialSegments = options.radialSegments || 32;
  26425. var tubularSegments = options.tubularSegments || 32;
  26426. var p = options.p || 2;
  26427. var q = options.q || 3;
  26428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26429. // Helper
  26430. var getPos = function (angle) {
  26431. var cu = Math.cos(angle);
  26432. var su = Math.sin(angle);
  26433. var quOverP = q / p * angle;
  26434. var cs = Math.cos(quOverP);
  26435. var tx = radius * (2 + cs) * 0.5 * cu;
  26436. var ty = radius * (2 + cs) * su * 0.5;
  26437. var tz = radius * Math.sin(quOverP) * 0.5;
  26438. return new BABYLON.Vector3(tx, ty, tz);
  26439. };
  26440. // Vertices
  26441. var i;
  26442. var j;
  26443. for (i = 0; i <= radialSegments; i++) {
  26444. var modI = i % radialSegments;
  26445. var u = modI / radialSegments * 2 * p * Math.PI;
  26446. var p1 = getPos(u);
  26447. var p2 = getPos(u + 0.01);
  26448. var tang = p2.subtract(p1);
  26449. var n = p2.add(p1);
  26450. var bitan = BABYLON.Vector3.Cross(tang, n);
  26451. n = BABYLON.Vector3.Cross(bitan, tang);
  26452. bitan.normalize();
  26453. n.normalize();
  26454. for (j = 0; j < tubularSegments; j++) {
  26455. var modJ = j % tubularSegments;
  26456. var v = modJ / tubularSegments * 2 * Math.PI;
  26457. var cx = -tube * Math.cos(v);
  26458. var cy = tube * Math.sin(v);
  26459. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26460. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26461. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26462. uvs.push(i / radialSegments);
  26463. uvs.push(j / tubularSegments);
  26464. }
  26465. }
  26466. for (i = 0; i < radialSegments; i++) {
  26467. for (j = 0; j < tubularSegments; j++) {
  26468. var jNext = (j + 1) % tubularSegments;
  26469. var a = i * tubularSegments + j;
  26470. var b = (i + 1) * tubularSegments + j;
  26471. var c = (i + 1) * tubularSegments + jNext;
  26472. var d = i * tubularSegments + jNext;
  26473. indices.push(d);
  26474. indices.push(b);
  26475. indices.push(a);
  26476. indices.push(d);
  26477. indices.push(c);
  26478. indices.push(b);
  26479. }
  26480. }
  26481. // Normals
  26482. VertexData.ComputeNormals(positions, indices, normals);
  26483. // Sides
  26484. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26485. // Result
  26486. var vertexData = new VertexData();
  26487. vertexData.indices = indices;
  26488. vertexData.positions = positions;
  26489. vertexData.normals = normals;
  26490. vertexData.uvs = uvs;
  26491. return vertexData;
  26492. };
  26493. // Tools
  26494. /**
  26495. * @param {any} - positions (number[] or Float32Array)
  26496. * @param {any} - indices (number[] or Uint16Array)
  26497. * @param {any} - normals (number[] or Float32Array)
  26498. * options (optional) :
  26499. * facetPositions : optional array of facet positions (vector3)
  26500. * facetNormals : optional array of facet normals (vector3)
  26501. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26502. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26503. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26504. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26505. * bInfo : optional bounding info, required for facetPartitioning computation
  26506. */
  26507. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26508. // temporary scalar variables
  26509. var index = 0; // facet index
  26510. var p1p2x = 0.0; // p1p2 vector x coordinate
  26511. var p1p2y = 0.0; // p1p2 vector y coordinate
  26512. var p1p2z = 0.0; // p1p2 vector z coordinate
  26513. var p3p2x = 0.0; // p3p2 vector x coordinate
  26514. var p3p2y = 0.0; // p3p2 vector y coordinate
  26515. var p3p2z = 0.0; // p3p2 vector z coordinate
  26516. var faceNormalx = 0.0; // facet normal x coordinate
  26517. var faceNormaly = 0.0; // facet normal y coordinate
  26518. var faceNormalz = 0.0; // facet normal z coordinate
  26519. var length = 0.0; // facet normal length before normalization
  26520. var v1x = 0; // vector1 x index in the positions array
  26521. var v1y = 0; // vector1 y index in the positions array
  26522. var v1z = 0; // vector1 z index in the positions array
  26523. var v2x = 0; // vector2 x index in the positions array
  26524. var v2y = 0; // vector2 y index in the positions array
  26525. var v2z = 0; // vector2 z index in the positions array
  26526. var v3x = 0; // vector3 x index in the positions array
  26527. var v3y = 0; // vector3 y index in the positions array
  26528. var v3z = 0; // vector3 z index in the positions array
  26529. var computeFacetNormals = false;
  26530. var computeFacetPositions = false;
  26531. var computeFacetPartitioning = false;
  26532. var faceNormalSign = 1;
  26533. if (options) {
  26534. computeFacetNormals = (options.facetNormals) ? true : false;
  26535. computeFacetPositions = (options.facetPositions) ? true : false;
  26536. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26537. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26538. }
  26539. // facetPartitioning reinit if needed
  26540. if (computeFacetPartitioning) {
  26541. var ox = 0; // X partitioning index for facet position
  26542. var oy = 0; // Y partinioning index for facet position
  26543. var oz = 0; // Z partinioning index for facet position
  26544. var b1x = 0; // X partitioning index for facet v1 vertex
  26545. var b1y = 0; // Y partitioning index for facet v1 vertex
  26546. var b1z = 0; // z partitioning index for facet v1 vertex
  26547. var b2x = 0; // X partitioning index for facet v2 vertex
  26548. var b2y = 0; // Y partitioning index for facet v2 vertex
  26549. var b2z = 0; // Z partitioning index for facet v2 vertex
  26550. var b3x = 0; // X partitioning index for facet v3 vertex
  26551. var b3y = 0; // Y partitioning index for facet v3 vertex
  26552. var b3z = 0; // Z partitioning index for facet v3 vertex
  26553. var block_idx_o = 0; // facet barycenter block index
  26554. var block_idx_v1 = 0; // v1 vertex block index
  26555. var block_idx_v2 = 0; // v2 vertex block index
  26556. var block_idx_v3 = 0; // v3 vertex block index
  26557. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26558. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26559. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26560. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26561. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26562. var subSq = options.subDiv.max * options.subDiv.max;
  26563. options.facetPartitioning.length = 0;
  26564. }
  26565. // reset the normals
  26566. for (index = 0; index < positions.length; index++) {
  26567. normals[index] = 0.0;
  26568. }
  26569. // Loop : 1 indice triplet = 1 facet
  26570. var nbFaces = indices.length / 3;
  26571. for (index = 0; index < nbFaces; index++) {
  26572. // get the indexes of the coordinates of each vertex of the facet
  26573. v1x = indices[index * 3] * 3;
  26574. v1y = v1x + 1;
  26575. v1z = v1x + 2;
  26576. v2x = indices[index * 3 + 1] * 3;
  26577. v2y = v2x + 1;
  26578. v2z = v2x + 2;
  26579. v3x = indices[index * 3 + 2] * 3;
  26580. v3y = v3x + 1;
  26581. v3z = v3x + 2;
  26582. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26583. p1p2y = positions[v1y] - positions[v2y];
  26584. p1p2z = positions[v1z] - positions[v2z];
  26585. p3p2x = positions[v3x] - positions[v2x];
  26586. p3p2y = positions[v3y] - positions[v2y];
  26587. p3p2z = positions[v3z] - positions[v2z];
  26588. // compute the face normal with the cross product
  26589. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26590. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26591. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26592. // normalize this normal and store it in the array facetData
  26593. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26594. length = (length === 0) ? 1.0 : length;
  26595. faceNormalx /= length;
  26596. faceNormaly /= length;
  26597. faceNormalz /= length;
  26598. if (computeFacetNormals) {
  26599. options.facetNormals[index].x = faceNormalx;
  26600. options.facetNormals[index].y = faceNormaly;
  26601. options.facetNormals[index].z = faceNormalz;
  26602. }
  26603. if (computeFacetPositions) {
  26604. // compute and the facet barycenter coordinates in the array facetPositions
  26605. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26606. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26607. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26608. }
  26609. if (computeFacetPartitioning) {
  26610. // store the facet indexes in arrays in the main facetPartitioning array :
  26611. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26612. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26613. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26614. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26615. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26616. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26617. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26618. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26619. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26620. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26621. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26622. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26623. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26624. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26625. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26626. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26627. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26628. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26629. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26630. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26631. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26632. // push each facet index in each block containing the vertex
  26633. options.facetPartitioning[block_idx_v1].push(index);
  26634. if (block_idx_v2 != block_idx_v1) {
  26635. options.facetPartitioning[block_idx_v2].push(index);
  26636. }
  26637. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26638. options.facetPartitioning[block_idx_v3].push(index);
  26639. }
  26640. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26641. options.facetPartitioning[block_idx_o].push(index);
  26642. }
  26643. }
  26644. // compute the normals anyway
  26645. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26646. normals[v1y] += faceNormaly;
  26647. normals[v1z] += faceNormalz;
  26648. normals[v2x] += faceNormalx;
  26649. normals[v2y] += faceNormaly;
  26650. normals[v2z] += faceNormalz;
  26651. normals[v3x] += faceNormalx;
  26652. normals[v3y] += faceNormaly;
  26653. normals[v3z] += faceNormalz;
  26654. }
  26655. // last normalization of each normal
  26656. for (index = 0; index < normals.length / 3; index++) {
  26657. faceNormalx = normals[index * 3];
  26658. faceNormaly = normals[index * 3 + 1];
  26659. faceNormalz = normals[index * 3 + 2];
  26660. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26661. length = (length === 0) ? 1.0 : length;
  26662. faceNormalx /= length;
  26663. faceNormaly /= length;
  26664. faceNormalz /= length;
  26665. normals[index * 3] = faceNormalx;
  26666. normals[index * 3 + 1] = faceNormaly;
  26667. normals[index * 3 + 2] = faceNormalz;
  26668. }
  26669. };
  26670. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26671. var li = indices.length;
  26672. var ln = normals.length;
  26673. var i;
  26674. var n;
  26675. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26676. switch (sideOrientation) {
  26677. case BABYLON.Mesh.FRONTSIDE:
  26678. // nothing changed
  26679. break;
  26680. case BABYLON.Mesh.BACKSIDE:
  26681. var tmp;
  26682. // indices
  26683. for (i = 0; i < li; i += 3) {
  26684. tmp = indices[i];
  26685. indices[i] = indices[i + 2];
  26686. indices[i + 2] = tmp;
  26687. }
  26688. // normals
  26689. for (n = 0; n < ln; n++) {
  26690. normals[n] = -normals[n];
  26691. }
  26692. break;
  26693. case BABYLON.Mesh.DOUBLESIDE:
  26694. // positions
  26695. var lp = positions.length;
  26696. var l = lp / 3;
  26697. for (var p = 0; p < lp; p++) {
  26698. positions[lp + p] = positions[p];
  26699. }
  26700. // indices
  26701. for (i = 0; i < li; i += 3) {
  26702. indices[i + li] = indices[i + 2] + l;
  26703. indices[i + 1 + li] = indices[i + 1] + l;
  26704. indices[i + 2 + li] = indices[i] + l;
  26705. }
  26706. // normals
  26707. for (n = 0; n < ln; n++) {
  26708. normals[ln + n] = -normals[n];
  26709. }
  26710. // uvs
  26711. var lu = uvs.length;
  26712. var u = 0;
  26713. for (u = 0; u < lu; u++) {
  26714. uvs[u + lu] = uvs[u];
  26715. }
  26716. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26717. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26718. u = 0;
  26719. for (i = 0; i < lu / 2; i++) {
  26720. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26721. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26722. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26723. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26724. u += 2;
  26725. }
  26726. break;
  26727. }
  26728. };
  26729. /**
  26730. * Creates a new VertexData from the imported parameters.
  26731. */
  26732. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26733. var vertexData = new VertexData();
  26734. // positions
  26735. var positions = parsedVertexData.positions;
  26736. if (positions) {
  26737. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26738. }
  26739. // normals
  26740. var normals = parsedVertexData.normals;
  26741. if (normals) {
  26742. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26743. }
  26744. // tangents
  26745. var tangents = parsedVertexData.tangents;
  26746. if (tangents) {
  26747. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26748. }
  26749. // uvs
  26750. var uvs = parsedVertexData.uvs;
  26751. if (uvs) {
  26752. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26753. }
  26754. // uv2s
  26755. var uv2s = parsedVertexData.uv2s;
  26756. if (uv2s) {
  26757. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26758. }
  26759. // uv3s
  26760. var uv3s = parsedVertexData.uv3s;
  26761. if (uv3s) {
  26762. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26763. }
  26764. // uv4s
  26765. var uv4s = parsedVertexData.uv4s;
  26766. if (uv4s) {
  26767. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26768. }
  26769. // uv5s
  26770. var uv5s = parsedVertexData.uv5s;
  26771. if (uv5s) {
  26772. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26773. }
  26774. // uv6s
  26775. var uv6s = parsedVertexData.uv6s;
  26776. if (uv6s) {
  26777. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26778. }
  26779. // colors
  26780. var colors = parsedVertexData.colors;
  26781. if (colors) {
  26782. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26783. }
  26784. // matricesIndices
  26785. var matricesIndices = parsedVertexData.matricesIndices;
  26786. if (matricesIndices) {
  26787. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26788. }
  26789. // matricesWeights
  26790. var matricesWeights = parsedVertexData.matricesWeights;
  26791. if (matricesWeights) {
  26792. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26793. }
  26794. // indices
  26795. var indices = parsedVertexData.indices;
  26796. if (indices) {
  26797. vertexData.indices = indices;
  26798. }
  26799. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26800. };
  26801. return VertexData;
  26802. }());
  26803. BABYLON.VertexData = VertexData;
  26804. })(BABYLON || (BABYLON = {}));
  26805. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26806. var BABYLON;
  26807. (function (BABYLON) {
  26808. var Geometry = (function () {
  26809. function Geometry(id, scene, vertexData, updatable, mesh) {
  26810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26811. this._totalVertices = 0;
  26812. this._isDisposed = false;
  26813. this.id = id;
  26814. this._engine = scene.getEngine();
  26815. this._meshes = [];
  26816. this._scene = scene;
  26817. //Init vertex buffer cache
  26818. this._vertexBuffers = {};
  26819. this._indices = [];
  26820. // vertexData
  26821. if (vertexData) {
  26822. this.setAllVerticesData(vertexData, updatable);
  26823. }
  26824. else {
  26825. this._totalVertices = 0;
  26826. this._indices = [];
  26827. }
  26828. if (this._engine.getCaps().vertexArrayObject) {
  26829. this._vertexArrayObjects = {};
  26830. }
  26831. // applyToMesh
  26832. if (mesh) {
  26833. if (mesh.getClassName() === "LinesMesh") {
  26834. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26835. this.updateExtend();
  26836. }
  26837. this.applyToMesh(mesh);
  26838. mesh.computeWorldMatrix(true);
  26839. }
  26840. }
  26841. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26842. /**
  26843. * 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
  26844. * @returns The Bias Vector
  26845. */
  26846. get: function () {
  26847. return this._boundingBias;
  26848. },
  26849. set: function (value) {
  26850. if (this._boundingBias && this._boundingBias.equals(value)) {
  26851. return;
  26852. }
  26853. this._boundingBias = value.clone();
  26854. this.updateBoundingInfo(true, null);
  26855. },
  26856. enumerable: true,
  26857. configurable: true
  26858. });
  26859. Object.defineProperty(Geometry.prototype, "extend", {
  26860. get: function () {
  26861. return this._extend;
  26862. },
  26863. enumerable: true,
  26864. configurable: true
  26865. });
  26866. Geometry.prototype.getScene = function () {
  26867. return this._scene;
  26868. };
  26869. Geometry.prototype.getEngine = function () {
  26870. return this._engine;
  26871. };
  26872. Geometry.prototype.isReady = function () {
  26873. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26874. };
  26875. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26876. get: function () {
  26877. for (var index = 0; index < this._meshes.length; index++) {
  26878. if (!this._meshes[index].doNotSerialize) {
  26879. return false;
  26880. }
  26881. }
  26882. return true;
  26883. },
  26884. enumerable: true,
  26885. configurable: true
  26886. });
  26887. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26888. vertexData.applyToGeometry(this, updatable);
  26889. this.notifyUpdate();
  26890. };
  26891. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26892. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26893. this.setVerticesBuffer(buffer);
  26894. };
  26895. Geometry.prototype.removeVerticesData = function (kind) {
  26896. if (this._vertexBuffers[kind]) {
  26897. this._vertexBuffers[kind].dispose();
  26898. delete this._vertexBuffers[kind];
  26899. }
  26900. };
  26901. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26902. var kind = buffer.getKind();
  26903. if (this._vertexBuffers[kind]) {
  26904. this._vertexBuffers[kind].dispose();
  26905. }
  26906. this._vertexBuffers[kind] = buffer;
  26907. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26908. var data = buffer.getData();
  26909. var stride = buffer.getStrideSize();
  26910. this._totalVertices = data.length / stride;
  26911. this.updateExtend(data, stride);
  26912. this._resetPointsArrayCache();
  26913. var meshes = this._meshes;
  26914. var numOfMeshes = meshes.length;
  26915. for (var index = 0; index < numOfMeshes; index++) {
  26916. var mesh = meshes[index];
  26917. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26918. mesh._createGlobalSubMesh();
  26919. mesh.computeWorldMatrix(true);
  26920. }
  26921. }
  26922. this.notifyUpdate(kind);
  26923. if (this._vertexArrayObjects) {
  26924. this._disposeVertexArrayObjects();
  26925. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26926. }
  26927. };
  26928. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26929. var vertexBuffer = this.getVertexBuffer(kind);
  26930. if (!vertexBuffer) {
  26931. return;
  26932. }
  26933. vertexBuffer.updateDirectly(data, offset);
  26934. this.notifyUpdate(kind);
  26935. };
  26936. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26937. var vertexBuffer = this.getVertexBuffer(kind);
  26938. if (!vertexBuffer) {
  26939. return;
  26940. }
  26941. vertexBuffer.update(data);
  26942. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26943. var stride = vertexBuffer.getStrideSize();
  26944. this._totalVertices = data.length / stride;
  26945. this.updateBoundingInfo(updateExtends, data);
  26946. }
  26947. this.notifyUpdate(kind);
  26948. };
  26949. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26950. if (updateExtends) {
  26951. this.updateExtend(data);
  26952. }
  26953. var meshes = this._meshes;
  26954. var numOfMeshes = meshes.length;
  26955. this._resetPointsArrayCache();
  26956. for (var index = 0; index < numOfMeshes; index++) {
  26957. var mesh = meshes[index];
  26958. if (updateExtends) {
  26959. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26960. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26961. var subMesh = mesh.subMeshes[subIndex];
  26962. subMesh.refreshBoundingInfo();
  26963. }
  26964. }
  26965. }
  26966. };
  26967. Geometry.prototype._bind = function (effect, indexToBind) {
  26968. if (indexToBind === void 0) { indexToBind = undefined; }
  26969. if (indexToBind === undefined) {
  26970. indexToBind = this._indexBuffer;
  26971. }
  26972. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  26973. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  26974. return;
  26975. }
  26976. // Using VAO
  26977. if (!this._vertexArrayObjects[effect.key]) {
  26978. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  26979. }
  26980. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  26981. };
  26982. Geometry.prototype.getTotalVertices = function () {
  26983. if (!this.isReady()) {
  26984. return 0;
  26985. }
  26986. return this._totalVertices;
  26987. };
  26988. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26989. var vertexBuffer = this.getVertexBuffer(kind);
  26990. if (!vertexBuffer) {
  26991. return null;
  26992. }
  26993. var orig = vertexBuffer.getData();
  26994. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  26995. return orig;
  26996. }
  26997. else {
  26998. var len = orig.length;
  26999. var copy = [];
  27000. for (var i = 0; i < len; i++) {
  27001. copy.push(orig[i]);
  27002. }
  27003. return copy;
  27004. }
  27005. };
  27006. Geometry.prototype.getVertexBuffer = function (kind) {
  27007. if (!this.isReady()) {
  27008. return null;
  27009. }
  27010. return this._vertexBuffers[kind];
  27011. };
  27012. Geometry.prototype.getVertexBuffers = function () {
  27013. if (!this.isReady()) {
  27014. return null;
  27015. }
  27016. return this._vertexBuffers;
  27017. };
  27018. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27019. if (!this._vertexBuffers) {
  27020. if (this._delayInfo) {
  27021. return this._delayInfo.indexOf(kind) !== -1;
  27022. }
  27023. return false;
  27024. }
  27025. return this._vertexBuffers[kind] !== undefined;
  27026. };
  27027. Geometry.prototype.getVerticesDataKinds = function () {
  27028. var result = [];
  27029. var kind;
  27030. if (!this._vertexBuffers && this._delayInfo) {
  27031. for (kind in this._delayInfo) {
  27032. result.push(kind);
  27033. }
  27034. }
  27035. else {
  27036. for (kind in this._vertexBuffers) {
  27037. result.push(kind);
  27038. }
  27039. }
  27040. return result;
  27041. };
  27042. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27043. if (this._indexBuffer) {
  27044. this._engine._releaseBuffer(this._indexBuffer);
  27045. }
  27046. this._disposeVertexArrayObjects();
  27047. this._indices = indices;
  27048. if (this._meshes.length !== 0 && this._indices) {
  27049. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27050. }
  27051. if (totalVertices !== undefined) {
  27052. this._totalVertices = totalVertices;
  27053. }
  27054. var meshes = this._meshes;
  27055. var numOfMeshes = meshes.length;
  27056. for (var index = 0; index < numOfMeshes; index++) {
  27057. meshes[index]._createGlobalSubMesh();
  27058. }
  27059. this.notifyUpdate();
  27060. };
  27061. Geometry.prototype.getTotalIndices = function () {
  27062. if (!this.isReady()) {
  27063. return 0;
  27064. }
  27065. return this._indices.length;
  27066. };
  27067. Geometry.prototype.getIndices = function (copyWhenShared) {
  27068. if (!this.isReady()) {
  27069. return null;
  27070. }
  27071. var orig = this._indices;
  27072. if (!copyWhenShared || this._meshes.length === 1) {
  27073. return orig;
  27074. }
  27075. else {
  27076. var len = orig.length;
  27077. var copy = [];
  27078. for (var i = 0; i < len; i++) {
  27079. copy.push(orig[i]);
  27080. }
  27081. return copy;
  27082. }
  27083. };
  27084. Geometry.prototype.getIndexBuffer = function () {
  27085. if (!this.isReady()) {
  27086. return null;
  27087. }
  27088. return this._indexBuffer;
  27089. };
  27090. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27091. if (!effect || !this._vertexArrayObjects) {
  27092. return;
  27093. }
  27094. if (this._vertexArrayObjects[effect.key]) {
  27095. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27096. delete this._vertexArrayObjects[effect.key];
  27097. }
  27098. };
  27099. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27100. var meshes = this._meshes;
  27101. var index = meshes.indexOf(mesh);
  27102. if (index === -1) {
  27103. return;
  27104. }
  27105. meshes.splice(index, 1);
  27106. mesh._geometry = null;
  27107. if (meshes.length === 0 && shouldDispose) {
  27108. this.dispose();
  27109. }
  27110. };
  27111. Geometry.prototype.applyToMesh = function (mesh) {
  27112. if (mesh._geometry === this) {
  27113. return;
  27114. }
  27115. var previousGeometry = mesh._geometry;
  27116. if (previousGeometry) {
  27117. previousGeometry.releaseForMesh(mesh);
  27118. }
  27119. var meshes = this._meshes;
  27120. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27121. mesh._geometry = this;
  27122. this._scene.pushGeometry(this);
  27123. meshes.push(mesh);
  27124. if (this.isReady()) {
  27125. this._applyToMesh(mesh);
  27126. }
  27127. else {
  27128. mesh._boundingInfo = this._boundingInfo;
  27129. }
  27130. };
  27131. Geometry.prototype.updateExtend = function (data, stride) {
  27132. if (data === void 0) { data = null; }
  27133. if (!data) {
  27134. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27135. }
  27136. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27137. };
  27138. Geometry.prototype._applyToMesh = function (mesh) {
  27139. var numOfMeshes = this._meshes.length;
  27140. // vertexBuffers
  27141. for (var kind in this._vertexBuffers) {
  27142. if (numOfMeshes === 1) {
  27143. this._vertexBuffers[kind].create();
  27144. }
  27145. var buffer = this._vertexBuffers[kind].getBuffer();
  27146. if (buffer)
  27147. buffer.references = numOfMeshes;
  27148. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27149. if (!this._extend) {
  27150. this.updateExtend(this._vertexBuffers[kind].getData());
  27151. }
  27152. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27153. mesh._createGlobalSubMesh();
  27154. //bounding info was just created again, world matrix should be applied again.
  27155. mesh._updateBoundingInfo();
  27156. }
  27157. }
  27158. // indexBuffer
  27159. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27160. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27161. }
  27162. if (this._indexBuffer) {
  27163. this._indexBuffer.references = numOfMeshes;
  27164. }
  27165. };
  27166. Geometry.prototype.notifyUpdate = function (kind) {
  27167. if (this.onGeometryUpdated) {
  27168. this.onGeometryUpdated(this, kind);
  27169. }
  27170. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27171. var mesh = _a[_i];
  27172. mesh._markSubMeshesAsAttributesDirty();
  27173. }
  27174. };
  27175. Geometry.prototype.load = function (scene, onLoaded) {
  27176. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27177. return;
  27178. }
  27179. if (this.isReady()) {
  27180. if (onLoaded) {
  27181. onLoaded();
  27182. }
  27183. return;
  27184. }
  27185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27186. this._queueLoad(scene, onLoaded);
  27187. };
  27188. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27189. var _this = this;
  27190. scene._addPendingData(this);
  27191. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27192. _this._delayLoadingFunction(JSON.parse(data), _this);
  27193. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27194. _this._delayInfo = [];
  27195. scene._removePendingData(_this);
  27196. var meshes = _this._meshes;
  27197. var numOfMeshes = meshes.length;
  27198. for (var index = 0; index < numOfMeshes; index++) {
  27199. _this._applyToMesh(meshes[index]);
  27200. }
  27201. if (onLoaded) {
  27202. onLoaded();
  27203. }
  27204. }, function () { }, scene.database);
  27205. };
  27206. /**
  27207. * Invert the geometry to move from a right handed system to a left handed one.
  27208. */
  27209. Geometry.prototype.toLeftHanded = function () {
  27210. // Flip faces
  27211. var tIndices = this.getIndices(false);
  27212. if (tIndices != null && tIndices.length > 0) {
  27213. for (var i = 0; i < tIndices.length; i += 3) {
  27214. var tTemp = tIndices[i + 0];
  27215. tIndices[i + 0] = tIndices[i + 2];
  27216. tIndices[i + 2] = tTemp;
  27217. }
  27218. this.setIndices(tIndices);
  27219. }
  27220. // Negate position.z
  27221. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27222. if (tPositions != null && tPositions.length > 0) {
  27223. for (var i = 0; i < tPositions.length; i += 3) {
  27224. tPositions[i + 2] = -tPositions[i + 2];
  27225. }
  27226. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27227. }
  27228. // Negate normal.z
  27229. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27230. if (tNormals != null && tNormals.length > 0) {
  27231. for (var i = 0; i < tNormals.length; i += 3) {
  27232. tNormals[i + 2] = -tNormals[i + 2];
  27233. }
  27234. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27235. }
  27236. };
  27237. // Cache
  27238. Geometry.prototype._resetPointsArrayCache = function () {
  27239. this._positions = null;
  27240. };
  27241. Geometry.prototype._generatePointsArray = function () {
  27242. if (this._positions)
  27243. return true;
  27244. this._positions = [];
  27245. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27246. if (!data) {
  27247. return false;
  27248. }
  27249. for (var index = 0; index < data.length; index += 3) {
  27250. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27251. }
  27252. return true;
  27253. };
  27254. Geometry.prototype.isDisposed = function () {
  27255. return this._isDisposed;
  27256. };
  27257. Geometry.prototype._disposeVertexArrayObjects = function () {
  27258. if (this._vertexArrayObjects) {
  27259. for (var kind in this._vertexArrayObjects) {
  27260. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27261. }
  27262. this._vertexArrayObjects = {};
  27263. }
  27264. };
  27265. Geometry.prototype.dispose = function () {
  27266. var meshes = this._meshes;
  27267. var numOfMeshes = meshes.length;
  27268. var index;
  27269. for (index = 0; index < numOfMeshes; index++) {
  27270. this.releaseForMesh(meshes[index]);
  27271. }
  27272. this._meshes = [];
  27273. this._disposeVertexArrayObjects();
  27274. for (var kind in this._vertexBuffers) {
  27275. this._vertexBuffers[kind].dispose();
  27276. }
  27277. this._vertexBuffers = {};
  27278. this._totalVertices = 0;
  27279. if (this._indexBuffer) {
  27280. this._engine._releaseBuffer(this._indexBuffer);
  27281. }
  27282. this._indexBuffer = null;
  27283. this._indices = [];
  27284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27285. this.delayLoadingFile = null;
  27286. this._delayLoadingFunction = null;
  27287. this._delayInfo = [];
  27288. this._boundingInfo = null;
  27289. this._scene.removeGeometry(this);
  27290. this._isDisposed = true;
  27291. };
  27292. Geometry.prototype.copy = function (id) {
  27293. var vertexData = new BABYLON.VertexData();
  27294. vertexData.indices = [];
  27295. var indices = this.getIndices();
  27296. for (var index = 0; index < indices.length; index++) {
  27297. vertexData.indices.push(indices[index]);
  27298. }
  27299. var updatable = false;
  27300. var stopChecking = false;
  27301. var kind;
  27302. for (kind in this._vertexBuffers) {
  27303. // using slice() to make a copy of the array and not just reference it
  27304. var data = this.getVerticesData(kind);
  27305. if (data instanceof Float32Array) {
  27306. vertexData.set(new Float32Array(data), kind);
  27307. }
  27308. else {
  27309. vertexData.set(data.slice(0), kind);
  27310. }
  27311. if (!stopChecking) {
  27312. updatable = this.getVertexBuffer(kind).isUpdatable();
  27313. stopChecking = !updatable;
  27314. }
  27315. }
  27316. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27317. geometry.delayLoadState = this.delayLoadState;
  27318. geometry.delayLoadingFile = this.delayLoadingFile;
  27319. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27320. for (kind in this._delayInfo) {
  27321. geometry._delayInfo = geometry._delayInfo || [];
  27322. geometry._delayInfo.push(kind);
  27323. }
  27324. // Bounding info
  27325. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27326. return geometry;
  27327. };
  27328. Geometry.prototype.serialize = function () {
  27329. var serializationObject = {};
  27330. serializationObject.id = this.id;
  27331. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27332. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27333. }
  27334. return serializationObject;
  27335. };
  27336. Geometry.prototype.toNumberArray = function (origin) {
  27337. if (Array.isArray(origin)) {
  27338. return origin;
  27339. }
  27340. else {
  27341. return Array.prototype.slice.call(origin);
  27342. }
  27343. };
  27344. Geometry.prototype.serializeVerticeData = function () {
  27345. var serializationObject = this.serialize();
  27346. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27347. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27348. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27349. serializationObject.positions._updatable = true;
  27350. }
  27351. }
  27352. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27353. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27354. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27355. serializationObject.normals._updatable = true;
  27356. }
  27357. }
  27358. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27359. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27360. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27361. serializationObject.uvs._updatable = true;
  27362. }
  27363. }
  27364. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27365. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27366. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27367. serializationObject.uv2s._updatable = true;
  27368. }
  27369. }
  27370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27371. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27372. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27373. serializationObject.uv3s._updatable = true;
  27374. }
  27375. }
  27376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27377. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27378. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27379. serializationObject.uv4s._updatable = true;
  27380. }
  27381. }
  27382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27383. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27384. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27385. serializationObject.uv5s._updatable = true;
  27386. }
  27387. }
  27388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27389. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27390. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27391. serializationObject.uv6s._updatable = true;
  27392. }
  27393. }
  27394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27395. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27396. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27397. serializationObject.colors._updatable = true;
  27398. }
  27399. }
  27400. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27401. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27402. serializationObject.matricesIndices._isExpanded = true;
  27403. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27404. serializationObject.matricesIndices._updatable = true;
  27405. }
  27406. }
  27407. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27408. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27409. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27410. serializationObject.matricesWeights._updatable = true;
  27411. }
  27412. }
  27413. serializationObject.indices = this.toNumberArray(this.getIndices());
  27414. return serializationObject;
  27415. };
  27416. // Statics
  27417. Geometry.ExtractFromMesh = function (mesh, id) {
  27418. var geometry = mesh._geometry;
  27419. if (!geometry) {
  27420. return null;
  27421. }
  27422. return geometry.copy(id);
  27423. };
  27424. /**
  27425. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27426. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27427. * Be aware Math.random() could cause collisions, but:
  27428. * "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"
  27429. */
  27430. Geometry.RandomId = function () {
  27431. return BABYLON.Tools.RandomId();
  27432. };
  27433. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27434. var scene = mesh.getScene();
  27435. // Geometry
  27436. var geometryId = parsedGeometry.geometryId;
  27437. if (geometryId) {
  27438. var geometry = scene.getGeometryByID(geometryId);
  27439. if (geometry) {
  27440. geometry.applyToMesh(mesh);
  27441. }
  27442. }
  27443. else if (parsedGeometry instanceof ArrayBuffer) {
  27444. var binaryInfo = mesh._binaryInfo;
  27445. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27446. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27447. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27448. }
  27449. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27450. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27451. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27452. }
  27453. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27454. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27455. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27456. }
  27457. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27458. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27459. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27460. }
  27461. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27462. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27463. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27464. }
  27465. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27466. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27467. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27468. }
  27469. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27470. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27471. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27472. }
  27473. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27474. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27475. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27476. }
  27477. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27478. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27479. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27480. }
  27481. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27482. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27484. }
  27485. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27486. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27488. }
  27489. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27490. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27491. mesh.setIndices(indicesData);
  27492. }
  27493. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27494. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27495. mesh.subMeshes = [];
  27496. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27497. var materialIndex = subMeshesData[(i * 5) + 0];
  27498. var verticesStart = subMeshesData[(i * 5) + 1];
  27499. var verticesCount = subMeshesData[(i * 5) + 2];
  27500. var indexStart = subMeshesData[(i * 5) + 3];
  27501. var indexCount = subMeshesData[(i * 5) + 4];
  27502. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27503. }
  27504. }
  27505. }
  27506. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27507. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27508. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27509. if (parsedGeometry.uvs) {
  27510. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27511. }
  27512. if (parsedGeometry.uvs2) {
  27513. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27514. }
  27515. if (parsedGeometry.uvs3) {
  27516. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27517. }
  27518. if (parsedGeometry.uvs4) {
  27519. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27520. }
  27521. if (parsedGeometry.uvs5) {
  27522. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27523. }
  27524. if (parsedGeometry.uvs6) {
  27525. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27526. }
  27527. if (parsedGeometry.colors) {
  27528. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27529. }
  27530. if (parsedGeometry.matricesIndices) {
  27531. if (!parsedGeometry.matricesIndices._isExpanded) {
  27532. var floatIndices = [];
  27533. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27534. var matricesIndex = parsedGeometry.matricesIndices[i];
  27535. floatIndices.push(matricesIndex & 0x000000FF);
  27536. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27537. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27538. floatIndices.push(matricesIndex >> 24);
  27539. }
  27540. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27541. }
  27542. else {
  27543. delete parsedGeometry.matricesIndices._isExpanded;
  27544. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27545. }
  27546. }
  27547. if (parsedGeometry.matricesIndicesExtra) {
  27548. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27549. var floatIndices = [];
  27550. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27551. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27552. floatIndices.push(matricesIndex & 0x000000FF);
  27553. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27554. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27555. floatIndices.push(matricesIndex >> 24);
  27556. }
  27557. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27558. }
  27559. else {
  27560. delete parsedGeometry.matricesIndices._isExpanded;
  27561. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27562. }
  27563. }
  27564. if (parsedGeometry.matricesWeights) {
  27565. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27566. }
  27567. if (parsedGeometry.matricesWeightsExtra) {
  27568. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27569. }
  27570. mesh.setIndices(parsedGeometry.indices);
  27571. }
  27572. // SubMeshes
  27573. if (parsedGeometry.subMeshes) {
  27574. mesh.subMeshes = [];
  27575. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27576. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27577. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27578. }
  27579. }
  27580. // Flat shading
  27581. if (mesh._shouldGenerateFlatShading) {
  27582. mesh.convertToFlatShadedMesh();
  27583. delete mesh._shouldGenerateFlatShading;
  27584. }
  27585. // Update
  27586. mesh.computeWorldMatrix(true);
  27587. // Octree
  27588. if (scene['_selectionOctree']) {
  27589. scene['_selectionOctree'].addMesh(mesh);
  27590. }
  27591. };
  27592. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27593. if (scene.getGeometryByID(parsedVertexData.id)) {
  27594. return null; // null since geometry could be something else than a box...
  27595. }
  27596. var geometry = new Geometry(parsedVertexData.id, scene);
  27597. if (BABYLON.Tags) {
  27598. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27599. }
  27600. if (parsedVertexData.delayLoadingFile) {
  27601. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27602. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27603. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27604. geometry._delayInfo = [];
  27605. if (parsedVertexData.hasUVs) {
  27606. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27607. }
  27608. if (parsedVertexData.hasUVs2) {
  27609. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27610. }
  27611. if (parsedVertexData.hasUVs3) {
  27612. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27613. }
  27614. if (parsedVertexData.hasUVs4) {
  27615. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27616. }
  27617. if (parsedVertexData.hasUVs5) {
  27618. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27619. }
  27620. if (parsedVertexData.hasUVs6) {
  27621. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27622. }
  27623. if (parsedVertexData.hasColors) {
  27624. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27625. }
  27626. if (parsedVertexData.hasMatricesIndices) {
  27627. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27628. }
  27629. if (parsedVertexData.hasMatricesWeights) {
  27630. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27631. }
  27632. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27633. }
  27634. else {
  27635. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27636. }
  27637. scene.pushGeometry(geometry, true);
  27638. return geometry;
  27639. };
  27640. return Geometry;
  27641. }());
  27642. BABYLON.Geometry = Geometry;
  27643. /////// Primitives //////////////////////////////////////////////
  27644. (function (Geometry) {
  27645. var Primitives;
  27646. (function (Primitives) {
  27647. /// Abstract class
  27648. var _Primitive = (function (_super) {
  27649. __extends(_Primitive, _super);
  27650. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27651. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27652. _this._canBeRegenerated = _canBeRegenerated;
  27653. _this._beingRegenerated = true;
  27654. _this.regenerate();
  27655. _this._beingRegenerated = false;
  27656. return _this;
  27657. }
  27658. _Primitive.prototype.canBeRegenerated = function () {
  27659. return this._canBeRegenerated;
  27660. };
  27661. _Primitive.prototype.regenerate = function () {
  27662. if (!this._canBeRegenerated) {
  27663. return;
  27664. }
  27665. this._beingRegenerated = true;
  27666. this.setAllVerticesData(this._regenerateVertexData(), false);
  27667. this._beingRegenerated = false;
  27668. };
  27669. _Primitive.prototype.asNewGeometry = function (id) {
  27670. return _super.prototype.copy.call(this, id);
  27671. };
  27672. // overrides
  27673. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27674. if (!this._beingRegenerated) {
  27675. return;
  27676. }
  27677. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27678. };
  27679. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27680. if (!this._beingRegenerated) {
  27681. return;
  27682. }
  27683. _super.prototype.setVerticesData.call(this, kind, data, false);
  27684. };
  27685. // to override
  27686. // protected
  27687. _Primitive.prototype._regenerateVertexData = function () {
  27688. throw new Error("Abstract method");
  27689. };
  27690. _Primitive.prototype.copy = function (id) {
  27691. throw new Error("Must be overriden in sub-classes.");
  27692. };
  27693. _Primitive.prototype.serialize = function () {
  27694. var serializationObject = _super.prototype.serialize.call(this);
  27695. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27696. return serializationObject;
  27697. };
  27698. return _Primitive;
  27699. }(Geometry));
  27700. Primitives._Primitive = _Primitive;
  27701. var Ribbon = (function (_super) {
  27702. __extends(Ribbon, _super);
  27703. // Members
  27704. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27705. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27706. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27707. _this.pathArray = pathArray;
  27708. _this.closeArray = closeArray;
  27709. _this.closePath = closePath;
  27710. _this.offset = offset;
  27711. _this.side = side;
  27712. return _this;
  27713. }
  27714. Ribbon.prototype._regenerateVertexData = function () {
  27715. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27716. };
  27717. Ribbon.prototype.copy = function (id) {
  27718. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27719. };
  27720. return Ribbon;
  27721. }(_Primitive));
  27722. Primitives.Ribbon = Ribbon;
  27723. var Box = (function (_super) {
  27724. __extends(Box, _super);
  27725. // Members
  27726. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27727. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27728. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27729. _this.size = size;
  27730. _this.side = side;
  27731. return _this;
  27732. }
  27733. Box.prototype._regenerateVertexData = function () {
  27734. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27735. };
  27736. Box.prototype.copy = function (id) {
  27737. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27738. };
  27739. Box.prototype.serialize = function () {
  27740. var serializationObject = _super.prototype.serialize.call(this);
  27741. serializationObject.size = this.size;
  27742. return serializationObject;
  27743. };
  27744. Box.Parse = function (parsedBox, scene) {
  27745. if (scene.getGeometryByID(parsedBox.id)) {
  27746. return null; // null since geometry could be something else than a box...
  27747. }
  27748. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27749. if (BABYLON.Tags) {
  27750. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27751. }
  27752. scene.pushGeometry(box, true);
  27753. return box;
  27754. };
  27755. return Box;
  27756. }(_Primitive));
  27757. Primitives.Box = Box;
  27758. var Sphere = (function (_super) {
  27759. __extends(Sphere, _super);
  27760. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27763. _this.segments = segments;
  27764. _this.diameter = diameter;
  27765. _this.side = side;
  27766. return _this;
  27767. }
  27768. Sphere.prototype._regenerateVertexData = function () {
  27769. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27770. };
  27771. Sphere.prototype.copy = function (id) {
  27772. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27773. };
  27774. Sphere.prototype.serialize = function () {
  27775. var serializationObject = _super.prototype.serialize.call(this);
  27776. serializationObject.segments = this.segments;
  27777. serializationObject.diameter = this.diameter;
  27778. return serializationObject;
  27779. };
  27780. Sphere.Parse = function (parsedSphere, scene) {
  27781. if (scene.getGeometryByID(parsedSphere.id)) {
  27782. return null; // null since geometry could be something else than a sphere...
  27783. }
  27784. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27785. if (BABYLON.Tags) {
  27786. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27787. }
  27788. scene.pushGeometry(sphere, true);
  27789. return sphere;
  27790. };
  27791. return Sphere;
  27792. }(_Primitive));
  27793. Primitives.Sphere = Sphere;
  27794. var Disc = (function (_super) {
  27795. __extends(Disc, _super);
  27796. // Members
  27797. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27798. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27799. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27800. _this.radius = radius;
  27801. _this.tessellation = tessellation;
  27802. _this.side = side;
  27803. return _this;
  27804. }
  27805. Disc.prototype._regenerateVertexData = function () {
  27806. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27807. };
  27808. Disc.prototype.copy = function (id) {
  27809. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27810. };
  27811. return Disc;
  27812. }(_Primitive));
  27813. Primitives.Disc = Disc;
  27814. var Cylinder = (function (_super) {
  27815. __extends(Cylinder, _super);
  27816. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27817. if (subdivisions === void 0) { subdivisions = 1; }
  27818. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27819. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27820. _this.height = height;
  27821. _this.diameterTop = diameterTop;
  27822. _this.diameterBottom = diameterBottom;
  27823. _this.tessellation = tessellation;
  27824. _this.subdivisions = subdivisions;
  27825. _this.side = side;
  27826. return _this;
  27827. }
  27828. Cylinder.prototype._regenerateVertexData = function () {
  27829. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27830. };
  27831. Cylinder.prototype.copy = function (id) {
  27832. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27833. };
  27834. Cylinder.prototype.serialize = function () {
  27835. var serializationObject = _super.prototype.serialize.call(this);
  27836. serializationObject.height = this.height;
  27837. serializationObject.diameterTop = this.diameterTop;
  27838. serializationObject.diameterBottom = this.diameterBottom;
  27839. serializationObject.tessellation = this.tessellation;
  27840. return serializationObject;
  27841. };
  27842. Cylinder.Parse = function (parsedCylinder, scene) {
  27843. if (scene.getGeometryByID(parsedCylinder.id)) {
  27844. return null; // null since geometry could be something else than a cylinder...
  27845. }
  27846. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27847. if (BABYLON.Tags) {
  27848. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27849. }
  27850. scene.pushGeometry(cylinder, true);
  27851. return cylinder;
  27852. };
  27853. return Cylinder;
  27854. }(_Primitive));
  27855. Primitives.Cylinder = Cylinder;
  27856. var Torus = (function (_super) {
  27857. __extends(Torus, _super);
  27858. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27859. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27860. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27861. _this.diameter = diameter;
  27862. _this.thickness = thickness;
  27863. _this.tessellation = tessellation;
  27864. _this.side = side;
  27865. return _this;
  27866. }
  27867. Torus.prototype._regenerateVertexData = function () {
  27868. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27869. };
  27870. Torus.prototype.copy = function (id) {
  27871. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27872. };
  27873. Torus.prototype.serialize = function () {
  27874. var serializationObject = _super.prototype.serialize.call(this);
  27875. serializationObject.diameter = this.diameter;
  27876. serializationObject.thickness = this.thickness;
  27877. serializationObject.tessellation = this.tessellation;
  27878. return serializationObject;
  27879. };
  27880. Torus.Parse = function (parsedTorus, scene) {
  27881. if (scene.getGeometryByID(parsedTorus.id)) {
  27882. return null; // null since geometry could be something else than a torus...
  27883. }
  27884. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27885. if (BABYLON.Tags) {
  27886. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27887. }
  27888. scene.pushGeometry(torus, true);
  27889. return torus;
  27890. };
  27891. return Torus;
  27892. }(_Primitive));
  27893. Primitives.Torus = Torus;
  27894. var Ground = (function (_super) {
  27895. __extends(Ground, _super);
  27896. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27897. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27898. _this.width = width;
  27899. _this.height = height;
  27900. _this.subdivisions = subdivisions;
  27901. return _this;
  27902. }
  27903. Ground.prototype._regenerateVertexData = function () {
  27904. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27905. };
  27906. Ground.prototype.copy = function (id) {
  27907. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27908. };
  27909. Ground.prototype.serialize = function () {
  27910. var serializationObject = _super.prototype.serialize.call(this);
  27911. serializationObject.width = this.width;
  27912. serializationObject.height = this.height;
  27913. serializationObject.subdivisions = this.subdivisions;
  27914. return serializationObject;
  27915. };
  27916. Ground.Parse = function (parsedGround, scene) {
  27917. if (scene.getGeometryByID(parsedGround.id)) {
  27918. return null; // null since geometry could be something else than a ground...
  27919. }
  27920. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27921. if (BABYLON.Tags) {
  27922. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27923. }
  27924. scene.pushGeometry(ground, true);
  27925. return ground;
  27926. };
  27927. return Ground;
  27928. }(_Primitive));
  27929. Primitives.Ground = Ground;
  27930. var TiledGround = (function (_super) {
  27931. __extends(TiledGround, _super);
  27932. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27933. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27934. _this.xmin = xmin;
  27935. _this.zmin = zmin;
  27936. _this.xmax = xmax;
  27937. _this.zmax = zmax;
  27938. _this.subdivisions = subdivisions;
  27939. _this.precision = precision;
  27940. return _this;
  27941. }
  27942. TiledGround.prototype._regenerateVertexData = function () {
  27943. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27944. };
  27945. TiledGround.prototype.copy = function (id) {
  27946. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27947. };
  27948. return TiledGround;
  27949. }(_Primitive));
  27950. Primitives.TiledGround = TiledGround;
  27951. var Plane = (function (_super) {
  27952. __extends(Plane, _super);
  27953. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27955. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27956. _this.size = size;
  27957. _this.side = side;
  27958. return _this;
  27959. }
  27960. Plane.prototype._regenerateVertexData = function () {
  27961. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27962. };
  27963. Plane.prototype.copy = function (id) {
  27964. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27965. };
  27966. Plane.prototype.serialize = function () {
  27967. var serializationObject = _super.prototype.serialize.call(this);
  27968. serializationObject.size = this.size;
  27969. return serializationObject;
  27970. };
  27971. Plane.Parse = function (parsedPlane, scene) {
  27972. if (scene.getGeometryByID(parsedPlane.id)) {
  27973. return null; // null since geometry could be something else than a ground...
  27974. }
  27975. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27976. if (BABYLON.Tags) {
  27977. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27978. }
  27979. scene.pushGeometry(plane, true);
  27980. return plane;
  27981. };
  27982. return Plane;
  27983. }(_Primitive));
  27984. Primitives.Plane = Plane;
  27985. var TorusKnot = (function (_super) {
  27986. __extends(TorusKnot, _super);
  27987. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27988. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27989. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27990. _this.radius = radius;
  27991. _this.tube = tube;
  27992. _this.radialSegments = radialSegments;
  27993. _this.tubularSegments = tubularSegments;
  27994. _this.p = p;
  27995. _this.q = q;
  27996. _this.side = side;
  27997. return _this;
  27998. }
  27999. TorusKnot.prototype._regenerateVertexData = function () {
  28000. 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 });
  28001. };
  28002. TorusKnot.prototype.copy = function (id) {
  28003. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28004. };
  28005. TorusKnot.prototype.serialize = function () {
  28006. var serializationObject = _super.prototype.serialize.call(this);
  28007. serializationObject.radius = this.radius;
  28008. serializationObject.tube = this.tube;
  28009. serializationObject.radialSegments = this.radialSegments;
  28010. serializationObject.tubularSegments = this.tubularSegments;
  28011. serializationObject.p = this.p;
  28012. serializationObject.q = this.q;
  28013. return serializationObject;
  28014. };
  28015. ;
  28016. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28017. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28018. return null; // null since geometry could be something else than a ground...
  28019. }
  28020. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28021. if (BABYLON.Tags) {
  28022. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28023. }
  28024. scene.pushGeometry(torusKnot, true);
  28025. return torusKnot;
  28026. };
  28027. return TorusKnot;
  28028. }(_Primitive));
  28029. Primitives.TorusKnot = TorusKnot;
  28030. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28031. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28032. })(BABYLON || (BABYLON = {}));
  28033. //# sourceMappingURL=babylon.geometry.js.map
  28034. var BABYLON;
  28035. (function (BABYLON) {
  28036. var PostProcessManager = (function () {
  28037. function PostProcessManager(scene) {
  28038. this._vertexBuffers = {};
  28039. this._scene = scene;
  28040. }
  28041. PostProcessManager.prototype._prepareBuffers = function () {
  28042. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28043. return;
  28044. }
  28045. // VBO
  28046. var vertices = [];
  28047. vertices.push(1, 1);
  28048. vertices.push(-1, 1);
  28049. vertices.push(-1, -1);
  28050. vertices.push(1, -1);
  28051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28052. // Indices
  28053. var indices = [];
  28054. indices.push(0);
  28055. indices.push(1);
  28056. indices.push(2);
  28057. indices.push(0);
  28058. indices.push(2);
  28059. indices.push(3);
  28060. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28061. };
  28062. // Methods
  28063. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28064. var postProcesses = this._scene.activeCamera._postProcesses;
  28065. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28066. return false;
  28067. }
  28068. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28069. return true;
  28070. };
  28071. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28072. var engine = this._scene.getEngine();
  28073. for (var index = 0; index < postProcesses.length; index++) {
  28074. if (index < postProcesses.length - 1) {
  28075. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28076. }
  28077. else {
  28078. if (targetTexture) {
  28079. engine.bindFramebuffer(targetTexture);
  28080. }
  28081. else {
  28082. engine.restoreDefaultFramebuffer();
  28083. }
  28084. }
  28085. var pp = postProcesses[index];
  28086. var effect = pp.apply();
  28087. if (effect) {
  28088. pp.onBeforeRenderObservable.notifyObservers(effect);
  28089. // VBOs
  28090. this._prepareBuffers();
  28091. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28092. // Draw order
  28093. engine.draw(true, 0, 6);
  28094. pp.onAfterRenderObservable.notifyObservers(effect);
  28095. }
  28096. }
  28097. // Restore depth buffer
  28098. engine.setDepthBuffer(true);
  28099. engine.setDepthWrite(true);
  28100. };
  28101. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28102. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28103. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28104. return;
  28105. }
  28106. var engine = this._scene.getEngine();
  28107. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28108. if (index < len - 1) {
  28109. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28110. }
  28111. else {
  28112. if (targetTexture) {
  28113. engine.bindFramebuffer(targetTexture, faceIndex);
  28114. }
  28115. else {
  28116. engine.restoreDefaultFramebuffer();
  28117. }
  28118. }
  28119. if (doNotPresent) {
  28120. break;
  28121. }
  28122. var pp = postProcesses[index];
  28123. var effect = pp.apply();
  28124. if (effect) {
  28125. pp.onBeforeRenderObservable.notifyObservers(effect);
  28126. // VBOs
  28127. this._prepareBuffers();
  28128. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28129. // Draw order
  28130. engine.draw(true, 0, 6);
  28131. pp.onAfterRenderObservable.notifyObservers(effect);
  28132. }
  28133. }
  28134. // Restore states
  28135. engine.setDepthBuffer(true);
  28136. engine.setDepthWrite(true);
  28137. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28138. };
  28139. PostProcessManager.prototype.dispose = function () {
  28140. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28141. if (buffer) {
  28142. buffer.dispose();
  28143. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28144. }
  28145. if (this._indexBuffer) {
  28146. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28147. this._indexBuffer = null;
  28148. }
  28149. };
  28150. return PostProcessManager;
  28151. }());
  28152. BABYLON.PostProcessManager = PostProcessManager;
  28153. })(BABYLON || (BABYLON = {}));
  28154. //# sourceMappingURL=babylon.postProcessManager.js.map
  28155. var BABYLON;
  28156. (function (BABYLON) {
  28157. var StandardMaterialDefines = (function (_super) {
  28158. __extends(StandardMaterialDefines, _super);
  28159. function StandardMaterialDefines() {
  28160. var _this = _super.call(this) || this;
  28161. _this.DIFFUSE = false;
  28162. _this.AMBIENT = false;
  28163. _this.OPACITY = false;
  28164. _this.OPACITYRGB = false;
  28165. _this.REFLECTION = false;
  28166. _this.EMISSIVE = false;
  28167. _this.SPECULAR = false;
  28168. _this.BUMP = false;
  28169. _this.PARALLAX = false;
  28170. _this.PARALLAXOCCLUSION = false;
  28171. _this.SPECULAROVERALPHA = false;
  28172. _this.CLIPPLANE = false;
  28173. _this.ALPHATEST = false;
  28174. _this.ALPHAFROMDIFFUSE = false;
  28175. _this.POINTSIZE = false;
  28176. _this.FOG = false;
  28177. _this.SPECULARTERM = false;
  28178. _this.DIFFUSEFRESNEL = false;
  28179. _this.OPACITYFRESNEL = false;
  28180. _this.REFLECTIONFRESNEL = false;
  28181. _this.REFRACTIONFRESNEL = false;
  28182. _this.EMISSIVEFRESNEL = false;
  28183. _this.FRESNEL = false;
  28184. _this.NORMAL = false;
  28185. _this.UV1 = false;
  28186. _this.UV2 = false;
  28187. _this.VERTEXCOLOR = false;
  28188. _this.VERTEXALPHA = false;
  28189. _this.NUM_BONE_INFLUENCERS = 0;
  28190. _this.BonesPerMesh = 0;
  28191. _this.INSTANCES = false;
  28192. _this.GLOSSINESS = false;
  28193. _this.ROUGHNESS = false;
  28194. _this.EMISSIVEASILLUMINATION = false;
  28195. _this.LINKEMISSIVEWITHDIFFUSE = false;
  28196. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  28197. _this.LIGHTMAP = false;
  28198. _this.USELIGHTMAPASSHADOWMAP = false;
  28199. _this.REFLECTIONMAP_3D = false;
  28200. _this.REFLECTIONMAP_SPHERICAL = false;
  28201. _this.REFLECTIONMAP_PLANAR = false;
  28202. _this.REFLECTIONMAP_CUBIC = false;
  28203. _this.REFLECTIONMAP_PROJECTION = false;
  28204. _this.REFLECTIONMAP_SKYBOX = false;
  28205. _this.REFLECTIONMAP_EXPLICIT = false;
  28206. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28207. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28208. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28209. _this.INVERTCUBICMAP = false;
  28210. _this.LOGARITHMICDEPTH = false;
  28211. _this.REFRACTION = false;
  28212. _this.REFRACTIONMAP_3D = false;
  28213. _this.REFLECTIONOVERALPHA = false;
  28214. _this.INVERTNORMALMAPX = false;
  28215. _this.INVERTNORMALMAPY = false;
  28216. _this.TWOSIDEDLIGHTING = false;
  28217. _this.SHADOWFULLFLOAT = false;
  28218. _this.CAMERACOLORGRADING = false;
  28219. _this.CAMERACOLORCURVES = false;
  28220. _this.MORPHTARGETS = false;
  28221. _this.MORPHTARGETS_NORMAL = false;
  28222. _this.MORPHTARGETS_TANGENT = false;
  28223. _this.NUM_MORPH_INFLUENCERS = 0;
  28224. _this.USERIGHTHANDEDSYSTEM = false;
  28225. _this.rebuild();
  28226. return _this;
  28227. }
  28228. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  28229. var modes = [
  28230. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  28231. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  28232. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  28233. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  28234. ];
  28235. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  28236. var mode = modes_1[_i];
  28237. this[mode] = (mode === modeToEnable);
  28238. }
  28239. };
  28240. return StandardMaterialDefines;
  28241. }(BABYLON.MaterialDefines));
  28242. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  28243. var StandardMaterial = (function (_super) {
  28244. __extends(StandardMaterial, _super);
  28245. function StandardMaterial(name, scene) {
  28246. var _this = _super.call(this, name, scene) || this;
  28247. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28248. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  28249. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  28250. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28251. _this.specularPower = 64;
  28252. _this._useAlphaFromDiffuseTexture = false;
  28253. _this._useEmissiveAsIllumination = false;
  28254. _this._linkEmissiveWithDiffuse = false;
  28255. _this._useSpecularOverAlpha = false;
  28256. _this._useReflectionOverAlpha = false;
  28257. _this._disableLighting = false;
  28258. _this._useParallax = false;
  28259. _this._useParallaxOcclusion = false;
  28260. _this.parallaxScaleBias = 0.05;
  28261. _this._roughness = 0;
  28262. _this.indexOfRefraction = 0.98;
  28263. _this.invertRefractionY = true;
  28264. _this._useLightmapAsShadowmap = false;
  28265. _this._useReflectionFresnelFromSpecular = false;
  28266. _this._useGlossinessFromSpecularMapAlpha = false;
  28267. _this._maxSimultaneousLights = 4;
  28268. /**
  28269. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28270. */
  28271. _this._invertNormalMapX = false;
  28272. /**
  28273. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28274. */
  28275. _this._invertNormalMapY = false;
  28276. /**
  28277. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28278. */
  28279. _this._twoSidedLighting = false;
  28280. /**
  28281. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28282. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28283. * 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;
  28284. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28285. */
  28286. _this._cameraColorCurves = null;
  28287. _this._renderTargets = new BABYLON.SmartArray(16);
  28288. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28289. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28290. _this.getRenderTargetTextures = function () {
  28291. _this._renderTargets.reset();
  28292. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  28293. _this._renderTargets.push(_this._reflectionTexture);
  28294. }
  28295. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  28296. _this._renderTargets.push(_this._refractionTexture);
  28297. }
  28298. return _this._renderTargets;
  28299. };
  28300. return _this;
  28301. }
  28302. StandardMaterial.prototype.getClassName = function () {
  28303. return "StandardMaterial";
  28304. };
  28305. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  28306. get: function () {
  28307. return this._useLogarithmicDepth;
  28308. },
  28309. set: function (value) {
  28310. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28311. this._markAllSubMeshesAsMiscDirty();
  28312. },
  28313. enumerable: true,
  28314. configurable: true
  28315. });
  28316. StandardMaterial.prototype.needAlphaBlending = function () {
  28317. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  28318. };
  28319. StandardMaterial.prototype.needAlphaTesting = function () {
  28320. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  28321. };
  28322. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  28323. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  28324. };
  28325. StandardMaterial.prototype.getAlphaTestTexture = function () {
  28326. return this._diffuseTexture;
  28327. };
  28328. /**
  28329. * Child classes can use it to update shaders
  28330. */
  28331. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28332. if (this.isFrozen) {
  28333. if (this._wasPreviouslyReady && subMesh.effect) {
  28334. return true;
  28335. }
  28336. }
  28337. if (!subMesh._materialDefines) {
  28338. subMesh._materialDefines = new StandardMaterialDefines();
  28339. }
  28340. var scene = this.getScene();
  28341. var defines = subMesh._materialDefines;
  28342. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  28343. if (defines._renderId === scene.getRenderId()) {
  28344. return true;
  28345. }
  28346. }
  28347. var engine = scene.getEngine();
  28348. // Lights
  28349. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  28350. // Textures
  28351. if (defines._areTexturesDirty) {
  28352. defines._needUVs = false;
  28353. if (scene.texturesEnabled) {
  28354. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28355. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  28356. return false;
  28357. }
  28358. else {
  28359. defines._needUVs = true;
  28360. defines.DIFFUSE = true;
  28361. }
  28362. }
  28363. else {
  28364. defines.DIFFUSE = false;
  28365. }
  28366. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28367. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  28368. return false;
  28369. }
  28370. else {
  28371. defines._needUVs = true;
  28372. defines.AMBIENT = true;
  28373. }
  28374. }
  28375. else {
  28376. defines.AMBIENT = false;
  28377. }
  28378. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28379. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  28380. return false;
  28381. }
  28382. else {
  28383. defines._needUVs = true;
  28384. defines.OPACITY = true;
  28385. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  28386. }
  28387. }
  28388. else {
  28389. defines.OPACITY = false;
  28390. }
  28391. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28392. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  28393. return false;
  28394. }
  28395. else {
  28396. defines._needNormals = true;
  28397. defines.REFLECTION = true;
  28398. defines.ROUGHNESS = (this._roughness > 0);
  28399. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  28400. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  28401. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  28402. switch (this._reflectionTexture.coordinatesMode) {
  28403. case BABYLON.Texture.CUBIC_MODE:
  28404. case BABYLON.Texture.INVCUBIC_MODE:
  28405. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  28406. break;
  28407. case BABYLON.Texture.EXPLICIT_MODE:
  28408. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  28409. break;
  28410. case BABYLON.Texture.PLANAR_MODE:
  28411. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  28412. break;
  28413. case BABYLON.Texture.PROJECTION_MODE:
  28414. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  28415. break;
  28416. case BABYLON.Texture.SKYBOX_MODE:
  28417. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  28418. break;
  28419. case BABYLON.Texture.SPHERICAL_MODE:
  28420. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  28421. break;
  28422. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28423. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  28424. break;
  28425. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28426. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  28427. break;
  28428. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28429. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  28430. break;
  28431. }
  28432. }
  28433. }
  28434. else {
  28435. defines.REFLECTION = false;
  28436. }
  28437. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28438. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  28439. return false;
  28440. }
  28441. else {
  28442. defines._needUVs = true;
  28443. defines.EMISSIVE = true;
  28444. }
  28445. }
  28446. else {
  28447. defines.EMISSIVE = false;
  28448. }
  28449. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28450. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  28451. return false;
  28452. }
  28453. else {
  28454. defines._needUVs = true;
  28455. defines.LIGHTMAP = true;
  28456. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  28457. }
  28458. }
  28459. else {
  28460. defines.LIGHTMAP = false;
  28461. }
  28462. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28463. if (!this._specularTexture.isReadyOrNotBlocking()) {
  28464. return false;
  28465. }
  28466. else {
  28467. defines._needUVs = true;
  28468. defines.SPECULAR = true;
  28469. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  28470. }
  28471. }
  28472. else {
  28473. defines.SPECULAR = false;
  28474. }
  28475. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  28476. // Bump texure can not be none blocking.
  28477. if (!this._bumpTexture.isReady()) {
  28478. return false;
  28479. }
  28480. else {
  28481. defines._needUVs = true;
  28482. defines.BUMP = true;
  28483. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  28484. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  28485. defines.PARALLAX = this._useParallax;
  28486. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  28487. }
  28488. }
  28489. else {
  28490. defines.BUMP = false;
  28491. }
  28492. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28493. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  28494. return false;
  28495. }
  28496. else {
  28497. defines._needUVs = true;
  28498. defines.REFRACTION = true;
  28499. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  28500. }
  28501. }
  28502. else {
  28503. defines.REFRACTION = false;
  28504. }
  28505. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28506. // Camera Color Grading can not be none blocking.
  28507. if (!this._cameraColorGradingTexture.isReady()) {
  28508. return false;
  28509. }
  28510. else {
  28511. defines.CAMERACOLORGRADING = true;
  28512. }
  28513. }
  28514. else {
  28515. defines.CAMERACOLORGRADING = false;
  28516. }
  28517. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  28518. }
  28519. else {
  28520. defines.DIFFUSE = false;
  28521. defines.AMBIENT = false;
  28522. defines.OPACITY = false;
  28523. defines.REFLECTION = false;
  28524. defines.EMISSIVE = false;
  28525. defines.LIGHTMAP = false;
  28526. defines.BUMP = false;
  28527. defines.REFRACTION = false;
  28528. defines.CAMERACOLORGRADING = false;
  28529. }
  28530. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  28531. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  28532. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  28533. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  28534. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  28535. }
  28536. if (defines._areFresnelDirty) {
  28537. if (StandardMaterial.FresnelEnabled) {
  28538. // Fresnel
  28539. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  28540. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  28541. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  28542. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  28543. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  28544. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  28545. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  28546. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  28547. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  28548. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  28549. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  28550. defines._needNormals = true;
  28551. defines.FRESNEL = true;
  28552. }
  28553. }
  28554. else {
  28555. defines.FRESNEL = false;
  28556. }
  28557. }
  28558. // Misc.
  28559. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  28560. // Attribs
  28561. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  28562. // Values that need to be evaluated on every frame
  28563. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  28564. if (scene._mirroredCameraPosition && defines.BUMP) {
  28565. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  28566. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  28567. defines.markAsUnprocessed();
  28568. }
  28569. // Get correct effect
  28570. if (defines.isDirty) {
  28571. defines.markAsProcessed();
  28572. scene.resetCachedMaterial();
  28573. // Fallbacks
  28574. var fallbacks = new BABYLON.EffectFallbacks();
  28575. if (defines.REFLECTION) {
  28576. fallbacks.addFallback(0, "REFLECTION");
  28577. }
  28578. if (defines.SPECULAR) {
  28579. fallbacks.addFallback(0, "SPECULAR");
  28580. }
  28581. if (defines.BUMP) {
  28582. fallbacks.addFallback(0, "BUMP");
  28583. }
  28584. if (defines.PARALLAX) {
  28585. fallbacks.addFallback(1, "PARALLAX");
  28586. }
  28587. if (defines.PARALLAXOCCLUSION) {
  28588. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  28589. }
  28590. if (defines.SPECULAROVERALPHA) {
  28591. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  28592. }
  28593. if (defines.FOG) {
  28594. fallbacks.addFallback(1, "FOG");
  28595. }
  28596. if (defines.POINTSIZE) {
  28597. fallbacks.addFallback(0, "POINTSIZE");
  28598. }
  28599. if (defines.LOGARITHMICDEPTH) {
  28600. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  28601. }
  28602. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  28603. if (defines.SPECULARTERM) {
  28604. fallbacks.addFallback(0, "SPECULARTERM");
  28605. }
  28606. if (defines.DIFFUSEFRESNEL) {
  28607. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  28608. }
  28609. if (defines.OPACITYFRESNEL) {
  28610. fallbacks.addFallback(2, "OPACITYFRESNEL");
  28611. }
  28612. if (defines.REFLECTIONFRESNEL) {
  28613. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  28614. }
  28615. if (defines.EMISSIVEFRESNEL) {
  28616. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  28617. }
  28618. if (defines.FRESNEL) {
  28619. fallbacks.addFallback(4, "FRESNEL");
  28620. }
  28621. //Attributes
  28622. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28623. if (defines.NORMAL) {
  28624. attribs.push(BABYLON.VertexBuffer.NormalKind);
  28625. }
  28626. if (defines.UV1) {
  28627. attribs.push(BABYLON.VertexBuffer.UVKind);
  28628. }
  28629. if (defines.UV2) {
  28630. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28631. }
  28632. if (defines.VERTEXCOLOR) {
  28633. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28634. }
  28635. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  28636. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  28637. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  28638. var shaderName = "default";
  28639. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  28640. "vFogInfos", "vFogColor", "pointSize",
  28641. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  28642. "mBones",
  28643. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  28644. "depthValues",
  28645. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  28646. "logarithmicDepthConstant"
  28647. ];
  28648. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  28649. var uniformBuffers = ["Material", "Scene"];
  28650. if (defines.CAMERACOLORCURVES) {
  28651. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  28652. }
  28653. if (defines.CAMERACOLORGRADING) {
  28654. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  28655. }
  28656. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  28657. uniformsNames: uniforms,
  28658. uniformBuffersNames: uniformBuffers,
  28659. samplers: samplers,
  28660. defines: defines,
  28661. maxSimultaneousLights: this._maxSimultaneousLights
  28662. });
  28663. if (this.customShaderNameResolve) {
  28664. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  28665. }
  28666. var join = defines.toString();
  28667. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  28668. attributes: attribs,
  28669. uniformsNames: uniforms,
  28670. uniformBuffersNames: uniformBuffers,
  28671. samplers: samplers,
  28672. defines: join,
  28673. fallbacks: fallbacks,
  28674. onCompiled: this.onCompiled,
  28675. onError: this.onError,
  28676. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  28677. }, engine), defines);
  28678. this.buildUniformLayout();
  28679. }
  28680. if (!subMesh.effect.isReady()) {
  28681. return false;
  28682. }
  28683. defines._renderId = scene.getRenderId();
  28684. this._wasPreviouslyReady = true;
  28685. return true;
  28686. };
  28687. StandardMaterial.prototype.buildUniformLayout = function () {
  28688. // Order is important !
  28689. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  28690. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  28691. this._uniformBuffer.addUniform("opacityParts", 4);
  28692. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  28693. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  28694. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  28695. this._uniformBuffer.addUniform("refractionRightColor", 4);
  28696. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  28697. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  28698. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  28699. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  28700. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  28701. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  28702. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  28703. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  28704. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  28705. this._uniformBuffer.addUniform("vBumpInfos", 3);
  28706. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  28707. this._uniformBuffer.addUniform("ambientMatrix", 16);
  28708. this._uniformBuffer.addUniform("opacityMatrix", 16);
  28709. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  28710. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  28711. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  28712. this._uniformBuffer.addUniform("specularMatrix", 16);
  28713. this._uniformBuffer.addUniform("bumpMatrix", 16);
  28714. this._uniformBuffer.addUniform("refractionMatrix", 16);
  28715. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  28716. this._uniformBuffer.addUniform("vSpecularColor", 4);
  28717. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  28718. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  28719. this._uniformBuffer.addUniform("pointSize", 1);
  28720. this._uniformBuffer.create();
  28721. };
  28722. StandardMaterial.prototype.unbind = function () {
  28723. if (this._activeEffect) {
  28724. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  28725. this._activeEffect.setTexture("reflection2DSampler", null);
  28726. }
  28727. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  28728. this._activeEffect.setTexture("refraction2DSampler", null);
  28729. }
  28730. }
  28731. _super.prototype.unbind.call(this);
  28732. };
  28733. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28734. var scene = this.getScene();
  28735. var defines = subMesh._materialDefines;
  28736. if (!defines) {
  28737. return;
  28738. }
  28739. var effect = subMesh.effect;
  28740. this._activeEffect = effect;
  28741. // Matrices
  28742. this.bindOnlyWorldMatrix(world);
  28743. // Bones
  28744. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  28745. if (this._mustRebind(scene, effect, mesh.visibility)) {
  28746. this._uniformBuffer.bindToEffect(effect, "Material");
  28747. this.bindViewProjection(effect);
  28748. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  28749. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  28750. // Fresnel
  28751. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  28752. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  28753. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  28754. }
  28755. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28756. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  28757. }
  28758. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  28759. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  28760. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  28761. }
  28762. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  28763. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  28764. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  28765. }
  28766. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28767. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  28768. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  28769. }
  28770. }
  28771. // Textures
  28772. if (scene.texturesEnabled) {
  28773. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28774. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  28775. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  28776. }
  28777. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28778. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  28779. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  28780. }
  28781. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28782. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  28783. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  28784. }
  28785. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28786. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  28787. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  28788. }
  28789. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28790. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  28791. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  28792. }
  28793. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28794. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  28795. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  28796. }
  28797. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28798. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  28799. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  28800. }
  28801. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28802. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  28803. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  28804. }
  28805. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28806. var depth = 1.0;
  28807. if (!this._refractionTexture.isCube) {
  28808. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  28809. if (this._refractionTexture.depth) {
  28810. depth = this._refractionTexture.depth;
  28811. }
  28812. }
  28813. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  28814. }
  28815. }
  28816. // Point size
  28817. if (this.pointsCloud) {
  28818. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  28819. }
  28820. if (defines.SPECULARTERM) {
  28821. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  28822. }
  28823. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  28824. // Diffuse
  28825. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  28826. }
  28827. // Textures
  28828. if (scene.texturesEnabled) {
  28829. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28830. effect.setTexture("diffuseSampler", this._diffuseTexture);
  28831. }
  28832. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28833. effect.setTexture("ambientSampler", this._ambientTexture);
  28834. }
  28835. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28836. effect.setTexture("opacitySampler", this._opacityTexture);
  28837. }
  28838. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28839. if (this._reflectionTexture.isCube) {
  28840. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  28841. }
  28842. else {
  28843. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  28844. }
  28845. }
  28846. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28847. effect.setTexture("emissiveSampler", this._emissiveTexture);
  28848. }
  28849. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28850. effect.setTexture("lightmapSampler", this._lightmapTexture);
  28851. }
  28852. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28853. effect.setTexture("specularSampler", this._specularTexture);
  28854. }
  28855. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28856. effect.setTexture("bumpSampler", this._bumpTexture);
  28857. }
  28858. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28859. var depth = 1.0;
  28860. if (this._refractionTexture.isCube) {
  28861. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  28862. }
  28863. else {
  28864. effect.setTexture("refraction2DSampler", this._refractionTexture);
  28865. }
  28866. }
  28867. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28868. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  28869. }
  28870. }
  28871. // Clip plane
  28872. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  28873. // Colors
  28874. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  28875. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  28876. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  28877. }
  28878. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  28879. // Lights
  28880. if (scene.lightsEnabled && !this._disableLighting) {
  28881. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  28882. }
  28883. // View
  28884. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  28885. this.bindView(effect);
  28886. }
  28887. // Fog
  28888. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  28889. // Morph targets
  28890. if (defines.NUM_MORPH_INFLUENCERS) {
  28891. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  28892. }
  28893. // Log. depth
  28894. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  28895. // Color Curves
  28896. if (this._cameraColorCurves) {
  28897. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  28898. }
  28899. }
  28900. this._uniformBuffer.update();
  28901. this._afterBind(mesh, this._activeEffect);
  28902. };
  28903. StandardMaterial.prototype.getAnimatables = function () {
  28904. var results = [];
  28905. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  28906. results.push(this._diffuseTexture);
  28907. }
  28908. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  28909. results.push(this._ambientTexture);
  28910. }
  28911. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  28912. results.push(this._opacityTexture);
  28913. }
  28914. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  28915. results.push(this._reflectionTexture);
  28916. }
  28917. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  28918. results.push(this._emissiveTexture);
  28919. }
  28920. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  28921. results.push(this._specularTexture);
  28922. }
  28923. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  28924. results.push(this._bumpTexture);
  28925. }
  28926. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  28927. results.push(this._lightmapTexture);
  28928. }
  28929. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  28930. results.push(this._refractionTexture);
  28931. }
  28932. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  28933. results.push(this._cameraColorGradingTexture);
  28934. }
  28935. return results;
  28936. };
  28937. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28938. if (forceDisposeTextures) {
  28939. if (this._diffuseTexture) {
  28940. this._diffuseTexture.dispose();
  28941. }
  28942. if (this._ambientTexture) {
  28943. this._ambientTexture.dispose();
  28944. }
  28945. if (this._opacityTexture) {
  28946. this._opacityTexture.dispose();
  28947. }
  28948. if (this._reflectionTexture) {
  28949. this._reflectionTexture.dispose();
  28950. }
  28951. if (this._emissiveTexture) {
  28952. this._emissiveTexture.dispose();
  28953. }
  28954. if (this._specularTexture) {
  28955. this._specularTexture.dispose();
  28956. }
  28957. if (this._bumpTexture) {
  28958. this._bumpTexture.dispose();
  28959. }
  28960. if (this._lightmapTexture) {
  28961. this._lightmapTexture.dispose();
  28962. }
  28963. if (this._refractionTexture) {
  28964. this._refractionTexture.dispose();
  28965. }
  28966. if (this._cameraColorGradingTexture) {
  28967. this._cameraColorGradingTexture.dispose();
  28968. }
  28969. }
  28970. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28971. };
  28972. StandardMaterial.prototype.clone = function (name) {
  28973. var _this = this;
  28974. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  28975. result.name = name;
  28976. result.id = name;
  28977. return result;
  28978. };
  28979. StandardMaterial.prototype.serialize = function () {
  28980. return BABYLON.SerializationHelper.Serialize(this);
  28981. };
  28982. // Statics
  28983. StandardMaterial.Parse = function (source, scene, rootUrl) {
  28984. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  28985. };
  28986. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  28987. get: function () {
  28988. return StandardMaterial._DiffuseTextureEnabled;
  28989. },
  28990. set: function (value) {
  28991. if (StandardMaterial._DiffuseTextureEnabled === value) {
  28992. return;
  28993. }
  28994. StandardMaterial._DiffuseTextureEnabled = value;
  28995. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28996. },
  28997. enumerable: true,
  28998. configurable: true
  28999. });
  29000. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  29001. get: function () {
  29002. return StandardMaterial._AmbientTextureEnabled;
  29003. },
  29004. set: function (value) {
  29005. if (StandardMaterial._AmbientTextureEnabled === value) {
  29006. return;
  29007. }
  29008. StandardMaterial._AmbientTextureEnabled = value;
  29009. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29010. },
  29011. enumerable: true,
  29012. configurable: true
  29013. });
  29014. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  29015. get: function () {
  29016. return StandardMaterial._OpacityTextureEnabled;
  29017. },
  29018. set: function (value) {
  29019. if (StandardMaterial._OpacityTextureEnabled === value) {
  29020. return;
  29021. }
  29022. StandardMaterial._OpacityTextureEnabled = value;
  29023. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29024. },
  29025. enumerable: true,
  29026. configurable: true
  29027. });
  29028. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  29029. get: function () {
  29030. return StandardMaterial._ReflectionTextureEnabled;
  29031. },
  29032. set: function (value) {
  29033. if (StandardMaterial._ReflectionTextureEnabled === value) {
  29034. return;
  29035. }
  29036. StandardMaterial._ReflectionTextureEnabled = value;
  29037. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29038. },
  29039. enumerable: true,
  29040. configurable: true
  29041. });
  29042. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  29043. get: function () {
  29044. return StandardMaterial._EmissiveTextureEnabled;
  29045. },
  29046. set: function (value) {
  29047. if (StandardMaterial._EmissiveTextureEnabled === value) {
  29048. return;
  29049. }
  29050. StandardMaterial._EmissiveTextureEnabled = value;
  29051. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29052. },
  29053. enumerable: true,
  29054. configurable: true
  29055. });
  29056. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  29057. get: function () {
  29058. return StandardMaterial._SpecularTextureEnabled;
  29059. },
  29060. set: function (value) {
  29061. if (StandardMaterial._SpecularTextureEnabled === value) {
  29062. return;
  29063. }
  29064. StandardMaterial._SpecularTextureEnabled = value;
  29065. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29066. },
  29067. enumerable: true,
  29068. configurable: true
  29069. });
  29070. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  29071. get: function () {
  29072. return StandardMaterial._BumpTextureEnabled;
  29073. },
  29074. set: function (value) {
  29075. if (StandardMaterial._BumpTextureEnabled === value) {
  29076. return;
  29077. }
  29078. StandardMaterial._BumpTextureEnabled = value;
  29079. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29080. },
  29081. enumerable: true,
  29082. configurable: true
  29083. });
  29084. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  29085. get: function () {
  29086. return StandardMaterial._LightmapTextureEnabled;
  29087. },
  29088. set: function (value) {
  29089. if (StandardMaterial._LightmapTextureEnabled === value) {
  29090. return;
  29091. }
  29092. StandardMaterial._LightmapTextureEnabled = value;
  29093. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29094. },
  29095. enumerable: true,
  29096. configurable: true
  29097. });
  29098. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  29099. get: function () {
  29100. return StandardMaterial._RefractionTextureEnabled;
  29101. },
  29102. set: function (value) {
  29103. if (StandardMaterial._RefractionTextureEnabled === value) {
  29104. return;
  29105. }
  29106. StandardMaterial._RefractionTextureEnabled = value;
  29107. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29108. },
  29109. enumerable: true,
  29110. configurable: true
  29111. });
  29112. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  29113. get: function () {
  29114. return StandardMaterial._ColorGradingTextureEnabled;
  29115. },
  29116. set: function (value) {
  29117. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  29118. return;
  29119. }
  29120. StandardMaterial._ColorGradingTextureEnabled = value;
  29121. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29122. },
  29123. enumerable: true,
  29124. configurable: true
  29125. });
  29126. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  29127. get: function () {
  29128. return StandardMaterial._FresnelEnabled;
  29129. },
  29130. set: function (value) {
  29131. if (StandardMaterial._FresnelEnabled === value) {
  29132. return;
  29133. }
  29134. StandardMaterial._FresnelEnabled = value;
  29135. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  29136. },
  29137. enumerable: true,
  29138. configurable: true
  29139. });
  29140. return StandardMaterial;
  29141. }(BABYLON.PushMaterial));
  29142. // Flags used to enable or disable a type of texture for all Standard Materials
  29143. StandardMaterial._DiffuseTextureEnabled = true;
  29144. StandardMaterial._AmbientTextureEnabled = true;
  29145. StandardMaterial._OpacityTextureEnabled = true;
  29146. StandardMaterial._ReflectionTextureEnabled = true;
  29147. StandardMaterial._EmissiveTextureEnabled = true;
  29148. StandardMaterial._SpecularTextureEnabled = true;
  29149. StandardMaterial._BumpTextureEnabled = true;
  29150. StandardMaterial._LightmapTextureEnabled = true;
  29151. StandardMaterial._RefractionTextureEnabled = true;
  29152. StandardMaterial._ColorGradingTextureEnabled = true;
  29153. StandardMaterial._FresnelEnabled = true;
  29154. __decorate([
  29155. BABYLON.serializeAsTexture("diffuseTexture")
  29156. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  29157. __decorate([
  29158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29159. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29160. __decorate([
  29161. BABYLON.serializeAsTexture("ambientTexture")
  29162. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  29163. __decorate([
  29164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29165. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29166. __decorate([
  29167. BABYLON.serializeAsTexture("opacityTexture")
  29168. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  29169. __decorate([
  29170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29171. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29172. __decorate([
  29173. BABYLON.serializeAsTexture("reflectionTexture")
  29174. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  29175. __decorate([
  29176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29177. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29178. __decorate([
  29179. BABYLON.serializeAsTexture("emissiveTexture")
  29180. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  29181. __decorate([
  29182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29183. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29184. __decorate([
  29185. BABYLON.serializeAsTexture("specularTexture")
  29186. ], StandardMaterial.prototype, "_specularTexture", void 0);
  29187. __decorate([
  29188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29189. ], StandardMaterial.prototype, "specularTexture", void 0);
  29190. __decorate([
  29191. BABYLON.serializeAsTexture("bumpTexture")
  29192. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  29193. __decorate([
  29194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29195. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29196. __decorate([
  29197. BABYLON.serializeAsTexture("lightmapTexture")
  29198. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  29199. __decorate([
  29200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29201. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29202. __decorate([
  29203. BABYLON.serializeAsTexture("refractionTexture")
  29204. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  29205. __decorate([
  29206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29207. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29208. __decorate([
  29209. BABYLON.serializeAsColor3("ambient")
  29210. ], StandardMaterial.prototype, "ambientColor", void 0);
  29211. __decorate([
  29212. BABYLON.serializeAsColor3("diffuse")
  29213. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29214. __decorate([
  29215. BABYLON.serializeAsColor3("specular")
  29216. ], StandardMaterial.prototype, "specularColor", void 0);
  29217. __decorate([
  29218. BABYLON.serializeAsColor3("emissive")
  29219. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29220. __decorate([
  29221. BABYLON.serialize()
  29222. ], StandardMaterial.prototype, "specularPower", void 0);
  29223. __decorate([
  29224. BABYLON.serialize("useAlphaFromDiffuseTexture")
  29225. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  29226. __decorate([
  29227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29228. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29229. __decorate([
  29230. BABYLON.serialize("useEmissiveAsIllumination")
  29231. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  29232. __decorate([
  29233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29234. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29235. __decorate([
  29236. BABYLON.serialize("linkEmissiveWithDiffuse")
  29237. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  29238. __decorate([
  29239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29240. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29241. __decorate([
  29242. BABYLON.serialize("useSpecularOverAlpha")
  29243. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  29244. __decorate([
  29245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29246. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29247. __decorate([
  29248. BABYLON.serialize("useReflectionOverAlpha")
  29249. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  29250. __decorate([
  29251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29252. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29253. __decorate([
  29254. BABYLON.serialize("disableLighting")
  29255. ], StandardMaterial.prototype, "_disableLighting", void 0);
  29256. __decorate([
  29257. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29258. ], StandardMaterial.prototype, "disableLighting", void 0);
  29259. __decorate([
  29260. BABYLON.serialize("useParallax")
  29261. ], StandardMaterial.prototype, "_useParallax", void 0);
  29262. __decorate([
  29263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29264. ], StandardMaterial.prototype, "useParallax", void 0);
  29265. __decorate([
  29266. BABYLON.serialize("useParallaxOcclusion")
  29267. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  29268. __decorate([
  29269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29270. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29271. __decorate([
  29272. BABYLON.serialize()
  29273. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29274. __decorate([
  29275. BABYLON.serialize("roughness")
  29276. ], StandardMaterial.prototype, "_roughness", void 0);
  29277. __decorate([
  29278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29279. ], StandardMaterial.prototype, "roughness", void 0);
  29280. __decorate([
  29281. BABYLON.serialize()
  29282. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29283. __decorate([
  29284. BABYLON.serialize()
  29285. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29286. __decorate([
  29287. BABYLON.serialize("useLightmapAsShadowmap")
  29288. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  29289. __decorate([
  29290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29291. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29292. __decorate([
  29293. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  29294. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  29295. __decorate([
  29296. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29297. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29298. __decorate([
  29299. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  29300. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  29301. __decorate([
  29302. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29303. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29304. __decorate([
  29305. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  29306. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  29307. __decorate([
  29308. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29309. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29310. __decorate([
  29311. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  29312. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  29313. __decorate([
  29314. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29315. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29316. __decorate([
  29317. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  29318. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  29319. __decorate([
  29320. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29321. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29322. __decorate([
  29323. BABYLON.serialize("useReflectionFresnelFromSpecular")
  29324. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  29325. __decorate([
  29326. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29327. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29328. __decorate([
  29329. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  29330. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  29331. __decorate([
  29332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29333. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29334. __decorate([
  29335. BABYLON.serialize("maxSimultaneousLights")
  29336. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  29337. __decorate([
  29338. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29339. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29340. __decorate([
  29341. BABYLON.serialize("invertNormalMapX")
  29342. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  29343. __decorate([
  29344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29345. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29346. __decorate([
  29347. BABYLON.serialize("invertNormalMapY")
  29348. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  29349. __decorate([
  29350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29351. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29352. __decorate([
  29353. BABYLON.serialize("twoSidedLighting")
  29354. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  29355. __decorate([
  29356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29357. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  29358. __decorate([
  29359. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  29360. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  29361. __decorate([
  29362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29363. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  29364. __decorate([
  29365. BABYLON.serializeAsColorCurves("cameraColorCurves")
  29366. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  29367. __decorate([
  29368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29369. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  29370. __decorate([
  29371. BABYLON.serialize()
  29372. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29373. BABYLON.StandardMaterial = StandardMaterial;
  29374. })(BABYLON || (BABYLON = {}));
  29375. //# sourceMappingURL=babylon.standardMaterial.js.map
  29376. var BABYLON;
  29377. (function (BABYLON) {
  29378. var PBRMaterialDefines = (function (_super) {
  29379. __extends(PBRMaterialDefines, _super);
  29380. function PBRMaterialDefines() {
  29381. var _this = _super.call(this) || this;
  29382. _this.PBR = true;
  29383. _this.ALBEDO = false;
  29384. _this.AMBIENT = false;
  29385. _this.AMBIENTINGRAYSCALE = false;
  29386. _this.OPACITY = false;
  29387. _this.OPACITYRGB = false;
  29388. _this.REFLECTION = false;
  29389. _this.EMISSIVE = false;
  29390. _this.REFLECTIVITY = false;
  29391. _this.BUMP = false;
  29392. _this.PARALLAX = false;
  29393. _this.PARALLAXOCCLUSION = false;
  29394. _this.SPECULAROVERALPHA = false;
  29395. _this.CLIPPLANE = false;
  29396. _this.ALPHATEST = false;
  29397. _this.ALPHAFROMALBEDO = false;
  29398. _this.POINTSIZE = false;
  29399. _this.FOG = false;
  29400. _this.SPECULARTERM = false;
  29401. _this.OPACITYFRESNEL = false;
  29402. _this.EMISSIVEFRESNEL = false;
  29403. _this.FRESNEL = false;
  29404. _this.NORMAL = false;
  29405. _this.TANGENT = false;
  29406. _this.UV1 = false;
  29407. _this.UV2 = false;
  29408. _this.VERTEXCOLOR = false;
  29409. _this.VERTEXALPHA = false;
  29410. _this.NUM_BONE_INFLUENCERS = 0;
  29411. _this.BonesPerMesh = 0;
  29412. _this.INSTANCES = false;
  29413. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  29414. _this.MICROSURFACEAUTOMATIC = false;
  29415. _this.EMISSIVEASILLUMINATION = false;
  29416. _this.LIGHTMAP = false;
  29417. _this.USELIGHTMAPASSHADOWMAP = false;
  29418. _this.REFLECTIONMAP_3D = false;
  29419. _this.REFLECTIONMAP_SPHERICAL = false;
  29420. _this.REFLECTIONMAP_PLANAR = false;
  29421. _this.REFLECTIONMAP_CUBIC = false;
  29422. _this.REFLECTIONMAP_PROJECTION = false;
  29423. _this.REFLECTIONMAP_SKYBOX = false;
  29424. _this.REFLECTIONMAP_EXPLICIT = false;
  29425. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29426. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29427. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29428. _this.INVERTCUBICMAP = false;
  29429. _this.LOGARITHMICDEPTH = false;
  29430. _this.CAMERATONEMAP = false;
  29431. _this.CAMERACONTRAST = false;
  29432. _this.CAMERACOLORGRADING = false;
  29433. _this.CAMERACOLORCURVES = false;
  29434. _this.USESPHERICALFROMREFLECTIONMAP = false;
  29435. _this.REFRACTION = false;
  29436. _this.REFRACTIONMAP_3D = false;
  29437. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  29438. _this.REFRACTIONMAPINLINEARSPACE = false;
  29439. _this.LODBASEDMICROSFURACE = false;
  29440. _this.USEPHYSICALLIGHTFALLOFF = false;
  29441. _this.RADIANCEOVERALPHA = false;
  29442. _this.USEPMREMREFLECTION = false;
  29443. _this.USEPMREMREFRACTION = false;
  29444. _this.INVERTNORMALMAPX = false;
  29445. _this.INVERTNORMALMAPY = false;
  29446. _this.TWOSIDEDLIGHTING = false;
  29447. _this.SHADOWFULLFLOAT = false;
  29448. _this.NORMALXYSCALE = true;
  29449. _this.USERIGHTHANDEDSYSTEM = false;
  29450. _this.METALLICWORKFLOW = false;
  29451. _this.METALLICMAP = false;
  29452. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  29453. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  29454. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  29455. _this.AOSTOREINMETALMAPRED = false;
  29456. _this.MICROSURFACEMAP = false;
  29457. _this.MORPHTARGETS = false;
  29458. _this.MORPHTARGETS_NORMAL = false;
  29459. _this.MORPHTARGETS_TANGENT = false;
  29460. _this.NUM_MORPH_INFLUENCERS = 0;
  29461. _this.ALPHATESTVALUE = 0.4;
  29462. _this.LDROUTPUT = true;
  29463. _this.rebuild();
  29464. return _this;
  29465. }
  29466. PBRMaterialDefines.prototype.reset = function () {
  29467. _super.prototype.reset.call(this);
  29468. this.ALPHATESTVALUE = 0.4;
  29469. this.PBR = true;
  29470. };
  29471. return PBRMaterialDefines;
  29472. }(BABYLON.MaterialDefines));
  29473. /**
  29474. * The Physically based material base class of BJS.
  29475. *
  29476. * This offers the main features of a standard PBR material.
  29477. * For more information, please refer to the documentation :
  29478. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  29479. */
  29480. var PBRBaseMaterial = (function (_super) {
  29481. __extends(PBRBaseMaterial, _super);
  29482. /**
  29483. * Instantiates a new PBRMaterial instance.
  29484. *
  29485. * @param name The material name
  29486. * @param scene The scene the material will be use in.
  29487. */
  29488. function PBRBaseMaterial(name, scene) {
  29489. var _this = _super.call(this, name, scene) || this;
  29490. /**
  29491. * Intensity of the direct lights e.g. the four lights available in your scene.
  29492. * This impacts both the direct diffuse and specular highlights.
  29493. */
  29494. _this._directIntensity = 1.0;
  29495. /**
  29496. * Intensity of the emissive part of the material.
  29497. * This helps controlling the emissive effect without modifying the emissive color.
  29498. */
  29499. _this._emissiveIntensity = 1.0;
  29500. /**
  29501. * Intensity of the environment e.g. how much the environment will light the object
  29502. * either through harmonics for rough material or through the refelction for shiny ones.
  29503. */
  29504. _this._environmentIntensity = 1.0;
  29505. /**
  29506. * This is a special control allowing the reduction of the specular highlights coming from the
  29507. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  29508. */
  29509. _this._specularIntensity = 1.0;
  29510. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  29511. /**
  29512. * Debug Control allowing disabling the bump map on this material.
  29513. */
  29514. _this._disableBumpMap = false;
  29515. /**
  29516. * The camera exposure used on this material.
  29517. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29518. * This corresponds to a photographic exposure.
  29519. */
  29520. _this._cameraExposure = 1.0;
  29521. /**
  29522. * The camera contrast used on this material.
  29523. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  29524. */
  29525. _this._cameraContrast = 1.0;
  29526. /**
  29527. * Color Grading 2D Lookup Texture.
  29528. * This allows special effects like sepia, black and white to sixties rendering style.
  29529. */
  29530. _this._cameraColorGradingTexture = null;
  29531. /**
  29532. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29533. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29534. * 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;
  29535. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29536. */
  29537. _this._cameraColorCurves = null;
  29538. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  29539. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  29540. /**
  29541. * AKA Occlusion Texture Intensity in other nomenclature.
  29542. */
  29543. _this._ambientTextureStrength = 1.0;
  29544. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  29545. /**
  29546. * AKA Diffuse Color in other nomenclature.
  29547. */
  29548. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  29549. /**
  29550. * AKA Specular Color in other nomenclature.
  29551. */
  29552. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  29553. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29554. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  29555. /**
  29556. * AKA Glossiness in other nomenclature.
  29557. */
  29558. _this._microSurface = 0.9;
  29559. /**
  29560. * source material index of refraction (IOR)' / 'destination material IOR.
  29561. */
  29562. _this._indexOfRefraction = 0.66;
  29563. /**
  29564. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  29565. */
  29566. _this._invertRefractionY = false;
  29567. /**
  29568. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  29569. * Materials half opaque for instance using refraction could benefit from this control.
  29570. */
  29571. _this._linkRefractionWithTransparency = false;
  29572. _this._useLightmapAsShadowmap = false;
  29573. /**
  29574. * In this mode, the emissive informtaion will always be added to the lighting once.
  29575. * A light for instance can be thought as emissive.
  29576. */
  29577. _this._useEmissiveAsIllumination = false;
  29578. /**
  29579. * Secifies that the alpha is coming form the albedo channel alpha channel.
  29580. */
  29581. _this._useAlphaFromAlbedoTexture = false;
  29582. /**
  29583. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  29584. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  29585. */
  29586. _this._useSpecularOverAlpha = true;
  29587. /**
  29588. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  29589. */
  29590. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  29591. /**
  29592. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  29593. */
  29594. _this._useRoughnessFromMetallicTextureAlpha = true;
  29595. /**
  29596. * Specifies if the metallic texture contains the roughness information in its green channel.
  29597. */
  29598. _this._useRoughnessFromMetallicTextureGreen = false;
  29599. /**
  29600. * Specifies if the metallic texture contains the metallness information in its blue channel.
  29601. */
  29602. _this._useMetallnessFromMetallicTextureBlue = false;
  29603. /**
  29604. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  29605. */
  29606. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  29607. /**
  29608. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  29609. */
  29610. _this._useAmbientInGrayScale = false;
  29611. /**
  29612. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  29613. * The material will try to infer what glossiness each pixel should be.
  29614. */
  29615. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  29616. /**
  29617. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  29618. * the creation of the material.
  29619. */
  29620. _this._useScalarInLinearSpace = false;
  29621. /**
  29622. * BJS is using an harcoded light falloff based on a manually sets up range.
  29623. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  29624. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  29625. */
  29626. _this._usePhysicalLightFalloff = true;
  29627. /**
  29628. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  29629. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  29630. */
  29631. _this._useRadianceOverAlpha = true;
  29632. /**
  29633. * Allows using the bump map in parallax mode.
  29634. */
  29635. _this._useParallax = false;
  29636. /**
  29637. * Allows using the bump map in parallax occlusion mode.
  29638. */
  29639. _this._useParallaxOcclusion = false;
  29640. /**
  29641. * Controls the scale bias of the parallax mode.
  29642. */
  29643. _this._parallaxScaleBias = 0.05;
  29644. /**
  29645. * If sets to true, disables all the lights affecting the material.
  29646. */
  29647. _this._disableLighting = false;
  29648. /**
  29649. * Number of Simultaneous lights allowed on the material.
  29650. */
  29651. _this._maxSimultaneousLights = 4;
  29652. /**
  29653. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29654. */
  29655. _this._invertNormalMapX = false;
  29656. /**
  29657. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29658. */
  29659. _this._invertNormalMapY = false;
  29660. /**
  29661. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29662. */
  29663. _this._twoSidedLighting = false;
  29664. /**
  29665. * Defines the alpha limits in alpha test mode.
  29666. */
  29667. _this._alphaCutOff = 0.4;
  29668. /**
  29669. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  29670. */
  29671. _this._forceAlphaTest = false;
  29672. /**
  29673. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is usefull
  29674. * in combination of post process in float or half float mode.
  29675. */
  29676. _this._ldrOutput = true;
  29677. _this._renderTargets = new BABYLON.SmartArray(16);
  29678. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29679. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29680. _this._tempColor = new BABYLON.Color3();
  29681. _this._defines = new PBRMaterialDefines();
  29682. _this._cachedDefines = new PBRMaterialDefines();
  29683. _this._myScene = null;
  29684. _this._myShadowGenerator = null;
  29685. _this._cachedDefines.BonesPerMesh = -1;
  29686. _this.getRenderTargetTextures = function () {
  29687. _this._renderTargets.reset();
  29688. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29689. _this._renderTargets.push(_this._reflectionTexture);
  29690. }
  29691. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29692. _this._renderTargets.push(_this._refractionTexture);
  29693. }
  29694. return _this._renderTargets;
  29695. };
  29696. return _this;
  29697. }
  29698. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  29699. get: function () {
  29700. return this._useLogarithmicDepth;
  29701. },
  29702. set: function (value) {
  29703. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29704. },
  29705. enumerable: true,
  29706. configurable: true
  29707. });
  29708. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  29709. if (this._linkRefractionWithTransparency) {
  29710. return false;
  29711. }
  29712. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29713. };
  29714. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  29715. if (this._linkRefractionWithTransparency) {
  29716. return false;
  29717. }
  29718. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  29719. };
  29720. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  29721. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  29722. };
  29723. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  29724. return this._albedoTexture;
  29725. };
  29726. PBRBaseMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29727. if (!mesh) {
  29728. return true;
  29729. }
  29730. if (this._defines.INSTANCES !== useInstances) {
  29731. return false;
  29732. }
  29733. return false;
  29734. };
  29735. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  29736. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  29737. };
  29738. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  29739. if (!useScalarInLinear) {
  29740. color.toLinearSpaceToRef(ref);
  29741. }
  29742. else {
  29743. ref.r = color.r;
  29744. ref.g = color.g;
  29745. ref.b = color.b;
  29746. }
  29747. };
  29748. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  29749. var lightIndex = 0;
  29750. var depthValuesAlreadySet = false;
  29751. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  29752. var light = _a[_i];
  29753. var useUbo = light._uniformBuffer.useUbo;
  29754. var scaledIntensity = light.getScaledIntensity();
  29755. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  29756. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29757. // GAMMA CORRECTION.
  29758. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  29759. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  29760. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  29761. if (defines["SPECULARTERM"]) {
  29762. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  29763. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  29764. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  29765. }
  29766. // Shadows
  29767. if (scene.shadowsEnabled) {
  29768. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  29769. }
  29770. light._uniformBuffer.update();
  29771. lightIndex++;
  29772. if (lightIndex === maxSimultaneousLights)
  29773. break;
  29774. }
  29775. };
  29776. PBRBaseMaterial.prototype.isReady = function (mesh, useInstances) {
  29777. if (this.isFrozen) {
  29778. if (this._wasPreviouslyReady) {
  29779. return true;
  29780. }
  29781. }
  29782. var scene = this.getScene();
  29783. var engine = scene.getEngine();
  29784. var needUVs = false;
  29785. this._defines.reset();
  29786. if (scene.lightsEnabled && !this._disableLighting) {
  29787. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this._maxSimultaneousLights);
  29788. }
  29789. if (!this.checkReadyOnEveryCall) {
  29790. if (this._renderId === scene.getRenderId()) {
  29791. if (this._checkCache(scene, mesh, useInstances)) {
  29792. return true;
  29793. }
  29794. }
  29795. }
  29796. if (scene.texturesEnabled) {
  29797. if (scene.getEngine().getCaps().textureLOD) {
  29798. this._defines.LODBASEDMICROSFURACE = true;
  29799. }
  29800. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29801. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  29802. return false;
  29803. }
  29804. needUVs = true;
  29805. this._defines.ALBEDO = true;
  29806. }
  29807. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29808. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29809. return false;
  29810. }
  29811. needUVs = true;
  29812. this._defines.AMBIENT = true;
  29813. this._defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  29814. }
  29815. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29816. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29817. return false;
  29818. }
  29819. needUVs = true;
  29820. this._defines.OPACITY = true;
  29821. if (this._opacityTexture.getAlphaFromRGB) {
  29822. this._defines.OPACITYRGB = true;
  29823. }
  29824. }
  29825. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  29826. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29827. if (!reflectionTexture.isReadyOrNotBlocking()) {
  29828. return false;
  29829. }
  29830. this._defines.REFLECTION = true;
  29831. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29832. this._defines.INVERTCUBICMAP = true;
  29833. }
  29834. this._defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  29835. switch (reflectionTexture.coordinatesMode) {
  29836. case BABYLON.Texture.CUBIC_MODE:
  29837. case BABYLON.Texture.INVCUBIC_MODE:
  29838. this._defines.REFLECTIONMAP_CUBIC = true;
  29839. break;
  29840. case BABYLON.Texture.EXPLICIT_MODE:
  29841. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29842. break;
  29843. case BABYLON.Texture.PLANAR_MODE:
  29844. this._defines.REFLECTIONMAP_PLANAR = true;
  29845. break;
  29846. case BABYLON.Texture.PROJECTION_MODE:
  29847. this._defines.REFLECTIONMAP_PROJECTION = true;
  29848. break;
  29849. case BABYLON.Texture.SKYBOX_MODE:
  29850. this._defines.REFLECTIONMAP_SKYBOX = true;
  29851. break;
  29852. case BABYLON.Texture.SPHERICAL_MODE:
  29853. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29854. break;
  29855. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29856. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29857. break;
  29858. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29859. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29860. break;
  29861. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  29862. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  29863. break;
  29864. }
  29865. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  29866. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  29867. if (reflectionTexture.isPMREM) {
  29868. this._defines.USEPMREMREFLECTION = true;
  29869. }
  29870. }
  29871. }
  29872. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29873. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  29874. return false;
  29875. }
  29876. needUVs = true;
  29877. this._defines.LIGHTMAP = true;
  29878. this._defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  29879. }
  29880. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29881. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  29882. return false;
  29883. }
  29884. needUVs = true;
  29885. this._defines.EMISSIVE = true;
  29886. }
  29887. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29888. if (this._metallicTexture) {
  29889. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  29890. return false;
  29891. }
  29892. needUVs = true;
  29893. this._defines.METALLICWORKFLOW = true;
  29894. this._defines.METALLICMAP = true;
  29895. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  29896. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  29897. this._defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  29898. this._defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  29899. }
  29900. else if (this._reflectivityTexture) {
  29901. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  29902. return false;
  29903. }
  29904. needUVs = true;
  29905. this._defines.REFLECTIVITY = true;
  29906. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  29907. this._defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  29908. }
  29909. if (this._microSurfaceTexture) {
  29910. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  29911. return false;
  29912. }
  29913. needUVs = true;
  29914. this._defines.MICROSURFACEMAP = true;
  29915. }
  29916. }
  29917. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  29918. // Bump texure can not be none blocking.
  29919. if (!this._bumpTexture.isReady()) {
  29920. return false;
  29921. }
  29922. needUVs = true;
  29923. this._defines.BUMP = true;
  29924. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29925. this._defines.PARALLAX = true;
  29926. if (this._useParallaxOcclusion) {
  29927. this._defines.PARALLAXOCCLUSION = true;
  29928. }
  29929. }
  29930. if (this._invertNormalMapX) {
  29931. this._defines.INVERTNORMALMAPX = true;
  29932. }
  29933. if (this._invertNormalMapY) {
  29934. this._defines.INVERTNORMALMAPY = true;
  29935. }
  29936. if (scene._mirroredCameraPosition) {
  29937. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29938. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29939. }
  29940. this._defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  29941. }
  29942. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29943. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  29944. return false;
  29945. }
  29946. needUVs = true;
  29947. this._defines.REFRACTION = true;
  29948. this._defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  29949. if (this._linkRefractionWithTransparency) {
  29950. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  29951. }
  29952. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  29953. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  29954. if (this._refractionTexture.isPMREM) {
  29955. this._defines.USEPMREMREFRACTION = true;
  29956. }
  29957. }
  29958. }
  29959. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29960. // Color Grading texure can not be none blocking.
  29961. if (!this._cameraColorGradingTexture.isReady()) {
  29962. return false;
  29963. }
  29964. this._defines.CAMERACOLORGRADING = true;
  29965. }
  29966. if (!this.backFaceCulling && this._twoSidedLighting) {
  29967. this._defines.TWOSIDEDLIGHTING = true;
  29968. }
  29969. }
  29970. this._defines.LDROUTPUT = this._ldrOutput;
  29971. // Effect
  29972. if (scene.clipPlane) {
  29973. this._defines.CLIPPLANE = true;
  29974. }
  29975. this._defines.ALPHATESTVALUE = this._alphaCutOff;
  29976. if (engine.getAlphaTesting() || this._forceAlphaTest) {
  29977. this._defines.ALPHATEST = true;
  29978. }
  29979. if (this._shouldUseAlphaFromAlbedoTexture()) {
  29980. this._defines.ALPHAFROMALBEDO = true;
  29981. }
  29982. if (this._useEmissiveAsIllumination) {
  29983. this._defines.EMISSIVEASILLUMINATION = true;
  29984. }
  29985. if (this.useLogarithmicDepth) {
  29986. this._defines.LOGARITHMICDEPTH = true;
  29987. }
  29988. if (this._cameraContrast != 1) {
  29989. this._defines.CAMERACONTRAST = true;
  29990. }
  29991. if (this._cameraExposure != 1) {
  29992. this._defines.CAMERATONEMAP = true;
  29993. }
  29994. if (this._cameraColorCurves) {
  29995. this._defines.CAMERACOLORCURVES = true;
  29996. }
  29997. // Point size
  29998. if (this.pointsCloud || scene.forcePointsCloud) {
  29999. this._defines.POINTSIZE = true;
  30000. }
  30001. // Fog
  30002. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30003. this._defines.FOG = true;
  30004. }
  30005. if (BABYLON.StandardMaterial.FresnelEnabled) {
  30006. // Fresnel
  30007. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  30008. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30009. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  30010. this._defines.OPACITYFRESNEL = true;
  30011. }
  30012. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30013. this._defines.EMISSIVEFRESNEL = true;
  30014. }
  30015. this._defines.FRESNEL = true;
  30016. }
  30017. }
  30018. if (this._defines.SPECULARTERM && this._useSpecularOverAlpha) {
  30019. this._defines.SPECULAROVERALPHA = true;
  30020. }
  30021. if (this._usePhysicalLightFalloff) {
  30022. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  30023. }
  30024. if (this._useRadianceOverAlpha) {
  30025. this._defines.RADIANCEOVERALPHA = true;
  30026. }
  30027. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  30028. this._defines.METALLICWORKFLOW = true;
  30029. }
  30030. // Attribs
  30031. if (mesh) {
  30032. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30033. mesh.createNormals(true);
  30034. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  30035. }
  30036. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30037. this._defines.NORMAL = true;
  30038. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30039. this._defines.TANGENT = true;
  30040. }
  30041. }
  30042. if (needUVs) {
  30043. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30044. this._defines.UV1 = true;
  30045. }
  30046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30047. this._defines.UV2 = true;
  30048. }
  30049. }
  30050. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30051. this._defines.VERTEXCOLOR = true;
  30052. if (mesh.hasVertexAlpha) {
  30053. this._defines.VERTEXALPHA = true;
  30054. }
  30055. }
  30056. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30057. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30058. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30059. }
  30060. // Instances
  30061. if (useInstances) {
  30062. this._defines.INSTANCES = true;
  30063. }
  30064. if (mesh.morphTargetManager) {
  30065. var manager = mesh.morphTargetManager;
  30066. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  30067. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  30068. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  30069. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  30070. }
  30071. }
  30072. // Get correct effect
  30073. if (!this._defines.isEqual(this._cachedDefines)) {
  30074. this._defines.cloneTo(this._cachedDefines);
  30075. scene.resetCachedMaterial();
  30076. // Fallbacks
  30077. var fallbacks = new BABYLON.EffectFallbacks();
  30078. if (this._defines.REFLECTION) {
  30079. fallbacks.addFallback(0, "REFLECTION");
  30080. }
  30081. if (this._defines.REFRACTION) {
  30082. fallbacks.addFallback(0, "REFRACTION");
  30083. }
  30084. if (this._defines.REFLECTIVITY) {
  30085. fallbacks.addFallback(0, "REFLECTIVITY");
  30086. }
  30087. if (this._defines.BUMP) {
  30088. fallbacks.addFallback(0, "BUMP");
  30089. }
  30090. if (this._defines.PARALLAX) {
  30091. fallbacks.addFallback(1, "PARALLAX");
  30092. }
  30093. if (this._defines.PARALLAXOCCLUSION) {
  30094. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30095. }
  30096. if (this._defines.SPECULAROVERALPHA) {
  30097. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30098. }
  30099. if (this._defines.FOG) {
  30100. fallbacks.addFallback(1, "FOG");
  30101. }
  30102. if (this._defines.POINTSIZE) {
  30103. fallbacks.addFallback(0, "POINTSIZE");
  30104. }
  30105. if (this._defines.LOGARITHMICDEPTH) {
  30106. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30107. }
  30108. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this._maxSimultaneousLights);
  30109. if (this._defines.SPECULARTERM) {
  30110. fallbacks.addFallback(0, "SPECULARTERM");
  30111. }
  30112. if (this._defines.OPACITYFRESNEL) {
  30113. fallbacks.addFallback(1, "OPACITYFRESNEL");
  30114. }
  30115. if (this._defines.EMISSIVEFRESNEL) {
  30116. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  30117. }
  30118. if (this._defines.FRESNEL) {
  30119. fallbacks.addFallback(3, "FRESNEL");
  30120. }
  30121. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  30122. fallbacks.addCPUSkinningFallback(0, mesh);
  30123. }
  30124. //Attributes
  30125. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30126. if (this._defines.NORMAL) {
  30127. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30128. }
  30129. if (this._defines.TANGENT) {
  30130. attribs.push(BABYLON.VertexBuffer.TangentKind);
  30131. }
  30132. if (this._defines.UV1) {
  30133. attribs.push(BABYLON.VertexBuffer.UVKind);
  30134. }
  30135. if (this._defines.UV2) {
  30136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30137. }
  30138. if (this._defines.VERTEXCOLOR) {
  30139. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30140. }
  30141. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30142. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30143. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  30144. // Legacy browser patch
  30145. var join = this._defines.toString();
  30146. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  30147. "vFogInfos", "vFogColor", "pointSize",
  30148. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30149. "mBones",
  30150. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30151. "depthValues",
  30152. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  30153. "vLightingIntensity",
  30154. "logarithmicDepthConstant",
  30155. "vSphericalX", "vSphericalY", "vSphericalZ",
  30156. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  30157. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  30158. "vMicrosurfaceTextureLods",
  30159. "vCameraInfos"
  30160. ];
  30161. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30162. var uniformBuffers = ["Material", "Scene"];
  30163. if (this._defines.CAMERACOLORCURVES) {
  30164. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30165. }
  30166. if (this._defines.CAMERACOLORGRADING) {
  30167. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30168. }
  30169. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30170. uniformsNames: uniforms,
  30171. uniformBuffersNames: uniformBuffers,
  30172. samplers: samplers,
  30173. defines: this._defines,
  30174. maxSimultaneousLights: this._maxSimultaneousLights
  30175. });
  30176. var onCompiled = function (effect) {
  30177. if (this.onCompiled) {
  30178. this.onCompiled(effect);
  30179. }
  30180. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  30181. }.bind(this);
  30182. this._effect = scene.getEngine().createEffect("pbr", {
  30183. attributes: attribs,
  30184. uniformsNames: uniforms,
  30185. uniformBuffersNames: uniformBuffers,
  30186. samplers: samplers,
  30187. defines: join,
  30188. fallbacks: fallbacks,
  30189. onCompiled: onCompiled,
  30190. onError: this.onError,
  30191. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  30192. }, engine);
  30193. this.buildUniformLayout();
  30194. }
  30195. if (!this._effect.isReady()) {
  30196. return false;
  30197. }
  30198. this._renderId = scene.getRenderId();
  30199. this._wasPreviouslyReady = true;
  30200. return true;
  30201. };
  30202. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  30203. // Order is important !
  30204. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  30205. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  30206. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30207. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30208. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30209. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  30210. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  30211. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30212. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30213. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30214. this._uniformBuffer.addUniform("albedoMatrix", 16);
  30215. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30216. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30217. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30218. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30219. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  30220. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  30221. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30222. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30223. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30224. this._uniformBuffer.addUniform("vReflectionColor", 3);
  30225. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  30226. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  30227. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  30228. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  30229. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30230. this._uniformBuffer.addUniform("opacityParts", 4);
  30231. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30232. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30233. this._uniformBuffer.addUniform("pointSize", 1);
  30234. this._uniformBuffer.create();
  30235. };
  30236. PBRBaseMaterial.prototype.unbind = function () {
  30237. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30238. this._uniformBuffer.setTexture("reflection2DSampler", null);
  30239. }
  30240. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30241. this._uniformBuffer.setTexture("refraction2DSampler", null);
  30242. }
  30243. _super.prototype.unbind.call(this);
  30244. };
  30245. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30246. this._effect.setMatrix("world", world);
  30247. };
  30248. PBRBaseMaterial.prototype.bind = function (world, mesh) {
  30249. this._myScene = this.getScene();
  30250. var effect = this._effect;
  30251. // Matrices
  30252. this.bindOnlyWorldMatrix(world);
  30253. // Bones
  30254. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30255. if (this._myScene.getCachedMaterial() !== this) {
  30256. this._uniformBuffer.bindToEffect(effect, "Material");
  30257. this.bindViewProjection(effect);
  30258. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30259. // Fresnel
  30260. if (BABYLON.StandardMaterial.FresnelEnabled) {
  30261. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  30262. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  30263. }
  30264. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30265. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  30266. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  30267. }
  30268. }
  30269. // Texture uniforms
  30270. if (this._myScene.texturesEnabled) {
  30271. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30272. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  30273. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  30274. }
  30275. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30276. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  30277. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  30278. }
  30279. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30280. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30281. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  30282. }
  30283. var reflectionTexture = this._reflectionTexture || this._myScene.environmentTexture;
  30284. ;
  30285. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30286. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  30287. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  30288. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  30289. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  30290. this._effect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  30291. this._effect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  30292. this._effect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  30293. this._effect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  30294. this._effect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  30295. this._effect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  30296. this._effect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  30297. this._effect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  30298. this._effect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  30299. }
  30300. }
  30301. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30302. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30303. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  30304. }
  30305. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30306. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30307. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  30308. }
  30309. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30310. if (this._metallicTexture) {
  30311. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  30312. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  30313. }
  30314. else if (this._reflectivityTexture) {
  30315. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  30316. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  30317. }
  30318. if (this._microSurfaceTexture) {
  30319. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  30320. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  30321. }
  30322. }
  30323. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30324. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  30325. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  30326. }
  30327. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30328. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  30329. var depth = 1.0;
  30330. if (!this._refractionTexture.isCube) {
  30331. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30332. if (this._refractionTexture.depth) {
  30333. depth = this._refractionTexture.depth;
  30334. }
  30335. }
  30336. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  30337. }
  30338. if ((reflectionTexture || this._refractionTexture)) {
  30339. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  30340. }
  30341. }
  30342. // Point size
  30343. if (this.pointsCloud) {
  30344. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30345. }
  30346. // Colors
  30347. if (this._defines.METALLICWORKFLOW) {
  30348. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  30349. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  30350. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  30351. }
  30352. else {
  30353. // GAMMA CORRECTION.
  30354. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  30355. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  30356. }
  30357. // GAMMA CORRECTION.
  30358. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  30359. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  30360. // GAMMA CORRECTION.
  30361. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  30362. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  30363. // GAMMA CORRECTION.
  30364. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  30365. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  30366. // Misc
  30367. this._lightingInfos.x = this._directIntensity;
  30368. this._lightingInfos.y = this._emissiveIntensity;
  30369. this._lightingInfos.z = this._environmentIntensity;
  30370. this._lightingInfos.w = this._specularIntensity;
  30371. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  30372. }
  30373. // Textures
  30374. if (this._myScene.texturesEnabled) {
  30375. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30376. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  30377. }
  30378. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30379. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  30380. }
  30381. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30382. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  30383. }
  30384. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30385. if (reflectionTexture.isCube) {
  30386. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  30387. }
  30388. else {
  30389. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  30390. }
  30391. }
  30392. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30393. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  30394. }
  30395. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30396. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  30397. }
  30398. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30399. if (this._metallicTexture) {
  30400. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  30401. }
  30402. else if (this._reflectivityTexture) {
  30403. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  30404. }
  30405. if (this._microSurfaceTexture) {
  30406. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  30407. }
  30408. }
  30409. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30410. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  30411. }
  30412. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30413. if (this._refractionTexture.isCube) {
  30414. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  30415. }
  30416. else {
  30417. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  30418. }
  30419. }
  30420. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  30421. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._effect);
  30422. }
  30423. }
  30424. // Clip plane
  30425. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  30426. // Colors
  30427. this._myScene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  30428. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  30429. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30430. }
  30431. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  30432. // Lights
  30433. if (this._myScene.lightsEnabled && !this._disableLighting) {
  30434. BABYLON.PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  30435. }
  30436. // View
  30437. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  30438. this.bindView(effect);
  30439. }
  30440. // Fog
  30441. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  30442. // Morph targets
  30443. if (this._defines.NUM_MORPH_INFLUENCERS) {
  30444. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  30445. }
  30446. this._cameraInfos.x = this._cameraExposure;
  30447. this._cameraInfos.y = this._cameraContrast;
  30448. effect.setVector4("vCameraInfos", this._cameraInfos);
  30449. if (this._cameraColorCurves) {
  30450. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._effect);
  30451. }
  30452. // Log. depth
  30453. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  30454. }
  30455. this._uniformBuffer.update();
  30456. this._afterBind(mesh);
  30457. this._myScene = null;
  30458. };
  30459. PBRBaseMaterial.prototype.getAnimatables = function () {
  30460. var results = [];
  30461. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  30462. results.push(this._albedoTexture);
  30463. }
  30464. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30465. results.push(this._ambientTexture);
  30466. }
  30467. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30468. results.push(this._opacityTexture);
  30469. }
  30470. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30471. results.push(this._reflectionTexture);
  30472. }
  30473. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30474. results.push(this._emissiveTexture);
  30475. }
  30476. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  30477. results.push(this._metallicTexture);
  30478. }
  30479. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  30480. results.push(this._reflectivityTexture);
  30481. }
  30482. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30483. results.push(this._bumpTexture);
  30484. }
  30485. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30486. results.push(this._lightmapTexture);
  30487. }
  30488. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30489. results.push(this._refractionTexture);
  30490. }
  30491. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  30492. results.push(this._cameraColorGradingTexture);
  30493. }
  30494. return results;
  30495. };
  30496. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30497. if (forceDisposeTextures) {
  30498. if (this._albedoTexture) {
  30499. this._albedoTexture.dispose();
  30500. }
  30501. if (this._ambientTexture) {
  30502. this._ambientTexture.dispose();
  30503. }
  30504. if (this._opacityTexture) {
  30505. this._opacityTexture.dispose();
  30506. }
  30507. if (this._reflectionTexture) {
  30508. this._reflectionTexture.dispose();
  30509. }
  30510. if (this._emissiveTexture) {
  30511. this._emissiveTexture.dispose();
  30512. }
  30513. if (this._metallicTexture) {
  30514. this._metallicTexture.dispose();
  30515. }
  30516. if (this._reflectivityTexture) {
  30517. this._reflectivityTexture.dispose();
  30518. }
  30519. if (this._bumpTexture) {
  30520. this._bumpTexture.dispose();
  30521. }
  30522. if (this._lightmapTexture) {
  30523. this._lightmapTexture.dispose();
  30524. }
  30525. if (this._refractionTexture) {
  30526. this._refractionTexture.dispose();
  30527. }
  30528. if (this._cameraColorGradingTexture) {
  30529. this._cameraColorGradingTexture.dispose();
  30530. }
  30531. }
  30532. this._renderTargets.dispose();
  30533. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30534. };
  30535. return PBRBaseMaterial;
  30536. }(BABYLON.Material));
  30537. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  30538. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  30539. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  30540. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  30541. __decorate([
  30542. BABYLON.serialize()
  30543. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  30544. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  30545. })(BABYLON || (BABYLON = {}));
  30546. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  30547. var BABYLON;
  30548. (function (BABYLON) {
  30549. var Internals;
  30550. (function (Internals) {
  30551. /**
  30552. * The Physically based simple base material of BJS.
  30553. *
  30554. * This enables better naming and convention enforcements on top of the pbrMaterial.
  30555. * It is used as the base class for both the specGloss and metalRough conventions.
  30556. */
  30557. var PBRBaseSimpleMaterial = (function (_super) {
  30558. __extends(PBRBaseSimpleMaterial, _super);
  30559. /**
  30560. * Instantiates a new PBRMaterial instance.
  30561. *
  30562. * @param name The material name
  30563. * @param scene The scene the material will be use in.
  30564. */
  30565. function PBRBaseSimpleMaterial(name, scene) {
  30566. var _this = _super.call(this, name, scene) || this;
  30567. /**
  30568. * Number of Simultaneous lights allowed on the material.
  30569. */
  30570. _this.maxSimultaneousLights = 4;
  30571. /**
  30572. * If sets to true, disables all the lights affecting the material.
  30573. */
  30574. _this.disableLighting = false;
  30575. /**
  30576. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30577. */
  30578. _this.invertNormalMapX = false;
  30579. /**
  30580. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30581. */
  30582. _this.invertNormalMapY = false;
  30583. /**
  30584. * Emissivie color used to self-illuminate the model.
  30585. */
  30586. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30587. /**
  30588. * Occlusion Channel Strenght.
  30589. */
  30590. _this.occlusionStrength = 1.0;
  30591. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30592. _this._useEmissiveAsIllumination = true;
  30593. _this._useAmbientInGrayScale = true;
  30594. _this._useScalarInLinearSpace = true;
  30595. return _this;
  30596. }
  30597. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  30598. /**
  30599. * Gets the current transparency mode.
  30600. */
  30601. get: function () {
  30602. return this._transparencyMode;
  30603. },
  30604. /**
  30605. * Sets the transparency mode of the material.
  30606. */
  30607. set: function (value) {
  30608. this._transparencyMode = value;
  30609. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  30610. this._forceAlphaTest = true;
  30611. }
  30612. else {
  30613. this._forceAlphaTest = false;
  30614. }
  30615. },
  30616. enumerable: true,
  30617. configurable: true
  30618. });
  30619. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  30620. /**
  30621. * Gets the current double sided mode.
  30622. */
  30623. get: function () {
  30624. return this._twoSidedLighting;
  30625. },
  30626. /**
  30627. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30628. */
  30629. set: function (value) {
  30630. this._twoSidedLighting = value;
  30631. this.backFaceCulling = !value;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. /**
  30637. * Specifies wether or not the alpha value of the albedo texture should be used.
  30638. */
  30639. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30640. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30641. };
  30642. /**
  30643. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  30644. */
  30645. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  30646. if (this._linkRefractionWithTransparency) {
  30647. return false;
  30648. }
  30649. return (this.alpha < 1.0) ||
  30650. (this._shouldUseAlphaFromAlbedoTexture() &&
  30651. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  30652. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  30653. };
  30654. /**
  30655. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  30656. */
  30657. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  30658. if (this._linkRefractionWithTransparency) {
  30659. return false;
  30660. }
  30661. return this._shouldUseAlphaFromAlbedoTexture() &&
  30662. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  30663. };
  30664. return PBRBaseSimpleMaterial;
  30665. }(BABYLON.PBRBaseMaterial));
  30666. __decorate([
  30667. BABYLON.serialize(),
  30668. BABYLON.expandToProperty(null)
  30669. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  30670. __decorate([
  30671. BABYLON.serialize(),
  30672. BABYLON.expandToProperty(null)
  30673. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  30674. __decorate([
  30675. BABYLON.serializeAsTexture(),
  30676. BABYLON.expandToProperty(null, "_reflectionTexture")
  30677. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  30678. __decorate([
  30679. BABYLON.serialize(),
  30680. BABYLON.expandToProperty(null)
  30681. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  30682. __decorate([
  30683. BABYLON.serialize(),
  30684. BABYLON.expandToProperty(null)
  30685. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  30686. __decorate([
  30687. BABYLON.serializeAsTexture(),
  30688. BABYLON.expandToProperty(null, "_bumpTexture")
  30689. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  30690. __decorate([
  30691. BABYLON.serializeAsColor3("emissive"),
  30692. BABYLON.expandToProperty(null)
  30693. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  30694. __decorate([
  30695. BABYLON.serializeAsTexture(),
  30696. BABYLON.expandToProperty(null)
  30697. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  30698. __decorate([
  30699. BABYLON.serialize(),
  30700. BABYLON.expandToProperty(null, "_ambientTextureStrength")
  30701. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  30702. __decorate([
  30703. BABYLON.serializeAsTexture(),
  30704. BABYLON.expandToProperty(null, "_ambientTexture")
  30705. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  30706. __decorate([
  30707. BABYLON.serialize(),
  30708. BABYLON.expandToProperty(null, "_alphaCutOff")
  30709. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  30710. __decorate([
  30711. BABYLON.serialize()
  30712. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  30713. __decorate([
  30714. BABYLON.serialize()
  30715. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  30716. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  30717. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30718. })(BABYLON || (BABYLON = {}));
  30719. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  30720. var BABYLON;
  30721. (function (BABYLON) {
  30722. /**
  30723. * The Physically based material of BJS.
  30724. *
  30725. * This offers the main features of a standard PBR material.
  30726. * For more information, please refer to the documentation :
  30727. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  30728. */
  30729. var PBRMaterial = (function (_super) {
  30730. __extends(PBRMaterial, _super);
  30731. /**
  30732. * Instantiates a new PBRMaterial instance.
  30733. *
  30734. * @param name The material name
  30735. * @param scene The scene the material will be use in.
  30736. */
  30737. function PBRMaterial(name, scene) {
  30738. var _this = _super.call(this, name, scene) || this;
  30739. /**
  30740. * Intensity of the direct lights e.g. the four lights available in your scene.
  30741. * This impacts both the direct diffuse and specular highlights.
  30742. */
  30743. _this.directIntensity = 1.0;
  30744. /**
  30745. * Intensity of the emissive part of the material.
  30746. * This helps controlling the emissive effect without modifying the emissive color.
  30747. */
  30748. _this.emissiveIntensity = 1.0;
  30749. /**
  30750. * Intensity of the environment e.g. how much the environment will light the object
  30751. * either through harmonics for rough material or through the refelction for shiny ones.
  30752. */
  30753. _this.environmentIntensity = 1.0;
  30754. /**
  30755. * This is a special control allowing the reduction of the specular highlights coming from the
  30756. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  30757. */
  30758. _this.specularIntensity = 1.0;
  30759. /**
  30760. * Debug Control allowing disabling the bump map on this material.
  30761. */
  30762. _this.disableBumpMap = false;
  30763. /**
  30764. * The camera exposure used on this material.
  30765. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30766. * This corresponds to a photographic exposure.
  30767. */
  30768. _this.cameraExposure = 1.0;
  30769. /**
  30770. * The camera contrast used on this material.
  30771. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  30772. */
  30773. _this.cameraContrast = 1.0;
  30774. /**
  30775. * Color Grading 2D Lookup Texture.
  30776. * This allows special effects like sepia, black and white to sixties rendering style.
  30777. */
  30778. _this.cameraColorGradingTexture = null;
  30779. /**
  30780. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30781. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30782. * 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;
  30783. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30784. */
  30785. _this.cameraColorCurves = null;
  30786. /**
  30787. * AKA Occlusion Texture Intensity in other nomenclature.
  30788. */
  30789. _this.ambientTextureStrength = 1.0;
  30790. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30791. /**
  30792. * AKA Diffuse Color in other nomenclature.
  30793. */
  30794. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  30795. /**
  30796. * AKA Specular Color in other nomenclature.
  30797. */
  30798. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  30799. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30800. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30801. /**
  30802. * AKA Glossiness in other nomenclature.
  30803. */
  30804. _this.microSurface = 0.9;
  30805. /**
  30806. * source material index of refraction (IOR)' / 'destination material IOR.
  30807. */
  30808. _this.indexOfRefraction = 0.66;
  30809. /**
  30810. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30811. */
  30812. _this.invertRefractionY = false;
  30813. /**
  30814. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30815. * Materials half opaque for instance using refraction could benefit from this control.
  30816. */
  30817. _this.linkRefractionWithTransparency = false;
  30818. _this.useLightmapAsShadowmap = false;
  30819. /**
  30820. * In this mode, the emissive informtaion will always be added to the lighting once.
  30821. * A light for instance can be thought as emissive.
  30822. */
  30823. _this.useEmissiveAsIllumination = false;
  30824. /**
  30825. * Secifies that the alpha is coming form the albedo channel alpha channel.
  30826. */
  30827. _this.useAlphaFromAlbedoTexture = false;
  30828. /**
  30829. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30830. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30831. */
  30832. _this.useSpecularOverAlpha = true;
  30833. /**
  30834. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30835. */
  30836. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  30837. /**
  30838. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30839. */
  30840. _this.useRoughnessFromMetallicTextureAlpha = true;
  30841. /**
  30842. * Specifies if the metallic texture contains the roughness information in its green channel.
  30843. */
  30844. _this.useRoughnessFromMetallicTextureGreen = false;
  30845. /**
  30846. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30847. */
  30848. _this.useMetallnessFromMetallicTextureBlue = false;
  30849. /**
  30850. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30851. */
  30852. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  30853. /**
  30854. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30855. */
  30856. _this.useAmbientInGrayScale = false;
  30857. /**
  30858. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30859. * The material will try to infer what glossiness each pixel should be.
  30860. */
  30861. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  30862. /**
  30863. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  30864. * the creation of the material.
  30865. */
  30866. _this.useScalarInLinearSpace = false;
  30867. /**
  30868. * BJS is using an harcoded light falloff based on a manually sets up range.
  30869. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30870. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30871. */
  30872. _this.usePhysicalLightFalloff = true;
  30873. /**
  30874. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30875. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30876. */
  30877. _this.useRadianceOverAlpha = true;
  30878. /**
  30879. * Allows using the bump map in parallax mode.
  30880. */
  30881. _this.useParallax = false;
  30882. /**
  30883. * Allows using the bump map in parallax occlusion mode.
  30884. */
  30885. _this.useParallaxOcclusion = false;
  30886. /**
  30887. * Controls the scale bias of the parallax mode.
  30888. */
  30889. _this.parallaxScaleBias = 0.05;
  30890. /**
  30891. * If sets to true, disables all the lights affecting the material.
  30892. */
  30893. _this.disableLighting = false;
  30894. /**
  30895. * Number of Simultaneous lights allowed on the material.
  30896. */
  30897. _this.maxSimultaneousLights = 4;
  30898. /**
  30899. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30900. */
  30901. _this.invertNormalMapX = false;
  30902. /**
  30903. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30904. */
  30905. _this.invertNormalMapY = false;
  30906. /**
  30907. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30908. */
  30909. _this.twoSidedLighting = false;
  30910. return _this;
  30911. }
  30912. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  30913. /**
  30914. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  30915. */
  30916. get: function () {
  30917. return this._PBRMATERIAL_OPAQUE;
  30918. },
  30919. enumerable: true,
  30920. configurable: true
  30921. });
  30922. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  30923. /**
  30924. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  30925. */
  30926. get: function () {
  30927. return this._PBRMATERIAL_ALPHATEST;
  30928. },
  30929. enumerable: true,
  30930. configurable: true
  30931. });
  30932. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  30933. /**
  30934. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  30935. */
  30936. get: function () {
  30937. return this._PBRMATERIAL_ALPHABLEND;
  30938. },
  30939. enumerable: true,
  30940. configurable: true
  30941. });
  30942. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  30943. /**
  30944. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  30945. * They are also discarded below the alpha cutoff threshold to improve performances.
  30946. */
  30947. get: function () {
  30948. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. PBRMaterial.prototype.getClassName = function () {
  30954. return "PBRMaterial";
  30955. };
  30956. PBRMaterial.prototype.clone = function (name) {
  30957. var _this = this;
  30958. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  30959. };
  30960. PBRMaterial.prototype.serialize = function () {
  30961. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30962. serializationObject.customType = "BABYLON.PBRMaterial";
  30963. return serializationObject;
  30964. };
  30965. // Statics
  30966. PBRMaterial.Parse = function (source, scene, rootUrl) {
  30967. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  30968. };
  30969. return PBRMaterial;
  30970. }(BABYLON.PBRBaseMaterial));
  30971. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  30972. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  30973. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  30974. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  30975. __decorate([
  30976. BABYLON.serialize(),
  30977. BABYLON.expandToProperty(null)
  30978. ], PBRMaterial.prototype, "directIntensity", void 0);
  30979. __decorate([
  30980. BABYLON.serialize(),
  30981. BABYLON.expandToProperty(null)
  30982. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  30983. __decorate([
  30984. BABYLON.serialize(),
  30985. BABYLON.expandToProperty(null)
  30986. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  30987. __decorate([
  30988. BABYLON.serialize(),
  30989. BABYLON.expandToProperty(null)
  30990. ], PBRMaterial.prototype, "specularIntensity", void 0);
  30991. __decorate([
  30992. BABYLON.serialize(),
  30993. BABYLON.expandToProperty(null)
  30994. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  30995. __decorate([
  30996. BABYLON.serialize(),
  30997. BABYLON.expandToProperty(null)
  30998. ], PBRMaterial.prototype, "cameraExposure", void 0);
  30999. __decorate([
  31000. BABYLON.serialize(),
  31001. BABYLON.expandToProperty(null)
  31002. ], PBRMaterial.prototype, "cameraContrast", void 0);
  31003. __decorate([
  31004. BABYLON.serializeAsTexture(),
  31005. BABYLON.expandToProperty(null)
  31006. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  31007. __decorate([
  31008. BABYLON.serializeAsColorCurves(),
  31009. BABYLON.expandToProperty(null)
  31010. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  31011. __decorate([
  31012. BABYLON.serializeAsTexture(),
  31013. BABYLON.expandToProperty(null)
  31014. ], PBRMaterial.prototype, "albedoTexture", void 0);
  31015. __decorate([
  31016. BABYLON.serializeAsTexture(),
  31017. BABYLON.expandToProperty(null)
  31018. ], PBRMaterial.prototype, "ambientTexture", void 0);
  31019. __decorate([
  31020. BABYLON.serialize(),
  31021. BABYLON.expandToProperty(null)
  31022. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  31023. __decorate([
  31024. BABYLON.serializeAsTexture(),
  31025. BABYLON.expandToProperty(null)
  31026. ], PBRMaterial.prototype, "opacityTexture", void 0);
  31027. __decorate([
  31028. BABYLON.serializeAsTexture(),
  31029. BABYLON.expandToProperty(null)
  31030. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  31031. __decorate([
  31032. BABYLON.serializeAsTexture(),
  31033. BABYLON.expandToProperty(null)
  31034. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  31035. __decorate([
  31036. BABYLON.serializeAsTexture(),
  31037. BABYLON.expandToProperty(null)
  31038. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  31039. __decorate([
  31040. BABYLON.serializeAsTexture(),
  31041. BABYLON.expandToProperty(null)
  31042. ], PBRMaterial.prototype, "metallicTexture", void 0);
  31043. __decorate([
  31044. BABYLON.serialize(),
  31045. BABYLON.expandToProperty(null)
  31046. ], PBRMaterial.prototype, "metallic", void 0);
  31047. __decorate([
  31048. BABYLON.serialize(),
  31049. BABYLON.expandToProperty(null)
  31050. ], PBRMaterial.prototype, "roughness", void 0);
  31051. __decorate([
  31052. BABYLON.serializeAsTexture(),
  31053. BABYLON.expandToProperty(null)
  31054. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  31055. __decorate([
  31056. BABYLON.serializeAsTexture(),
  31057. BABYLON.expandToProperty(null)
  31058. ], PBRMaterial.prototype, "bumpTexture", void 0);
  31059. __decorate([
  31060. BABYLON.serializeAsTexture(),
  31061. BABYLON.expandToProperty(null)
  31062. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  31063. __decorate([
  31064. BABYLON.serializeAsTexture(),
  31065. BABYLON.expandToProperty(null)
  31066. ], PBRMaterial.prototype, "refractionTexture", void 0);
  31067. __decorate([
  31068. BABYLON.serializeAsColor3("ambient"),
  31069. BABYLON.expandToProperty(null)
  31070. ], PBRMaterial.prototype, "ambientColor", void 0);
  31071. __decorate([
  31072. BABYLON.serializeAsColor3("albedo"),
  31073. BABYLON.expandToProperty(null)
  31074. ], PBRMaterial.prototype, "albedoColor", void 0);
  31075. __decorate([
  31076. BABYLON.serializeAsColor3("reflectivity"),
  31077. BABYLON.expandToProperty(null)
  31078. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  31079. __decorate([
  31080. BABYLON.serializeAsColor3("reflection"),
  31081. BABYLON.expandToProperty(null)
  31082. ], PBRMaterial.prototype, "reflectionColor", void 0);
  31083. __decorate([
  31084. BABYLON.serializeAsColor3("emissive"),
  31085. BABYLON.expandToProperty(null)
  31086. ], PBRMaterial.prototype, "emissiveColor", void 0);
  31087. __decorate([
  31088. BABYLON.serialize(),
  31089. BABYLON.expandToProperty(null)
  31090. ], PBRMaterial.prototype, "microSurface", void 0);
  31091. __decorate([
  31092. BABYLON.serialize(),
  31093. BABYLON.expandToProperty(null)
  31094. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  31095. __decorate([
  31096. BABYLON.serialize(),
  31097. BABYLON.expandToProperty(null)
  31098. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  31099. __decorate([
  31100. BABYLON.serializeAsFresnelParameters(),
  31101. BABYLON.expandToProperty(null)
  31102. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  31103. __decorate([
  31104. BABYLON.serializeAsFresnelParameters(),
  31105. BABYLON.expandToProperty(null)
  31106. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  31107. __decorate([
  31108. BABYLON.serialize(),
  31109. BABYLON.expandToProperty(null)
  31110. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  31111. __decorate([
  31112. BABYLON.serialize(),
  31113. BABYLON.expandToProperty(null)
  31114. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31115. __decorate([
  31116. BABYLON.serialize(),
  31117. BABYLON.expandToProperty(null)
  31118. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31119. __decorate([
  31120. BABYLON.serialize(),
  31121. BABYLON.expandToProperty(null)
  31122. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  31123. __decorate([
  31124. BABYLON.serialize(),
  31125. BABYLON.expandToProperty(null)
  31126. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  31127. __decorate([
  31128. BABYLON.serialize(),
  31129. BABYLON.expandToProperty(null)
  31130. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  31131. __decorate([
  31132. BABYLON.serialize(),
  31133. BABYLON.expandToProperty(null)
  31134. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  31135. __decorate([
  31136. BABYLON.serialize(),
  31137. BABYLON.expandToProperty(null)
  31138. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  31139. __decorate([
  31140. BABYLON.serialize(),
  31141. BABYLON.expandToProperty(null)
  31142. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  31143. __decorate([
  31144. BABYLON.serialize(),
  31145. BABYLON.expandToProperty(null)
  31146. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  31147. __decorate([
  31148. BABYLON.serialize(),
  31149. BABYLON.expandToProperty(null)
  31150. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  31151. __decorate([
  31152. BABYLON.serialize(),
  31153. BABYLON.expandToProperty(null)
  31154. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  31155. __decorate([
  31156. BABYLON.serialize(),
  31157. BABYLON.expandToProperty(null)
  31158. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  31159. __decorate([
  31160. BABYLON.serialize(),
  31161. BABYLON.expandToProperty(null)
  31162. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  31163. __decorate([
  31164. BABYLON.serialize(),
  31165. BABYLON.expandToProperty(null)
  31166. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  31167. __decorate([
  31168. BABYLON.serialize(),
  31169. BABYLON.expandToProperty(null)
  31170. ], PBRMaterial.prototype, "useParallax", void 0);
  31171. __decorate([
  31172. BABYLON.serialize(),
  31173. BABYLON.expandToProperty(null)
  31174. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  31175. __decorate([
  31176. BABYLON.serialize(),
  31177. BABYLON.expandToProperty(null)
  31178. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  31179. __decorate([
  31180. BABYLON.serialize(),
  31181. BABYLON.expandToProperty(null)
  31182. ], PBRMaterial.prototype, "disableLighting", void 0);
  31183. __decorate([
  31184. BABYLON.serialize(),
  31185. BABYLON.expandToProperty(null)
  31186. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  31187. __decorate([
  31188. BABYLON.serialize(),
  31189. BABYLON.expandToProperty(null)
  31190. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  31191. __decorate([
  31192. BABYLON.serialize(),
  31193. BABYLON.expandToProperty(null)
  31194. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  31195. __decorate([
  31196. BABYLON.serialize(),
  31197. BABYLON.expandToProperty(null)
  31198. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  31199. BABYLON.PBRMaterial = PBRMaterial;
  31200. })(BABYLON || (BABYLON = {}));
  31201. //# sourceMappingURL=babylon.pbrMaterial.js.map
  31202. var BABYLON;
  31203. (function (BABYLON) {
  31204. /**
  31205. * The PBR material of BJS following the metal roughness convention.
  31206. *
  31207. * This fits to the define PBR convention in the GLTF definition:
  31208. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  31209. */
  31210. var PBRMetallicRoughnessMaterial = (function (_super) {
  31211. __extends(PBRMetallicRoughnessMaterial, _super);
  31212. /**
  31213. * Instantiates a new PBRMetalRoughnessMaterial instance.
  31214. *
  31215. * @param name The material name
  31216. * @param scene The scene the material will be use in.
  31217. */
  31218. function PBRMetallicRoughnessMaterial(name, scene) {
  31219. var _this = _super.call(this, name, scene) || this;
  31220. _this._useRoughnessFromMetallicTextureGreen = true;
  31221. _this._useMetallnessFromMetallicTextureBlue = true;
  31222. return _this;
  31223. }
  31224. /**
  31225. * Return the currrent class name of the material.
  31226. */
  31227. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  31228. return "PBRMetallicRoughnessMaterial";
  31229. };
  31230. /**
  31231. * Serialize the material to a parsable JSON object.
  31232. */
  31233. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  31234. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31235. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  31236. return serializationObject;
  31237. };
  31238. /**
  31239. * Parses a JSON object correponding to the serialize function.
  31240. */
  31241. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  31242. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  31243. };
  31244. return PBRMetallicRoughnessMaterial;
  31245. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31246. __decorate([
  31247. BABYLON.serializeAsTexture(),
  31248. BABYLON.expandToProperty(null, "_albedoColor")
  31249. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  31250. __decorate([
  31251. BABYLON.serializeAsTexture(),
  31252. BABYLON.expandToProperty(null, "_albedoTexture")
  31253. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  31254. __decorate([
  31255. BABYLON.serialize(),
  31256. BABYLON.expandToProperty(null)
  31257. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  31258. __decorate([
  31259. BABYLON.serialize(),
  31260. BABYLON.expandToProperty(null)
  31261. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  31262. __decorate([
  31263. BABYLON.serializeAsTexture(),
  31264. BABYLON.expandToProperty(null, "_metallicTexture")
  31265. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  31266. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  31267. })(BABYLON || (BABYLON = {}));
  31268. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  31269. var BABYLON;
  31270. (function (BABYLON) {
  31271. /**
  31272. * The PBR material of BJS following the specular glossiness convention.
  31273. *
  31274. * This fits to the define PBR convention in the GLTF definition:
  31275. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  31276. */
  31277. var PBRSpecularGlossinessMaterial = (function (_super) {
  31278. __extends(PBRSpecularGlossinessMaterial, _super);
  31279. /**
  31280. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  31281. *
  31282. * @param name The material name
  31283. * @param scene The scene the material will be use in.
  31284. */
  31285. function PBRSpecularGlossinessMaterial(name, scene) {
  31286. var _this = _super.call(this, name, scene) || this;
  31287. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  31288. return _this;
  31289. }
  31290. /**
  31291. * Return the currrent class name of the material.
  31292. */
  31293. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  31294. return "PBRSpecularGlossinessMaterial";
  31295. };
  31296. /**
  31297. * Serialize the material to a parsable JSON object.
  31298. */
  31299. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  31300. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31301. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  31302. return serializationObject;
  31303. };
  31304. /**
  31305. * Parses a JSON object correponding to the serialize function.
  31306. */
  31307. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  31308. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  31309. };
  31310. return PBRSpecularGlossinessMaterial;
  31311. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31312. __decorate([
  31313. BABYLON.serializeAsColor3(),
  31314. BABYLON.expandToProperty(null, "_albedoColor")
  31315. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  31316. __decorate([
  31317. BABYLON.serializeAsTexture(),
  31318. BABYLON.expandToProperty(null, "_albedoTexture")
  31319. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  31320. __decorate([
  31321. BABYLON.serializeAsColor3(),
  31322. BABYLON.expandToProperty(null, "_reflectivityColor")
  31323. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  31324. __decorate([
  31325. BABYLON.serialize(),
  31326. BABYLON.expandToProperty(null, "_microSurface")
  31327. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  31328. __decorate([
  31329. BABYLON.serializeAsTexture(),
  31330. BABYLON.expandToProperty(null, "_reflectivityTexture")
  31331. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  31332. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  31333. })(BABYLON || (BABYLON = {}));
  31334. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  31335. var BABYLON;
  31336. (function (BABYLON) {
  31337. BABYLON.CameraInputTypes = {};
  31338. var CameraInputsManager = (function () {
  31339. function CameraInputsManager(camera) {
  31340. this.attached = {};
  31341. this.camera = camera;
  31342. this.checkInputs = function () { };
  31343. }
  31344. CameraInputsManager.prototype.add = function (input) {
  31345. var type = input.getSimpleName();
  31346. if (this.attached[type]) {
  31347. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31348. return;
  31349. }
  31350. this.attached[type] = input;
  31351. input.camera = this.camera;
  31352. //for checkInputs, we are dynamically creating a function
  31353. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31354. if (input.checkInputs) {
  31355. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31356. }
  31357. if (this.attachedElement) {
  31358. input.attachControl(this.attachedElement);
  31359. }
  31360. };
  31361. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31362. for (var cam in this.attached) {
  31363. var input = this.attached[cam];
  31364. if (input === inputToRemove) {
  31365. input.detachControl(this.attachedElement);
  31366. delete this.attached[cam];
  31367. this.rebuildInputCheck();
  31368. }
  31369. }
  31370. };
  31371. CameraInputsManager.prototype.removeByType = function (inputType) {
  31372. for (var cam in this.attached) {
  31373. var input = this.attached[cam];
  31374. if (input.getTypeName() === inputType) {
  31375. input.detachControl(this.attachedElement);
  31376. delete this.attached[cam];
  31377. this.rebuildInputCheck();
  31378. }
  31379. }
  31380. };
  31381. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31382. var current = this.checkInputs;
  31383. return function () {
  31384. current();
  31385. fn();
  31386. };
  31387. };
  31388. CameraInputsManager.prototype.attachInput = function (input) {
  31389. input.attachControl(this.attachedElement, this.noPreventDefault);
  31390. };
  31391. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31392. if (this.attachedElement) {
  31393. return;
  31394. }
  31395. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31396. this.attachedElement = element;
  31397. this.noPreventDefault = noPreventDefault;
  31398. for (var cam in this.attached) {
  31399. var input = this.attached[cam];
  31400. this.attached[cam].attachControl(element, noPreventDefault);
  31401. }
  31402. };
  31403. CameraInputsManager.prototype.detachElement = function (element) {
  31404. if (this.attachedElement !== element) {
  31405. return;
  31406. }
  31407. for (var cam in this.attached) {
  31408. var input = this.attached[cam];
  31409. this.attached[cam].detachControl(element);
  31410. }
  31411. this.attachedElement = null;
  31412. };
  31413. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31414. this.checkInputs = function () { };
  31415. for (var cam in this.attached) {
  31416. var input = this.attached[cam];
  31417. if (input.checkInputs) {
  31418. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31419. }
  31420. }
  31421. };
  31422. CameraInputsManager.prototype.clear = function () {
  31423. if (this.attachedElement) {
  31424. this.detachElement(this.attachedElement);
  31425. }
  31426. this.attached = {};
  31427. this.attachedElement = null;
  31428. this.checkInputs = function () { };
  31429. };
  31430. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31431. var inputs = {};
  31432. for (var cam in this.attached) {
  31433. var input = this.attached[cam];
  31434. var res = BABYLON.SerializationHelper.Serialize(input);
  31435. inputs[input.getTypeName()] = res;
  31436. }
  31437. serializedCamera.inputsmgr = inputs;
  31438. };
  31439. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31440. var parsedInputs = parsedCamera.inputsmgr;
  31441. if (parsedInputs) {
  31442. this.clear();
  31443. for (var n in parsedInputs) {
  31444. var construct = BABYLON.CameraInputTypes[n];
  31445. if (construct) {
  31446. var parsedinput = parsedInputs[n];
  31447. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31448. this.add(input);
  31449. }
  31450. }
  31451. }
  31452. else {
  31453. //2016-03-08 this part is for managing backward compatibility
  31454. for (var n in this.attached) {
  31455. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31456. if (construct) {
  31457. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31458. this.remove(this.attached[n]);
  31459. this.add(input);
  31460. }
  31461. }
  31462. }
  31463. };
  31464. return CameraInputsManager;
  31465. }());
  31466. BABYLON.CameraInputsManager = CameraInputsManager;
  31467. })(BABYLON || (BABYLON = {}));
  31468. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31469. var BABYLON;
  31470. (function (BABYLON) {
  31471. var FreeCameraMouseInput = (function () {
  31472. function FreeCameraMouseInput(touchEnabled) {
  31473. if (touchEnabled === void 0) { touchEnabled = true; }
  31474. this.touchEnabled = touchEnabled;
  31475. this.buttons = [0, 1, 2];
  31476. this.angularSensibility = 2000.0;
  31477. }
  31478. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  31479. var _this = this;
  31480. var engine = this.camera.getEngine();
  31481. if (!this._pointerInput) {
  31482. this._pointerInput = function (p, s) {
  31483. var evt = p.event;
  31484. if (!_this.touchEnabled && evt.pointerType === "touch") {
  31485. return;
  31486. }
  31487. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31488. return;
  31489. }
  31490. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31491. try {
  31492. evt.srcElement.setPointerCapture(evt.pointerId);
  31493. }
  31494. catch (e) {
  31495. //Nothing to do with the error. Execution will continue.
  31496. }
  31497. _this.previousPosition = {
  31498. x: evt.clientX,
  31499. y: evt.clientY
  31500. };
  31501. if (!noPreventDefault) {
  31502. evt.preventDefault();
  31503. element.focus();
  31504. }
  31505. }
  31506. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31507. try {
  31508. evt.srcElement.releasePointerCapture(evt.pointerId);
  31509. }
  31510. catch (e) {
  31511. //Nothing to do with the error.
  31512. }
  31513. _this.previousPosition = null;
  31514. if (!noPreventDefault) {
  31515. evt.preventDefault();
  31516. }
  31517. }
  31518. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31519. if (!_this.previousPosition || engine.isPointerLock) {
  31520. return;
  31521. }
  31522. var offsetX = evt.clientX - _this.previousPosition.x;
  31523. var offsetY = evt.clientY - _this.previousPosition.y;
  31524. if (_this.camera.getScene().useRightHandedSystem) {
  31525. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31526. }
  31527. else {
  31528. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31529. }
  31530. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31531. _this.previousPosition = {
  31532. x: evt.clientX,
  31533. y: evt.clientY
  31534. };
  31535. if (!noPreventDefault) {
  31536. evt.preventDefault();
  31537. }
  31538. }
  31539. };
  31540. }
  31541. this._onMouseMove = function (evt) {
  31542. if (!engine.isPointerLock) {
  31543. return;
  31544. }
  31545. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31546. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31547. if (_this.camera.getScene().useRightHandedSystem) {
  31548. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31549. }
  31550. else {
  31551. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31552. }
  31553. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31554. _this.previousPosition = null;
  31555. if (!noPreventDefault) {
  31556. evt.preventDefault();
  31557. }
  31558. };
  31559. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31560. element.addEventListener("mousemove", this._onMouseMove, false);
  31561. };
  31562. FreeCameraMouseInput.prototype.detachControl = function (element) {
  31563. if (this._observer && element) {
  31564. this.camera.getScene().onPointerObservable.remove(this._observer);
  31565. element.removeEventListener("mousemove", this._onMouseMove);
  31566. this._observer = null;
  31567. this._onMouseMove = null;
  31568. this.previousPosition = null;
  31569. }
  31570. };
  31571. FreeCameraMouseInput.prototype.getTypeName = function () {
  31572. return "FreeCameraMouseInput";
  31573. };
  31574. FreeCameraMouseInput.prototype.getSimpleName = function () {
  31575. return "mouse";
  31576. };
  31577. return FreeCameraMouseInput;
  31578. }());
  31579. __decorate([
  31580. BABYLON.serialize()
  31581. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  31582. __decorate([
  31583. BABYLON.serialize()
  31584. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  31585. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  31586. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  31587. })(BABYLON || (BABYLON = {}));
  31588. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  31589. var BABYLON;
  31590. (function (BABYLON) {
  31591. var FreeCameraKeyboardMoveInput = (function () {
  31592. function FreeCameraKeyboardMoveInput() {
  31593. this._keys = [];
  31594. this.keysUp = [38];
  31595. this.keysDown = [40];
  31596. this.keysLeft = [37];
  31597. this.keysRight = [39];
  31598. }
  31599. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31600. var _this = this;
  31601. if (!this._onKeyDown) {
  31602. element.tabIndex = 1;
  31603. this._onKeyDown = function (evt) {
  31604. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31605. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31606. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31607. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31608. var index = _this._keys.indexOf(evt.keyCode);
  31609. if (index === -1) {
  31610. _this._keys.push(evt.keyCode);
  31611. }
  31612. if (!noPreventDefault) {
  31613. evt.preventDefault();
  31614. }
  31615. }
  31616. };
  31617. this._onKeyUp = function (evt) {
  31618. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31619. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31620. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31621. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31622. var index = _this._keys.indexOf(evt.keyCode);
  31623. if (index >= 0) {
  31624. _this._keys.splice(index, 1);
  31625. }
  31626. if (!noPreventDefault) {
  31627. evt.preventDefault();
  31628. }
  31629. }
  31630. };
  31631. element.addEventListener("keydown", this._onKeyDown, false);
  31632. element.addEventListener("keyup", this._onKeyUp, false);
  31633. BABYLON.Tools.RegisterTopRootEvents([
  31634. { name: "blur", handler: this._onLostFocus }
  31635. ]);
  31636. }
  31637. };
  31638. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31639. if (this._onKeyDown) {
  31640. element.removeEventListener("keydown", this._onKeyDown);
  31641. element.removeEventListener("keyup", this._onKeyUp);
  31642. BABYLON.Tools.UnregisterTopRootEvents([
  31643. { name: "blur", handler: this._onLostFocus }
  31644. ]);
  31645. this._keys = [];
  31646. this._onKeyDown = null;
  31647. this._onKeyUp = null;
  31648. }
  31649. };
  31650. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31651. if (this._onKeyDown) {
  31652. var camera = this.camera;
  31653. // Keyboard
  31654. for (var index = 0; index < this._keys.length; index++) {
  31655. var keyCode = this._keys[index];
  31656. var speed = camera._computeLocalCameraSpeed();
  31657. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31658. camera._localDirection.copyFromFloats(-speed, 0, 0);
  31659. }
  31660. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31661. camera._localDirection.copyFromFloats(0, 0, speed);
  31662. }
  31663. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31664. camera._localDirection.copyFromFloats(speed, 0, 0);
  31665. }
  31666. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31667. camera._localDirection.copyFromFloats(0, 0, -speed);
  31668. }
  31669. if (camera.getScene().useRightHandedSystem) {
  31670. camera._localDirection.z *= -1;
  31671. }
  31672. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  31673. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  31674. camera.cameraDirection.addInPlace(camera._transformedDirection);
  31675. }
  31676. }
  31677. };
  31678. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31679. return "FreeCameraKeyboardMoveInput";
  31680. };
  31681. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  31682. this._keys = [];
  31683. };
  31684. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31685. return "keyboard";
  31686. };
  31687. return FreeCameraKeyboardMoveInput;
  31688. }());
  31689. __decorate([
  31690. BABYLON.serialize()
  31691. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31692. __decorate([
  31693. BABYLON.serialize()
  31694. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31695. __decorate([
  31696. BABYLON.serialize()
  31697. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31698. __decorate([
  31699. BABYLON.serialize()
  31700. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31701. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  31702. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  31703. })(BABYLON || (BABYLON = {}));
  31704. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  31705. var BABYLON;
  31706. (function (BABYLON) {
  31707. var FreeCameraInputsManager = (function (_super) {
  31708. __extends(FreeCameraInputsManager, _super);
  31709. function FreeCameraInputsManager(camera) {
  31710. return _super.call(this, camera) || this;
  31711. }
  31712. FreeCameraInputsManager.prototype.addKeyboard = function () {
  31713. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  31714. return this;
  31715. };
  31716. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  31717. if (touchEnabled === void 0) { touchEnabled = true; }
  31718. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  31719. return this;
  31720. };
  31721. FreeCameraInputsManager.prototype.addGamepad = function () {
  31722. this.add(new BABYLON.FreeCameraGamepadInput());
  31723. return this;
  31724. };
  31725. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  31726. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  31727. return this;
  31728. };
  31729. FreeCameraInputsManager.prototype.addTouch = function () {
  31730. this.add(new BABYLON.FreeCameraTouchInput());
  31731. return this;
  31732. };
  31733. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  31734. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  31735. return this;
  31736. };
  31737. return FreeCameraInputsManager;
  31738. }(BABYLON.CameraInputsManager));
  31739. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  31740. })(BABYLON || (BABYLON = {}));
  31741. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  31742. /// <reference path="babylon.camera.ts" />
  31743. var BABYLON;
  31744. (function (BABYLON) {
  31745. var TargetCamera = (function (_super) {
  31746. __extends(TargetCamera, _super);
  31747. function TargetCamera(name, position, scene) {
  31748. var _this = _super.call(this, name, position, scene) || this;
  31749. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31750. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31751. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31752. _this.speed = 2.0;
  31753. _this.noRotationConstraint = false;
  31754. _this.lockedTarget = null;
  31755. _this._currentTarget = BABYLON.Vector3.Zero();
  31756. _this._viewMatrix = BABYLON.Matrix.Zero();
  31757. _this._camMatrix = BABYLON.Matrix.Zero();
  31758. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31759. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31760. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31761. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31762. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31763. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31764. _this._tempMatrix = BABYLON.Matrix.Zero();
  31765. return _this;
  31766. }
  31767. TargetCamera.prototype.getFrontPosition = function (distance) {
  31768. var direction = this.getTarget().subtract(this.position);
  31769. direction.normalize();
  31770. direction.scaleInPlace(distance);
  31771. return this.globalPosition.add(direction);
  31772. };
  31773. TargetCamera.prototype._getLockedTargetPosition = function () {
  31774. if (!this.lockedTarget) {
  31775. return null;
  31776. }
  31777. if (this.lockedTarget.absolutePosition) {
  31778. this.lockedTarget.computeWorldMatrix();
  31779. }
  31780. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31781. };
  31782. // Cache
  31783. TargetCamera.prototype._initCache = function () {
  31784. _super.prototype._initCache.call(this);
  31785. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31786. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31787. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31788. };
  31789. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31790. if (!ignoreParentClass) {
  31791. _super.prototype._updateCache.call(this);
  31792. }
  31793. var lockedTargetPosition = this._getLockedTargetPosition();
  31794. if (!lockedTargetPosition) {
  31795. this._cache.lockedTarget = null;
  31796. }
  31797. else {
  31798. if (!this._cache.lockedTarget) {
  31799. this._cache.lockedTarget = lockedTargetPosition.clone();
  31800. }
  31801. else {
  31802. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31803. }
  31804. }
  31805. this._cache.rotation.copyFrom(this.rotation);
  31806. if (this.rotationQuaternion)
  31807. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31808. };
  31809. // Synchronized
  31810. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31811. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31812. return false;
  31813. }
  31814. var lockedTargetPosition = this._getLockedTargetPosition();
  31815. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31816. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31817. };
  31818. // Methods
  31819. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31820. var engine = this.getEngine();
  31821. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31822. };
  31823. // Target
  31824. TargetCamera.prototype.setTarget = function (target) {
  31825. this.upVector.normalize();
  31826. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31827. this._camMatrix.invert();
  31828. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31829. var vDir = target.subtract(this.position);
  31830. if (vDir.x >= 0.0) {
  31831. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31832. }
  31833. else {
  31834. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31835. }
  31836. this.rotation.z = 0;
  31837. if (isNaN(this.rotation.x)) {
  31838. this.rotation.x = 0;
  31839. }
  31840. if (isNaN(this.rotation.y)) {
  31841. this.rotation.y = 0;
  31842. }
  31843. if (isNaN(this.rotation.z)) {
  31844. this.rotation.z = 0;
  31845. }
  31846. if (this.rotationQuaternion) {
  31847. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31848. }
  31849. };
  31850. /**
  31851. * Return the current target position of the camera. This value is expressed in local space.
  31852. */
  31853. TargetCamera.prototype.getTarget = function () {
  31854. return this._currentTarget;
  31855. };
  31856. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31857. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31858. };
  31859. TargetCamera.prototype._updatePosition = function () {
  31860. if (this.parent) {
  31861. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31862. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31863. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31864. return;
  31865. }
  31866. this.position.addInPlace(this.cameraDirection);
  31867. };
  31868. TargetCamera.prototype._checkInputs = function () {
  31869. var needToMove = this._decideIfNeedsToMove();
  31870. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31871. // Move
  31872. if (needToMove) {
  31873. this._updatePosition();
  31874. }
  31875. // Rotate
  31876. if (needToRotate) {
  31877. this.rotation.x += this.cameraRotation.x;
  31878. this.rotation.y += this.cameraRotation.y;
  31879. //rotate, if quaternion is set and rotation was used
  31880. if (this.rotationQuaternion) {
  31881. var len = this.rotation.lengthSquared();
  31882. if (len) {
  31883. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31884. }
  31885. }
  31886. if (!this.noRotationConstraint) {
  31887. var limit = (Math.PI / 2) * 0.95;
  31888. if (this.rotation.x > limit)
  31889. this.rotation.x = limit;
  31890. if (this.rotation.x < -limit)
  31891. this.rotation.x = -limit;
  31892. }
  31893. }
  31894. // Inertia
  31895. if (needToMove) {
  31896. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31897. this.cameraDirection.x = 0;
  31898. }
  31899. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31900. this.cameraDirection.y = 0;
  31901. }
  31902. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31903. this.cameraDirection.z = 0;
  31904. }
  31905. this.cameraDirection.scaleInPlace(this.inertia);
  31906. }
  31907. if (needToRotate) {
  31908. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31909. this.cameraRotation.x = 0;
  31910. }
  31911. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31912. this.cameraRotation.y = 0;
  31913. }
  31914. this.cameraRotation.scaleInPlace(this.inertia);
  31915. }
  31916. _super.prototype._checkInputs.call(this);
  31917. };
  31918. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31919. if (this.rotationQuaternion) {
  31920. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31921. //update the up vector!
  31922. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31923. }
  31924. else {
  31925. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31926. }
  31927. };
  31928. TargetCamera.prototype._getViewMatrix = function () {
  31929. if (!this.lockedTarget) {
  31930. // Compute
  31931. this._updateCameraRotationMatrix();
  31932. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31933. // Computing target and final matrix
  31934. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31935. }
  31936. else {
  31937. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31938. }
  31939. if (this.getScene().useRightHandedSystem) {
  31940. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31941. }
  31942. else {
  31943. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31944. }
  31945. return this._viewMatrix;
  31946. };
  31947. /**
  31948. * @override
  31949. * Override Camera.createRigCamera
  31950. */
  31951. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31952. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31953. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31954. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31955. if (!this.rotationQuaternion) {
  31956. this.rotationQuaternion = new BABYLON.Quaternion();
  31957. }
  31958. rigCamera._cameraRigParams = {};
  31959. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31960. }
  31961. return rigCamera;
  31962. }
  31963. return null;
  31964. };
  31965. /**
  31966. * @override
  31967. * Override Camera._updateRigCameras
  31968. */
  31969. TargetCamera.prototype._updateRigCameras = function () {
  31970. var camLeft = this._rigCameras[0];
  31971. var camRight = this._rigCameras[1];
  31972. switch (this.cameraRigMode) {
  31973. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31975. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31976. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31977. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31978. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31979. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31980. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31981. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31982. camLeft.setTarget(this.getTarget());
  31983. camRight.setTarget(this.getTarget());
  31984. break;
  31985. case BABYLON.Camera.RIG_MODE_VR:
  31986. if (camLeft.rotationQuaternion) {
  31987. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31988. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31989. }
  31990. else {
  31991. camLeft.rotation.copyFrom(this.rotation);
  31992. camRight.rotation.copyFrom(this.rotation);
  31993. }
  31994. camLeft.position.copyFrom(this.position);
  31995. camRight.position.copyFrom(this.position);
  31996. break;
  31997. }
  31998. _super.prototype._updateRigCameras.call(this);
  31999. };
  32000. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  32001. if (!this._rigCamTransformMatrix) {
  32002. this._rigCamTransformMatrix = new BABYLON.Matrix();
  32003. }
  32004. var target = this.getTarget();
  32005. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  32006. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  32007. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  32008. };
  32009. TargetCamera.prototype.getClassName = function () {
  32010. return "TargetCamera";
  32011. };
  32012. return TargetCamera;
  32013. }(BABYLON.Camera));
  32014. __decorate([
  32015. BABYLON.serializeAsVector3()
  32016. ], TargetCamera.prototype, "rotation", void 0);
  32017. __decorate([
  32018. BABYLON.serialize()
  32019. ], TargetCamera.prototype, "speed", void 0);
  32020. __decorate([
  32021. BABYLON.serializeAsMeshReference("lockedTargetId")
  32022. ], TargetCamera.prototype, "lockedTarget", void 0);
  32023. BABYLON.TargetCamera = TargetCamera;
  32024. })(BABYLON || (BABYLON = {}));
  32025. //# sourceMappingURL=babylon.targetCamera.js.map
  32026. var BABYLON;
  32027. (function (BABYLON) {
  32028. var FreeCamera = (function (_super) {
  32029. __extends(FreeCamera, _super);
  32030. function FreeCamera(name, position, scene) {
  32031. var _this = _super.call(this, name, position, scene) || this;
  32032. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  32033. _this.checkCollisions = false;
  32034. _this.applyGravity = false;
  32035. _this._needMoveForGravity = false;
  32036. _this._oldPosition = BABYLON.Vector3.Zero();
  32037. _this._diffPosition = BABYLON.Vector3.Zero();
  32038. _this._newPosition = BABYLON.Vector3.Zero();
  32039. // Collisions
  32040. _this._collisionMask = -1;
  32041. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32042. if (collidedMesh === void 0) { collidedMesh = null; }
  32043. //TODO move this to the collision coordinator!
  32044. if (_this.getScene().workerCollisions)
  32045. newPosition.multiplyInPlace(_this._collider.radius);
  32046. var updatePosition = function (newPos) {
  32047. _this._newPosition.copyFrom(newPos);
  32048. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  32049. var oldPosition = _this.position.clone();
  32050. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  32051. _this.position.addInPlace(_this._diffPosition);
  32052. if (_this.onCollide && collidedMesh) {
  32053. _this.onCollide(collidedMesh);
  32054. }
  32055. }
  32056. };
  32057. updatePosition(newPosition);
  32058. };
  32059. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  32060. _this.inputs.addKeyboard().addMouse();
  32061. return _this;
  32062. }
  32063. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  32064. //-- begin properties for backward compatibility for inputs
  32065. get: function () {
  32066. var mouse = this.inputs.attached["mouse"];
  32067. if (mouse)
  32068. return mouse.angularSensibility;
  32069. },
  32070. set: function (value) {
  32071. var mouse = this.inputs.attached["mouse"];
  32072. if (mouse)
  32073. mouse.angularSensibility = value;
  32074. },
  32075. enumerable: true,
  32076. configurable: true
  32077. });
  32078. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  32079. get: function () {
  32080. var keyboard = this.inputs.attached["keyboard"];
  32081. if (keyboard)
  32082. return keyboard.keysUp;
  32083. },
  32084. set: function (value) {
  32085. var keyboard = this.inputs.attached["keyboard"];
  32086. if (keyboard)
  32087. keyboard.keysUp = value;
  32088. },
  32089. enumerable: true,
  32090. configurable: true
  32091. });
  32092. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  32093. get: function () {
  32094. var keyboard = this.inputs.attached["keyboard"];
  32095. if (keyboard)
  32096. return keyboard.keysDown;
  32097. },
  32098. set: function (value) {
  32099. var keyboard = this.inputs.attached["keyboard"];
  32100. if (keyboard)
  32101. keyboard.keysDown = value;
  32102. },
  32103. enumerable: true,
  32104. configurable: true
  32105. });
  32106. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  32107. get: function () {
  32108. var keyboard = this.inputs.attached["keyboard"];
  32109. if (keyboard)
  32110. return keyboard.keysLeft;
  32111. },
  32112. set: function (value) {
  32113. var keyboard = this.inputs.attached["keyboard"];
  32114. if (keyboard)
  32115. keyboard.keysLeft = value;
  32116. },
  32117. enumerable: true,
  32118. configurable: true
  32119. });
  32120. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  32121. get: function () {
  32122. var keyboard = this.inputs.attached["keyboard"];
  32123. if (keyboard)
  32124. return keyboard.keysRight;
  32125. },
  32126. set: function (value) {
  32127. var keyboard = this.inputs.attached["keyboard"];
  32128. if (keyboard)
  32129. keyboard.keysRight = value;
  32130. },
  32131. enumerable: true,
  32132. configurable: true
  32133. });
  32134. // Controls
  32135. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32136. this.inputs.attachElement(element, noPreventDefault);
  32137. };
  32138. FreeCamera.prototype.detachControl = function (element) {
  32139. this.inputs.detachElement(element);
  32140. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32141. this.cameraRotation = new BABYLON.Vector2(0, 0);
  32142. };
  32143. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  32144. get: function () {
  32145. return this._collisionMask;
  32146. },
  32147. set: function (mask) {
  32148. this._collisionMask = !isNaN(mask) ? mask : -1;
  32149. },
  32150. enumerable: true,
  32151. configurable: true
  32152. });
  32153. FreeCamera.prototype._collideWithWorld = function (velocity) {
  32154. var globalPosition;
  32155. if (this.parent) {
  32156. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  32157. }
  32158. else {
  32159. globalPosition = this.position;
  32160. }
  32161. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  32162. if (!this._collider) {
  32163. this._collider = new BABYLON.Collider();
  32164. }
  32165. this._collider.radius = this.ellipsoid;
  32166. this._collider.collisionMask = this._collisionMask;
  32167. //no need for clone, as long as gravity is not on.
  32168. var actualVelocity = velocity;
  32169. //add gravity to the velocity to prevent the dual-collision checking
  32170. if (this.applyGravity) {
  32171. //this prevents mending with cameraDirection, a global variable of the free camera class.
  32172. actualVelocity = velocity.add(this.getScene().gravity);
  32173. }
  32174. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32175. };
  32176. FreeCamera.prototype._checkInputs = function () {
  32177. if (!this._localDirection) {
  32178. this._localDirection = BABYLON.Vector3.Zero();
  32179. this._transformedDirection = BABYLON.Vector3.Zero();
  32180. }
  32181. this.inputs.checkInputs();
  32182. _super.prototype._checkInputs.call(this);
  32183. };
  32184. FreeCamera.prototype._decideIfNeedsToMove = function () {
  32185. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32186. };
  32187. FreeCamera.prototype._updatePosition = function () {
  32188. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  32189. this._collideWithWorld(this.cameraDirection);
  32190. }
  32191. else {
  32192. _super.prototype._updatePosition.call(this);
  32193. }
  32194. };
  32195. FreeCamera.prototype.dispose = function () {
  32196. this.inputs.clear();
  32197. _super.prototype.dispose.call(this);
  32198. };
  32199. FreeCamera.prototype.getClassName = function () {
  32200. return "FreeCamera";
  32201. };
  32202. return FreeCamera;
  32203. }(BABYLON.TargetCamera));
  32204. __decorate([
  32205. BABYLON.serializeAsVector3()
  32206. ], FreeCamera.prototype, "ellipsoid", void 0);
  32207. __decorate([
  32208. BABYLON.serialize()
  32209. ], FreeCamera.prototype, "checkCollisions", void 0);
  32210. __decorate([
  32211. BABYLON.serialize()
  32212. ], FreeCamera.prototype, "applyGravity", void 0);
  32213. BABYLON.FreeCamera = FreeCamera;
  32214. })(BABYLON || (BABYLON = {}));
  32215. //# sourceMappingURL=babylon.freeCamera.js.map
  32216. var BABYLON;
  32217. (function (BABYLON) {
  32218. var ArcRotateCameraKeyboardMoveInput = (function () {
  32219. function ArcRotateCameraKeyboardMoveInput() {
  32220. this._keys = [];
  32221. this.keysUp = [38];
  32222. this.keysDown = [40];
  32223. this.keysLeft = [37];
  32224. this.keysRight = [39];
  32225. }
  32226. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32227. var _this = this;
  32228. element.tabIndex = 1;
  32229. this._onKeyDown = function (evt) {
  32230. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32231. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32232. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32233. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32234. var index = _this._keys.indexOf(evt.keyCode);
  32235. if (index === -1) {
  32236. _this._keys.push(evt.keyCode);
  32237. }
  32238. if (evt.preventDefault) {
  32239. if (!noPreventDefault) {
  32240. evt.preventDefault();
  32241. }
  32242. }
  32243. }
  32244. };
  32245. this._onKeyUp = function (evt) {
  32246. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32247. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32248. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32249. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32250. var index = _this._keys.indexOf(evt.keyCode);
  32251. if (index >= 0) {
  32252. _this._keys.splice(index, 1);
  32253. }
  32254. if (evt.preventDefault) {
  32255. if (!noPreventDefault) {
  32256. evt.preventDefault();
  32257. }
  32258. }
  32259. }
  32260. };
  32261. this._onLostFocus = function () {
  32262. _this._keys = [];
  32263. };
  32264. element.addEventListener("keydown", this._onKeyDown, false);
  32265. element.addEventListener("keyup", this._onKeyUp, false);
  32266. BABYLON.Tools.RegisterTopRootEvents([
  32267. { name: "blur", handler: this._onLostFocus }
  32268. ]);
  32269. };
  32270. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32271. if (element) {
  32272. element.removeEventListener("keydown", this._onKeyDown);
  32273. element.removeEventListener("keyup", this._onKeyUp);
  32274. }
  32275. BABYLON.Tools.UnregisterTopRootEvents([
  32276. { name: "blur", handler: this._onLostFocus }
  32277. ]);
  32278. this._keys = [];
  32279. this._onKeyDown = null;
  32280. this._onKeyUp = null;
  32281. this._onLostFocus = null;
  32282. };
  32283. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32284. if (this._onKeyDown) {
  32285. var camera = this.camera;
  32286. for (var index = 0; index < this._keys.length; index++) {
  32287. var keyCode = this._keys[index];
  32288. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32289. camera.inertialAlphaOffset -= 0.01;
  32290. }
  32291. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32292. camera.inertialBetaOffset -= 0.01;
  32293. }
  32294. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32295. camera.inertialAlphaOffset += 0.01;
  32296. }
  32297. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32298. camera.inertialBetaOffset += 0.01;
  32299. }
  32300. }
  32301. }
  32302. };
  32303. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32304. return "ArcRotateCameraKeyboardMoveInput";
  32305. };
  32306. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32307. return "keyboard";
  32308. };
  32309. return ArcRotateCameraKeyboardMoveInput;
  32310. }());
  32311. __decorate([
  32312. BABYLON.serialize()
  32313. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32314. __decorate([
  32315. BABYLON.serialize()
  32316. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32317. __decorate([
  32318. BABYLON.serialize()
  32319. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32320. __decorate([
  32321. BABYLON.serialize()
  32322. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32323. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32324. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32325. })(BABYLON || (BABYLON = {}));
  32326. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32327. var BABYLON;
  32328. (function (BABYLON) {
  32329. var ArcRotateCameraMouseWheelInput = (function () {
  32330. function ArcRotateCameraMouseWheelInput() {
  32331. this.wheelPrecision = 3.0;
  32332. }
  32333. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32334. var _this = this;
  32335. this._wheel = function (p, s) {
  32336. //sanity check - this should be a PointerWheel event.
  32337. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32338. return;
  32339. var event = p.event;
  32340. var delta = 0;
  32341. if (event.wheelDelta) {
  32342. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32343. }
  32344. else if (event.detail) {
  32345. delta = -event.detail / _this.wheelPrecision;
  32346. }
  32347. if (delta)
  32348. _this.camera.inertialRadiusOffset += delta;
  32349. if (event.preventDefault) {
  32350. if (!noPreventDefault) {
  32351. event.preventDefault();
  32352. }
  32353. }
  32354. };
  32355. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32356. };
  32357. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32358. if (this._observer && element) {
  32359. this.camera.getScene().onPointerObservable.remove(this._observer);
  32360. this._observer = null;
  32361. this._wheel = null;
  32362. }
  32363. };
  32364. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  32365. return "ArcRotateCameraMouseWheelInput";
  32366. };
  32367. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32368. return "mousewheel";
  32369. };
  32370. return ArcRotateCameraMouseWheelInput;
  32371. }());
  32372. __decorate([
  32373. BABYLON.serialize()
  32374. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32375. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32376. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32377. })(BABYLON || (BABYLON = {}));
  32378. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32379. var BABYLON;
  32380. (function (BABYLON) {
  32381. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32382. var ArcRotateCameraPointersInput = (function () {
  32383. function ArcRotateCameraPointersInput() {
  32384. this.buttons = [0, 1, 2];
  32385. this.angularSensibilityX = 1000.0;
  32386. this.angularSensibilityY = 1000.0;
  32387. this.pinchPrecision = 6.0;
  32388. this.panningSensibility = 50.0;
  32389. this._isPanClick = false;
  32390. this.pinchInwards = true;
  32391. }
  32392. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32393. var _this = this;
  32394. var engine = this.camera.getEngine();
  32395. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32396. var pointA, pointB;
  32397. var previousPinchDistance = 0;
  32398. this._pointerInput = function (p, s) {
  32399. var evt = p.event;
  32400. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32401. return;
  32402. }
  32403. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32404. try {
  32405. evt.srcElement.setPointerCapture(evt.pointerId);
  32406. }
  32407. catch (e) {
  32408. //Nothing to do with the error. Execution will continue.
  32409. }
  32410. // Manage panning with pan button click
  32411. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32412. // manage pointers
  32413. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32414. if (pointA === undefined) {
  32415. pointA = cacheSoloPointer;
  32416. }
  32417. else if (pointB === undefined) {
  32418. pointB = cacheSoloPointer;
  32419. }
  32420. if (!noPreventDefault) {
  32421. evt.preventDefault();
  32422. element.focus();
  32423. }
  32424. }
  32425. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32426. try {
  32427. evt.srcElement.releasePointerCapture(evt.pointerId);
  32428. }
  32429. catch (e) {
  32430. //Nothing to do with the error.
  32431. }
  32432. cacheSoloPointer = null;
  32433. previousPinchDistance = 0;
  32434. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32435. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32436. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32437. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32438. pointA = pointB = undefined;
  32439. if (!noPreventDefault) {
  32440. evt.preventDefault();
  32441. }
  32442. }
  32443. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32444. if (!noPreventDefault) {
  32445. evt.preventDefault();
  32446. }
  32447. // One button down
  32448. if (pointA && pointB === undefined) {
  32449. if (_this.panningSensibility !== 0 &&
  32450. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32451. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32452. _this.camera
  32453. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32454. _this.camera
  32455. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32456. }
  32457. else {
  32458. var offsetX = evt.clientX - cacheSoloPointer.x;
  32459. var offsetY = evt.clientY - cacheSoloPointer.y;
  32460. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32461. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32462. }
  32463. cacheSoloPointer.x = evt.clientX;
  32464. cacheSoloPointer.y = evt.clientY;
  32465. }
  32466. else if (pointA && pointB) {
  32467. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32468. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32469. ed.x = evt.clientX;
  32470. ed.y = evt.clientY;
  32471. var direction = _this.pinchInwards ? 1 : -1;
  32472. var distX = pointA.x - pointB.x;
  32473. var distY = pointA.y - pointB.y;
  32474. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32475. if (previousPinchDistance === 0) {
  32476. previousPinchDistance = pinchSquaredDistance;
  32477. return;
  32478. }
  32479. if (pinchSquaredDistance !== previousPinchDistance) {
  32480. _this.camera
  32481. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32482. (_this.pinchPrecision *
  32483. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32484. direction);
  32485. previousPinchDistance = pinchSquaredDistance;
  32486. }
  32487. }
  32488. }
  32489. };
  32490. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32491. this._onContextMenu = function (evt) {
  32492. evt.preventDefault();
  32493. };
  32494. if (!this.camera._useCtrlForPanning) {
  32495. element.addEventListener("contextmenu", this._onContextMenu, false);
  32496. }
  32497. this._onLostFocus = function () {
  32498. //this._keys = [];
  32499. pointA = pointB = undefined;
  32500. previousPinchDistance = 0;
  32501. cacheSoloPointer = null;
  32502. };
  32503. this._onMouseMove = function (evt) {
  32504. if (!engine.isPointerLock) {
  32505. return;
  32506. }
  32507. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32508. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32509. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32510. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32511. if (!noPreventDefault) {
  32512. evt.preventDefault();
  32513. }
  32514. };
  32515. this._onGestureStart = function (e) {
  32516. if (window.MSGesture === undefined) {
  32517. return;
  32518. }
  32519. if (!_this._MSGestureHandler) {
  32520. _this._MSGestureHandler = new MSGesture();
  32521. _this._MSGestureHandler.target = element;
  32522. }
  32523. _this._MSGestureHandler.addPointer(e.pointerId);
  32524. };
  32525. this._onGesture = function (e) {
  32526. _this.camera.radius *= e.scale;
  32527. if (e.preventDefault) {
  32528. if (!noPreventDefault) {
  32529. e.stopPropagation();
  32530. e.preventDefault();
  32531. }
  32532. }
  32533. };
  32534. element.addEventListener("mousemove", this._onMouseMove, false);
  32535. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32536. element.addEventListener("MSGestureChange", this._onGesture, false);
  32537. BABYLON.Tools.RegisterTopRootEvents([
  32538. { name: "blur", handler: this._onLostFocus }
  32539. ]);
  32540. };
  32541. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32542. if (element && this._observer) {
  32543. this.camera.getScene().onPointerObservable.remove(this._observer);
  32544. this._observer = null;
  32545. element.removeEventListener("contextmenu", this._onContextMenu);
  32546. element.removeEventListener("mousemove", this._onMouseMove);
  32547. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32548. element.removeEventListener("MSGestureChange", this._onGesture);
  32549. this._isPanClick = false;
  32550. this.pinchInwards = true;
  32551. this._onMouseMove = null;
  32552. this._onGestureStart = null;
  32553. this._onGesture = null;
  32554. this._MSGestureHandler = null;
  32555. this._onLostFocus = null;
  32556. this._onContextMenu = null;
  32557. }
  32558. BABYLON.Tools.UnregisterTopRootEvents([
  32559. { name: "blur", handler: this._onLostFocus }
  32560. ]);
  32561. };
  32562. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  32563. return "ArcRotateCameraPointersInput";
  32564. };
  32565. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32566. return "pointers";
  32567. };
  32568. return ArcRotateCameraPointersInput;
  32569. }());
  32570. __decorate([
  32571. BABYLON.serialize()
  32572. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32573. __decorate([
  32574. BABYLON.serialize()
  32575. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32576. __decorate([
  32577. BABYLON.serialize()
  32578. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32579. __decorate([
  32580. BABYLON.serialize()
  32581. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32582. __decorate([
  32583. BABYLON.serialize()
  32584. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32585. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32586. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32587. })(BABYLON || (BABYLON = {}));
  32588. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32589. /// <reference path="babylon.targetCamera.ts" />
  32590. /// <reference path="..\Tools\babylon.tools.ts" />
  32591. var BABYLON;
  32592. (function (BABYLON) {
  32593. var ArcRotateCamera = (function (_super) {
  32594. __extends(ArcRotateCamera, _super);
  32595. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32596. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32597. _this.inertialAlphaOffset = 0;
  32598. _this.inertialBetaOffset = 0;
  32599. _this.inertialRadiusOffset = 0;
  32600. _this.lowerAlphaLimit = null;
  32601. _this.upperAlphaLimit = null;
  32602. _this.lowerBetaLimit = 0.01;
  32603. _this.upperBetaLimit = Math.PI;
  32604. _this.lowerRadiusLimit = null;
  32605. _this.upperRadiusLimit = null;
  32606. _this.inertialPanningX = 0;
  32607. _this.inertialPanningY = 0;
  32608. _this.panningInertia = 0.9;
  32609. //-- end properties for backward compatibility for inputs
  32610. _this.zoomOnFactor = 1;
  32611. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32612. _this.allowUpsideDown = true;
  32613. _this._viewMatrix = new BABYLON.Matrix();
  32614. // Panning
  32615. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32616. _this.checkCollisions = false;
  32617. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32618. _this._previousPosition = BABYLON.Vector3.Zero();
  32619. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32620. _this._newPosition = BABYLON.Vector3.Zero();
  32621. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32622. if (collidedMesh === void 0) { collidedMesh = null; }
  32623. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32624. newPosition.multiplyInPlace(_this._collider.radius);
  32625. }
  32626. if (!collidedMesh) {
  32627. _this._previousPosition.copyFrom(_this.position);
  32628. }
  32629. else {
  32630. _this.setPosition(newPosition);
  32631. if (_this.onCollide) {
  32632. _this.onCollide(collidedMesh);
  32633. }
  32634. }
  32635. // Recompute because of constraints
  32636. var cosa = Math.cos(_this.alpha);
  32637. var sina = Math.sin(_this.alpha);
  32638. var cosb = Math.cos(_this.beta);
  32639. var sinb = Math.sin(_this.beta);
  32640. if (sinb === 0) {
  32641. sinb = 0.0001;
  32642. }
  32643. var target = _this._getTargetPosition();
  32644. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32645. _this.position.copyFrom(_this._newPosition);
  32646. var up = _this.upVector;
  32647. if (_this.allowUpsideDown && _this.beta < 0) {
  32648. up = up.clone();
  32649. up = up.negate();
  32650. }
  32651. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32652. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32653. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32654. _this._collisionTriggered = false;
  32655. };
  32656. _this._target = BABYLON.Vector3.Zero();
  32657. if (target) {
  32658. _this.setTarget(target);
  32659. }
  32660. _this.alpha = alpha;
  32661. _this.beta = beta;
  32662. _this.radius = radius;
  32663. _this.getViewMatrix();
  32664. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32665. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32666. return _this;
  32667. }
  32668. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32669. get: function () {
  32670. return this._target;
  32671. },
  32672. set: function (value) {
  32673. this.setTarget(value);
  32674. },
  32675. enumerable: true,
  32676. configurable: true
  32677. });
  32678. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32679. //-- begin properties for backward compatibility for inputs
  32680. get: function () {
  32681. var pointers = this.inputs.attached["pointers"];
  32682. if (pointers)
  32683. return pointers.angularSensibilityX;
  32684. },
  32685. set: function (value) {
  32686. var pointers = this.inputs.attached["pointers"];
  32687. if (pointers) {
  32688. pointers.angularSensibilityX = value;
  32689. }
  32690. },
  32691. enumerable: true,
  32692. configurable: true
  32693. });
  32694. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32695. get: function () {
  32696. var pointers = this.inputs.attached["pointers"];
  32697. if (pointers)
  32698. return pointers.angularSensibilityY;
  32699. },
  32700. set: function (value) {
  32701. var pointers = this.inputs.attached["pointers"];
  32702. if (pointers) {
  32703. pointers.angularSensibilityY = value;
  32704. }
  32705. },
  32706. enumerable: true,
  32707. configurable: true
  32708. });
  32709. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32710. get: function () {
  32711. var pointers = this.inputs.attached["pointers"];
  32712. if (pointers)
  32713. return pointers.pinchPrecision;
  32714. },
  32715. set: function (value) {
  32716. var pointers = this.inputs.attached["pointers"];
  32717. if (pointers) {
  32718. pointers.pinchPrecision = value;
  32719. }
  32720. },
  32721. enumerable: true,
  32722. configurable: true
  32723. });
  32724. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32725. get: function () {
  32726. var pointers = this.inputs.attached["pointers"];
  32727. if (pointers)
  32728. return pointers.panningSensibility;
  32729. },
  32730. set: function (value) {
  32731. var pointers = this.inputs.attached["pointers"];
  32732. if (pointers) {
  32733. pointers.panningSensibility = value;
  32734. }
  32735. },
  32736. enumerable: true,
  32737. configurable: true
  32738. });
  32739. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32740. get: function () {
  32741. var keyboard = this.inputs.attached["keyboard"];
  32742. if (keyboard)
  32743. return keyboard.keysUp;
  32744. },
  32745. set: function (value) {
  32746. var keyboard = this.inputs.attached["keyboard"];
  32747. if (keyboard)
  32748. keyboard.keysUp = value;
  32749. },
  32750. enumerable: true,
  32751. configurable: true
  32752. });
  32753. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32754. get: function () {
  32755. var keyboard = this.inputs.attached["keyboard"];
  32756. if (keyboard)
  32757. return keyboard.keysDown;
  32758. },
  32759. set: function (value) {
  32760. var keyboard = this.inputs.attached["keyboard"];
  32761. if (keyboard)
  32762. keyboard.keysDown = value;
  32763. },
  32764. enumerable: true,
  32765. configurable: true
  32766. });
  32767. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32768. get: function () {
  32769. var keyboard = this.inputs.attached["keyboard"];
  32770. if (keyboard)
  32771. return keyboard.keysLeft;
  32772. },
  32773. set: function (value) {
  32774. var keyboard = this.inputs.attached["keyboard"];
  32775. if (keyboard)
  32776. keyboard.keysLeft = value;
  32777. },
  32778. enumerable: true,
  32779. configurable: true
  32780. });
  32781. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32782. get: function () {
  32783. var keyboard = this.inputs.attached["keyboard"];
  32784. if (keyboard)
  32785. return keyboard.keysRight;
  32786. },
  32787. set: function (value) {
  32788. var keyboard = this.inputs.attached["keyboard"];
  32789. if (keyboard)
  32790. keyboard.keysRight = value;
  32791. },
  32792. enumerable: true,
  32793. configurable: true
  32794. });
  32795. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32796. get: function () {
  32797. var mousewheel = this.inputs.attached["mousewheel"];
  32798. if (mousewheel)
  32799. return mousewheel.wheelPrecision;
  32800. },
  32801. set: function (value) {
  32802. var mousewheel = this.inputs.attached["mousewheel"];
  32803. if (mousewheel)
  32804. mousewheel.wheelPrecision = value;
  32805. },
  32806. enumerable: true,
  32807. configurable: true
  32808. });
  32809. // Cache
  32810. ArcRotateCamera.prototype._initCache = function () {
  32811. _super.prototype._initCache.call(this);
  32812. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32813. this._cache.alpha = undefined;
  32814. this._cache.beta = undefined;
  32815. this._cache.radius = undefined;
  32816. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32817. };
  32818. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32819. if (!ignoreParentClass) {
  32820. _super.prototype._updateCache.call(this);
  32821. }
  32822. this._cache._target.copyFrom(this._getTargetPosition());
  32823. this._cache.alpha = this.alpha;
  32824. this._cache.beta = this.beta;
  32825. this._cache.radius = this.radius;
  32826. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32827. };
  32828. ArcRotateCamera.prototype._getTargetPosition = function () {
  32829. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32830. var pos = this._targetHost.getAbsolutePosition();
  32831. if (this._targetBoundingCenter) {
  32832. pos.addToRef(this._targetBoundingCenter, this._target);
  32833. }
  32834. else {
  32835. this._target.copyFrom(pos);
  32836. }
  32837. }
  32838. return this._target;
  32839. };
  32840. // Synchronized
  32841. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32842. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32843. return false;
  32844. return this._cache._target.equals(this._target)
  32845. && this._cache.alpha === this.alpha
  32846. && this._cache.beta === this.beta
  32847. && this._cache.radius === this.radius
  32848. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32849. };
  32850. // Methods
  32851. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32852. var _this = this;
  32853. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32854. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32855. this._useCtrlForPanning = useCtrlForPanning;
  32856. this._panningMouseButton = panningMouseButton;
  32857. this.inputs.attachElement(element, noPreventDefault);
  32858. this._reset = function () {
  32859. _this.inertialAlphaOffset = 0;
  32860. _this.inertialBetaOffset = 0;
  32861. _this.inertialRadiusOffset = 0;
  32862. };
  32863. };
  32864. ArcRotateCamera.prototype.detachControl = function (element) {
  32865. this.inputs.detachElement(element);
  32866. if (this._reset) {
  32867. this._reset();
  32868. }
  32869. };
  32870. ArcRotateCamera.prototype._checkInputs = function () {
  32871. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32872. if (this._collisionTriggered) {
  32873. return;
  32874. }
  32875. this.inputs.checkInputs();
  32876. // Inertia
  32877. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32878. if (this.getScene().useRightHandedSystem) {
  32879. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32880. }
  32881. else {
  32882. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32883. }
  32884. this.beta += this.inertialBetaOffset;
  32885. this.radius -= this.inertialRadiusOffset;
  32886. this.inertialAlphaOffset *= this.inertia;
  32887. this.inertialBetaOffset *= this.inertia;
  32888. this.inertialRadiusOffset *= this.inertia;
  32889. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  32890. this.inertialAlphaOffset = 0;
  32891. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  32892. this.inertialBetaOffset = 0;
  32893. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32894. this.inertialRadiusOffset = 0;
  32895. }
  32896. // Panning inertia
  32897. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32898. if (!this._localDirection) {
  32899. this._localDirection = BABYLON.Vector3.Zero();
  32900. this._transformedDirection = BABYLON.Vector3.Zero();
  32901. }
  32902. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32903. this._localDirection.multiplyInPlace(this.panningAxis);
  32904. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32905. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32906. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32907. if (!this.panningAxis.y) {
  32908. this._transformedDirection.y = 0;
  32909. }
  32910. if (!this._targetHost) {
  32911. this._target.addInPlace(this._transformedDirection);
  32912. }
  32913. this.inertialPanningX *= this.panningInertia;
  32914. this.inertialPanningY *= this.panningInertia;
  32915. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32916. this.inertialPanningX = 0;
  32917. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32918. this.inertialPanningY = 0;
  32919. }
  32920. // Limits
  32921. this._checkLimits();
  32922. _super.prototype._checkInputs.call(this);
  32923. };
  32924. ArcRotateCamera.prototype._checkLimits = function () {
  32925. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32926. if (this.allowUpsideDown && this.beta > Math.PI) {
  32927. this.beta = this.beta - (2 * Math.PI);
  32928. }
  32929. }
  32930. else {
  32931. if (this.beta < this.lowerBetaLimit) {
  32932. this.beta = this.lowerBetaLimit;
  32933. }
  32934. }
  32935. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32936. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32937. this.beta = this.beta + (2 * Math.PI);
  32938. }
  32939. }
  32940. else {
  32941. if (this.beta > this.upperBetaLimit) {
  32942. this.beta = this.upperBetaLimit;
  32943. }
  32944. }
  32945. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32946. this.alpha = this.lowerAlphaLimit;
  32947. }
  32948. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32949. this.alpha = this.upperAlphaLimit;
  32950. }
  32951. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32952. this.radius = this.lowerRadiusLimit;
  32953. }
  32954. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32955. this.radius = this.upperRadiusLimit;
  32956. }
  32957. };
  32958. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32959. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32960. this.radius = radiusv3.length();
  32961. // Alpha
  32962. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32963. if (radiusv3.z < 0) {
  32964. this.alpha = 2 * Math.PI - this.alpha;
  32965. }
  32966. // Beta
  32967. this.beta = Math.acos(radiusv3.y / this.radius);
  32968. this._checkLimits();
  32969. };
  32970. ArcRotateCamera.prototype.setPosition = function (position) {
  32971. if (this.position.equals(position)) {
  32972. return;
  32973. }
  32974. this.position.copyFrom(position);
  32975. this.rebuildAnglesAndRadius();
  32976. };
  32977. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32978. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32979. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32980. if (target.getBoundingInfo) {
  32981. if (toBoundingCenter) {
  32982. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32983. }
  32984. else {
  32985. this._targetBoundingCenter = null;
  32986. }
  32987. this._targetHost = target;
  32988. this._target = this._getTargetPosition();
  32989. }
  32990. else {
  32991. var newTarget = target;
  32992. var currentTarget = this._getTargetPosition();
  32993. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32994. return;
  32995. }
  32996. this._target = newTarget;
  32997. this._targetBoundingCenter = null;
  32998. }
  32999. this.rebuildAnglesAndRadius();
  33000. };
  33001. ArcRotateCamera.prototype._getViewMatrix = function () {
  33002. // Compute
  33003. var cosa = Math.cos(this.alpha);
  33004. var sina = Math.sin(this.alpha);
  33005. var cosb = Math.cos(this.beta);
  33006. var sinb = Math.sin(this.beta);
  33007. if (sinb === 0) {
  33008. sinb = 0.0001;
  33009. }
  33010. var target = this._getTargetPosition();
  33011. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  33012. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  33013. if (!this._collider) {
  33014. this._collider = new BABYLON.Collider();
  33015. }
  33016. this._collider.radius = this.collisionRadius;
  33017. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  33018. this._collisionTriggered = true;
  33019. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33020. }
  33021. else {
  33022. this.position.copyFrom(this._newPosition);
  33023. var up = this.upVector;
  33024. if (this.allowUpsideDown && sinb < 0) {
  33025. up = up.clone();
  33026. up = up.negate();
  33027. }
  33028. if (this.getScene().useRightHandedSystem) {
  33029. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  33030. }
  33031. else {
  33032. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  33033. }
  33034. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  33035. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  33036. }
  33037. this._currentTarget = target;
  33038. return this._viewMatrix;
  33039. };
  33040. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  33041. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33042. meshes = meshes || this.getScene().meshes;
  33043. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  33044. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  33045. this.radius = distance * this.zoomOnFactor;
  33046. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  33047. };
  33048. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  33049. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33050. var meshesOrMinMaxVector;
  33051. var distance;
  33052. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  33053. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  33054. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  33055. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  33056. }
  33057. else {
  33058. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  33059. distance = meshesOrMinMaxVectorAndDistance.distance;
  33060. }
  33061. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  33062. if (!doNotUpdateMaxZ) {
  33063. this.maxZ = distance * 2;
  33064. }
  33065. };
  33066. /**
  33067. * @override
  33068. * Override Camera.createRigCamera
  33069. */
  33070. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33071. var alphaShift;
  33072. switch (this.cameraRigMode) {
  33073. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33074. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33076. case BABYLON.Camera.RIG_MODE_VR:
  33077. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  33078. break;
  33079. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33080. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  33081. break;
  33082. }
  33083. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  33084. rigCam._cameraRigParams = {};
  33085. return rigCam;
  33086. };
  33087. /**
  33088. * @override
  33089. * Override Camera._updateRigCameras
  33090. */
  33091. ArcRotateCamera.prototype._updateRigCameras = function () {
  33092. var camLeft = this._rigCameras[0];
  33093. var camRight = this._rigCameras[1];
  33094. camLeft.beta = camRight.beta = this.beta;
  33095. camLeft.radius = camRight.radius = this.radius;
  33096. switch (this.cameraRigMode) {
  33097. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33098. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33099. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33100. case BABYLON.Camera.RIG_MODE_VR:
  33101. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33102. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33103. break;
  33104. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33105. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33106. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33107. break;
  33108. }
  33109. _super.prototype._updateRigCameras.call(this);
  33110. };
  33111. ArcRotateCamera.prototype.dispose = function () {
  33112. this.inputs.clear();
  33113. _super.prototype.dispose.call(this);
  33114. };
  33115. ArcRotateCamera.prototype.getClassName = function () {
  33116. return "ArcRotateCamera";
  33117. };
  33118. return ArcRotateCamera;
  33119. }(BABYLON.TargetCamera));
  33120. __decorate([
  33121. BABYLON.serialize()
  33122. ], ArcRotateCamera.prototype, "alpha", void 0);
  33123. __decorate([
  33124. BABYLON.serialize()
  33125. ], ArcRotateCamera.prototype, "beta", void 0);
  33126. __decorate([
  33127. BABYLON.serialize()
  33128. ], ArcRotateCamera.prototype, "radius", void 0);
  33129. __decorate([
  33130. BABYLON.serializeAsVector3("target")
  33131. ], ArcRotateCamera.prototype, "_target", void 0);
  33132. __decorate([
  33133. BABYLON.serialize()
  33134. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  33135. __decorate([
  33136. BABYLON.serialize()
  33137. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  33138. __decorate([
  33139. BABYLON.serialize()
  33140. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  33141. __decorate([
  33142. BABYLON.serialize()
  33143. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  33144. __decorate([
  33145. BABYLON.serialize()
  33146. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  33147. __decorate([
  33148. BABYLON.serialize()
  33149. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  33150. __decorate([
  33151. BABYLON.serialize()
  33152. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  33153. __decorate([
  33154. BABYLON.serialize()
  33155. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  33156. __decorate([
  33157. BABYLON.serialize()
  33158. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  33159. __decorate([
  33160. BABYLON.serialize()
  33161. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  33162. __decorate([
  33163. BABYLON.serialize()
  33164. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  33165. __decorate([
  33166. BABYLON.serialize()
  33167. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  33168. __decorate([
  33169. BABYLON.serialize()
  33170. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  33171. __decorate([
  33172. BABYLON.serialize()
  33173. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  33174. BABYLON.ArcRotateCamera = ArcRotateCamera;
  33175. })(BABYLON || (BABYLON = {}));
  33176. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  33177. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  33178. var BABYLON;
  33179. (function (BABYLON) {
  33180. var ArcRotateCameraInputsManager = (function (_super) {
  33181. __extends(ArcRotateCameraInputsManager, _super);
  33182. function ArcRotateCameraInputsManager(camera) {
  33183. return _super.call(this, camera) || this;
  33184. }
  33185. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33186. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33187. return this;
  33188. };
  33189. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33190. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33191. return this;
  33192. };
  33193. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33194. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33195. return this;
  33196. };
  33197. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33198. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33199. return this;
  33200. };
  33201. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33202. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33203. return this;
  33204. };
  33205. return ArcRotateCameraInputsManager;
  33206. }(BABYLON.CameraInputsManager));
  33207. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33208. })(BABYLON || (BABYLON = {}));
  33209. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33210. var BABYLON;
  33211. (function (BABYLON) {
  33212. var HemisphericLight = (function (_super) {
  33213. __extends(HemisphericLight, _super);
  33214. /**
  33215. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  33216. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  33217. * The HemisphericLight can't cast shadows.
  33218. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33219. */
  33220. function HemisphericLight(name, direction, scene) {
  33221. var _this = _super.call(this, name, scene) || this;
  33222. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  33223. _this.direction = direction || BABYLON.Vector3.Up();
  33224. return _this;
  33225. }
  33226. HemisphericLight.prototype._buildUniformLayout = function () {
  33227. this._uniformBuffer.addUniform("vLightData", 4);
  33228. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33229. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33230. this._uniformBuffer.addUniform("vLightGround", 3);
  33231. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33232. this._uniformBuffer.create();
  33233. };
  33234. /**
  33235. * Returns the string "HemisphericLight".
  33236. */
  33237. HemisphericLight.prototype.getClassName = function () {
  33238. return "HemisphericLight";
  33239. };
  33240. /**
  33241. * Sets the HemisphericLight direction towards the passed target (Vector3).
  33242. * Returns the updated direction.
  33243. */
  33244. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  33245. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  33246. return this.direction;
  33247. };
  33248. HemisphericLight.prototype.getShadowGenerator = function () {
  33249. return null;
  33250. };
  33251. /**
  33252. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  33253. * Returns the HemisphericLight.
  33254. */
  33255. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  33256. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33257. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  33258. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  33259. return this;
  33260. };
  33261. HemisphericLight.prototype._getWorldMatrix = function () {
  33262. if (!this._worldMatrix) {
  33263. this._worldMatrix = BABYLON.Matrix.Identity();
  33264. }
  33265. return this._worldMatrix;
  33266. };
  33267. /**
  33268. * Returns the integer 3.
  33269. */
  33270. HemisphericLight.prototype.getTypeID = function () {
  33271. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  33272. };
  33273. return HemisphericLight;
  33274. }(BABYLON.Light));
  33275. __decorate([
  33276. BABYLON.serializeAsColor3()
  33277. ], HemisphericLight.prototype, "groundColor", void 0);
  33278. __decorate([
  33279. BABYLON.serializeAsVector3()
  33280. ], HemisphericLight.prototype, "direction", void 0);
  33281. BABYLON.HemisphericLight = HemisphericLight;
  33282. })(BABYLON || (BABYLON = {}));
  33283. //# sourceMappingURL=babylon.hemisphericLight.js.map
  33284. var BABYLON;
  33285. (function (BABYLON) {
  33286. var ShadowLight = (function (_super) {
  33287. __extends(ShadowLight, _super);
  33288. function ShadowLight() {
  33289. var _this = _super !== null && _super.apply(this, arguments) || this;
  33290. _this._needProjectionMatrixCompute = true;
  33291. return _this;
  33292. }
  33293. Object.defineProperty(ShadowLight.prototype, "direction", {
  33294. get: function () {
  33295. return this._direction;
  33296. },
  33297. set: function (value) {
  33298. this._direction = value;
  33299. },
  33300. enumerable: true,
  33301. configurable: true
  33302. });
  33303. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33304. get: function () {
  33305. return this._shadowMinZ;
  33306. },
  33307. set: function (value) {
  33308. this._shadowMinZ = value;
  33309. this.forceProjectionMatrixCompute();
  33310. },
  33311. enumerable: true,
  33312. configurable: true
  33313. });
  33314. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33315. get: function () {
  33316. return this._shadowMaxZ;
  33317. },
  33318. set: function (value) {
  33319. this._shadowMaxZ = value;
  33320. this.forceProjectionMatrixCompute();
  33321. },
  33322. enumerable: true,
  33323. configurable: true
  33324. });
  33325. /**
  33326. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33327. */
  33328. ShadowLight.prototype.computeTransformedInformation = function () {
  33329. if (this.parent && this.parent.getWorldMatrix) {
  33330. if (!this.transformedPosition) {
  33331. this.transformedPosition = BABYLON.Vector3.Zero();
  33332. }
  33333. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33334. // In case the direction is present.
  33335. if (this.direction) {
  33336. if (!this.transformedDirection) {
  33337. this.transformedDirection = BABYLON.Vector3.Zero();
  33338. }
  33339. BABYLON.Vector3.TransformCoordinatesToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33340. }
  33341. return true;
  33342. }
  33343. return false;
  33344. };
  33345. /**
  33346. * Return the depth scale used for the shadow map.
  33347. */
  33348. ShadowLight.prototype.getDepthScale = function () {
  33349. return 30.0;
  33350. };
  33351. /**
  33352. * Returns the light direction (Vector3) for any passed face index.
  33353. */
  33354. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33355. return this.transformedDirection ? this.transformedDirection : this.direction;
  33356. };
  33357. /**
  33358. * Returns the DirectionalLight absolute position in the World.
  33359. */
  33360. ShadowLight.prototype.getAbsolutePosition = function () {
  33361. return this.transformedPosition ? this.transformedPosition : this.position;
  33362. };
  33363. /**
  33364. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33365. * Returns the updated DirectionalLight direction (Vector3).
  33366. */
  33367. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33368. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33369. return this.direction;
  33370. };
  33371. /**
  33372. * Returns the light rotation (Vector3).
  33373. */
  33374. ShadowLight.prototype.getRotation = function () {
  33375. this.direction.normalize();
  33376. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33377. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33378. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33379. };
  33380. /**
  33381. * Boolean : false by default.
  33382. */
  33383. ShadowLight.prototype.needCube = function () {
  33384. return false;
  33385. };
  33386. /**
  33387. * Specifies wether or not the projection matrix should be recomputed this frame.
  33388. */
  33389. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33390. return this._needProjectionMatrixCompute;
  33391. };
  33392. /**
  33393. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33394. */
  33395. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33396. this._needProjectionMatrixCompute = true;
  33397. };
  33398. /**
  33399. * Get the world matrix of the sahdow lights.
  33400. */
  33401. ShadowLight.prototype._getWorldMatrix = function () {
  33402. if (!this._worldMatrix) {
  33403. this._worldMatrix = BABYLON.Matrix.Identity();
  33404. }
  33405. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33406. return this._worldMatrix;
  33407. };
  33408. /**
  33409. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33410. * Returns the light.
  33411. */
  33412. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33413. if (this.customProjectionMatrixBuilder) {
  33414. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33415. }
  33416. else {
  33417. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33418. }
  33419. return this;
  33420. };
  33421. return ShadowLight;
  33422. }(BABYLON.Light));
  33423. __decorate([
  33424. BABYLON.serializeAsVector3()
  33425. ], ShadowLight.prototype, "position", void 0);
  33426. __decorate([
  33427. BABYLON.serializeAsVector3()
  33428. ], ShadowLight.prototype, "direction", null);
  33429. __decorate([
  33430. BABYLON.serialize()
  33431. ], ShadowLight.prototype, "shadowMinZ", null);
  33432. __decorate([
  33433. BABYLON.serialize()
  33434. ], ShadowLight.prototype, "shadowMaxZ", null);
  33435. BABYLON.ShadowLight = ShadowLight;
  33436. })(BABYLON || (BABYLON = {}));
  33437. //# sourceMappingURL=babylon.shadowLight.js.map
  33438. var BABYLON;
  33439. (function (BABYLON) {
  33440. var PointLight = (function (_super) {
  33441. __extends(PointLight, _super);
  33442. /**
  33443. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33444. * A PointLight emits the light in every direction.
  33445. * It can cast shadows.
  33446. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33447. * ```javascript
  33448. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33449. * ```
  33450. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33451. */
  33452. function PointLight(name, position, scene) {
  33453. var _this = _super.call(this, name, scene) || this;
  33454. _this._shadowAngle = Math.PI / 2;
  33455. _this.position = position;
  33456. return _this;
  33457. }
  33458. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33459. /**
  33460. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33461. * This specifies what angle the shadow will use to be created.
  33462. *
  33463. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33464. */
  33465. get: function () {
  33466. return this._shadowAngle;
  33467. },
  33468. /**
  33469. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33470. * This specifies what angle the shadow will use to be created.
  33471. *
  33472. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33473. */
  33474. set: function (value) {
  33475. this._shadowAngle = value;
  33476. this.forceProjectionMatrixCompute();
  33477. },
  33478. enumerable: true,
  33479. configurable: true
  33480. });
  33481. Object.defineProperty(PointLight.prototype, "direction", {
  33482. get: function () {
  33483. return this._direction;
  33484. },
  33485. /**
  33486. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33487. */
  33488. set: function (value) {
  33489. var previousNeedCube = this.needCube();
  33490. this._direction = value;
  33491. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33492. this._shadowGenerator.recreateShadowMap();
  33493. }
  33494. },
  33495. enumerable: true,
  33496. configurable: true
  33497. });
  33498. /**
  33499. * Returns the string "PointLight"
  33500. */
  33501. PointLight.prototype.getClassName = function () {
  33502. return "PointLight";
  33503. };
  33504. /**
  33505. * Returns the integer 0.
  33506. */
  33507. PointLight.prototype.getTypeID = function () {
  33508. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  33509. };
  33510. /**
  33511. * Specifies wether or not the shadowmap should be a cube texture.
  33512. */
  33513. PointLight.prototype.needCube = function () {
  33514. return !this.direction;
  33515. };
  33516. /**
  33517. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  33518. */
  33519. PointLight.prototype.getShadowDirection = function (faceIndex) {
  33520. if (this.direction) {
  33521. return _super.prototype.getShadowDirection.call(this, faceIndex);
  33522. }
  33523. else {
  33524. switch (faceIndex) {
  33525. case 0:
  33526. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  33527. case 1:
  33528. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  33529. case 2:
  33530. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  33531. case 3:
  33532. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  33533. case 4:
  33534. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  33535. case 5:
  33536. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  33537. }
  33538. }
  33539. return BABYLON.Vector3.Zero();
  33540. };
  33541. /**
  33542. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  33543. * - fov = PI / 2
  33544. * - aspect ratio : 1.0
  33545. * - z-near and far equal to the active camera minZ and maxZ.
  33546. * Returns the PointLight.
  33547. */
  33548. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33549. var activeCamera = this.getScene().activeCamera;
  33550. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33551. };
  33552. PointLight.prototype._buildUniformLayout = function () {
  33553. this._uniformBuffer.addUniform("vLightData", 4);
  33554. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33555. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33556. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33557. this._uniformBuffer.create();
  33558. };
  33559. /**
  33560. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  33561. * Returns the PointLight.
  33562. */
  33563. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  33564. if (this.computeTransformedInformation()) {
  33565. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  33566. return this;
  33567. }
  33568. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  33569. return this;
  33570. };
  33571. return PointLight;
  33572. }(BABYLON.ShadowLight));
  33573. __decorate([
  33574. BABYLON.serialize()
  33575. ], PointLight.prototype, "shadowAngle", null);
  33576. BABYLON.PointLight = PointLight;
  33577. })(BABYLON || (BABYLON = {}));
  33578. //# sourceMappingURL=babylon.pointLight.js.map
  33579. /// <reference path="babylon.light.ts" />
  33580. var BABYLON;
  33581. (function (BABYLON) {
  33582. var DirectionalLight = (function (_super) {
  33583. __extends(DirectionalLight, _super);
  33584. /**
  33585. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  33586. * The directional light is emitted from everywhere in the given direction.
  33587. * It can cast shawdows.
  33588. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33589. */
  33590. function DirectionalLight(name, direction, scene) {
  33591. var _this = _super.call(this, name, scene) || this;
  33592. _this._shadowOrthoScale = 0.5;
  33593. _this.autoUpdateExtends = true;
  33594. // Cache
  33595. _this._orthoLeft = Number.MAX_VALUE;
  33596. _this._orthoRight = Number.MIN_VALUE;
  33597. _this._orthoTop = Number.MIN_VALUE;
  33598. _this._orthoBottom = Number.MAX_VALUE;
  33599. _this.position = direction.scale(-1.0);
  33600. _this.direction = direction;
  33601. return _this;
  33602. }
  33603. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  33604. get: function () {
  33605. return this._shadowOrthoScale;
  33606. },
  33607. set: function (value) {
  33608. this._shadowOrthoScale = value;
  33609. this.forceProjectionMatrixCompute();
  33610. },
  33611. enumerable: true,
  33612. configurable: true
  33613. });
  33614. /**
  33615. * Returns the string "DirectionalLight".
  33616. */
  33617. DirectionalLight.prototype.getClassName = function () {
  33618. return "DirectionalLight";
  33619. };
  33620. /**
  33621. * Returns the integer 1.
  33622. */
  33623. DirectionalLight.prototype.getTypeID = function () {
  33624. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  33625. };
  33626. /**
  33627. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  33628. * Returns the DirectionalLight.
  33629. */
  33630. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33631. var activeCamera = this.getScene().activeCamera;
  33632. // Check extends
  33633. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  33634. var tempVector3 = BABYLON.Vector3.Zero();
  33635. this._orthoLeft = Number.MAX_VALUE;
  33636. this._orthoRight = Number.MIN_VALUE;
  33637. this._orthoTop = Number.MIN_VALUE;
  33638. this._orthoBottom = Number.MAX_VALUE;
  33639. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  33640. var mesh = renderList[meshIndex];
  33641. if (!mesh) {
  33642. continue;
  33643. }
  33644. var boundingInfo = mesh.getBoundingInfo();
  33645. if (!boundingInfo) {
  33646. continue;
  33647. }
  33648. var boundingBox = boundingInfo.boundingBox;
  33649. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  33650. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  33651. if (tempVector3.x < this._orthoLeft)
  33652. this._orthoLeft = tempVector3.x;
  33653. if (tempVector3.y < this._orthoBottom)
  33654. this._orthoBottom = tempVector3.y;
  33655. if (tempVector3.x > this._orthoRight)
  33656. this._orthoRight = tempVector3.x;
  33657. if (tempVector3.y > this._orthoTop)
  33658. this._orthoTop = tempVector3.y;
  33659. }
  33660. }
  33661. }
  33662. var xOffset = this._orthoRight - this._orthoLeft;
  33663. var yOffset = this._orthoTop - this._orthoBottom;
  33664. 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);
  33665. };
  33666. DirectionalLight.prototype._buildUniformLayout = function () {
  33667. this._uniformBuffer.addUniform("vLightData", 4);
  33668. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33669. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33670. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33671. this._uniformBuffer.create();
  33672. };
  33673. /**
  33674. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  33675. * Returns the DirectionalLight.
  33676. */
  33677. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  33678. if (this.computeTransformedInformation()) {
  33679. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  33680. return this;
  33681. }
  33682. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  33683. return this;
  33684. };
  33685. return DirectionalLight;
  33686. }(BABYLON.ShadowLight));
  33687. __decorate([
  33688. BABYLON.serialize()
  33689. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  33690. __decorate([
  33691. BABYLON.serialize()
  33692. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  33693. BABYLON.DirectionalLight = DirectionalLight;
  33694. })(BABYLON || (BABYLON = {}));
  33695. //# sourceMappingURL=babylon.directionalLight.js.map
  33696. var BABYLON;
  33697. (function (BABYLON) {
  33698. var SpotLight = (function (_super) {
  33699. __extends(SpotLight, _super);
  33700. /**
  33701. * Creates a SpotLight object in the scene with the passed parameters :
  33702. * - `position` (Vector3) is the initial SpotLight position,
  33703. * - `direction` (Vector3) is the initial SpotLight direction,
  33704. * - `angle` (float, in radians) is the spot light cone angle,
  33705. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  33706. * A spot light is a simply light oriented cone.
  33707. * It can cast shadows.
  33708. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33709. */
  33710. function SpotLight(name, position, direction, angle, exponent, scene) {
  33711. var _this = _super.call(this, name, scene) || this;
  33712. _this.position = position;
  33713. _this.direction = direction;
  33714. _this.angle = angle;
  33715. _this.exponent = exponent;
  33716. return _this;
  33717. }
  33718. Object.defineProperty(SpotLight.prototype, "angle", {
  33719. get: function () {
  33720. return this._angle;
  33721. },
  33722. set: function (value) {
  33723. this._angle = value;
  33724. this.forceProjectionMatrixCompute();
  33725. },
  33726. enumerable: true,
  33727. configurable: true
  33728. });
  33729. /**
  33730. * Returns the string "SpotLight".
  33731. */
  33732. SpotLight.prototype.getClassName = function () {
  33733. return "SpotLight";
  33734. };
  33735. /**
  33736. * Returns the integer 2.
  33737. */
  33738. SpotLight.prototype.getTypeID = function () {
  33739. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  33740. };
  33741. /**
  33742. * 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.
  33743. * Returns the SpotLight.
  33744. */
  33745. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33746. var activeCamera = this.getScene().activeCamera;
  33747. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33748. };
  33749. SpotLight.prototype._buildUniformLayout = function () {
  33750. this._uniformBuffer.addUniform("vLightData", 4);
  33751. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33752. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33753. this._uniformBuffer.addUniform("vLightDirection", 3);
  33754. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33755. this._uniformBuffer.create();
  33756. };
  33757. /**
  33758. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  33759. * Return the SpotLight.
  33760. */
  33761. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  33762. var normalizeDirection;
  33763. if (this.computeTransformedInformation()) {
  33764. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  33765. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  33766. }
  33767. else {
  33768. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  33769. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33770. }
  33771. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  33772. return this;
  33773. };
  33774. return SpotLight;
  33775. }(BABYLON.ShadowLight));
  33776. __decorate([
  33777. BABYLON.serialize()
  33778. ], SpotLight.prototype, "angle", null);
  33779. __decorate([
  33780. BABYLON.serialize()
  33781. ], SpotLight.prototype, "exponent", void 0);
  33782. BABYLON.SpotLight = SpotLight;
  33783. })(BABYLON || (BABYLON = {}));
  33784. //# sourceMappingURL=babylon.spotLight.js.map
  33785. var BABYLON;
  33786. (function (BABYLON) {
  33787. var AnimationRange = (function () {
  33788. function AnimationRange(name, from, to) {
  33789. this.name = name;
  33790. this.from = from;
  33791. this.to = to;
  33792. }
  33793. AnimationRange.prototype.clone = function () {
  33794. return new AnimationRange(this.name, this.from, this.to);
  33795. };
  33796. return AnimationRange;
  33797. }());
  33798. BABYLON.AnimationRange = AnimationRange;
  33799. /**
  33800. * Composed of a frame, and an action function
  33801. */
  33802. var AnimationEvent = (function () {
  33803. function AnimationEvent(frame, action, onlyOnce) {
  33804. this.frame = frame;
  33805. this.action = action;
  33806. this.onlyOnce = onlyOnce;
  33807. this.isDone = false;
  33808. }
  33809. return AnimationEvent;
  33810. }());
  33811. BABYLON.AnimationEvent = AnimationEvent;
  33812. var PathCursor = (function () {
  33813. function PathCursor(path) {
  33814. this.path = path;
  33815. this._onchange = new Array();
  33816. this.value = 0;
  33817. this.animations = new Array();
  33818. }
  33819. PathCursor.prototype.getPoint = function () {
  33820. var point = this.path.getPointAtLengthPosition(this.value);
  33821. return new BABYLON.Vector3(point.x, 0, point.y);
  33822. };
  33823. PathCursor.prototype.moveAhead = function (step) {
  33824. if (step === void 0) { step = 0.002; }
  33825. this.move(step);
  33826. return this;
  33827. };
  33828. PathCursor.prototype.moveBack = function (step) {
  33829. if (step === void 0) { step = 0.002; }
  33830. this.move(-step);
  33831. return this;
  33832. };
  33833. PathCursor.prototype.move = function (step) {
  33834. if (Math.abs(step) > 1) {
  33835. throw "step size should be less than 1.";
  33836. }
  33837. this.value += step;
  33838. this.ensureLimits();
  33839. this.raiseOnChange();
  33840. return this;
  33841. };
  33842. PathCursor.prototype.ensureLimits = function () {
  33843. while (this.value > 1) {
  33844. this.value -= 1;
  33845. }
  33846. while (this.value < 0) {
  33847. this.value += 1;
  33848. }
  33849. return this;
  33850. };
  33851. // used by animation engine
  33852. PathCursor.prototype.markAsDirty = function (propertyName) {
  33853. this.ensureLimits();
  33854. this.raiseOnChange();
  33855. return this;
  33856. };
  33857. PathCursor.prototype.raiseOnChange = function () {
  33858. var _this = this;
  33859. this._onchange.forEach(function (f) { return f(_this); });
  33860. return this;
  33861. };
  33862. PathCursor.prototype.onchange = function (f) {
  33863. this._onchange.push(f);
  33864. return this;
  33865. };
  33866. return PathCursor;
  33867. }());
  33868. BABYLON.PathCursor = PathCursor;
  33869. var Animation = (function () {
  33870. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  33871. this.name = name;
  33872. this.targetProperty = targetProperty;
  33873. this.framePerSecond = framePerSecond;
  33874. this.dataType = dataType;
  33875. this.loopMode = loopMode;
  33876. this.enableBlending = enableBlending;
  33877. this._offsetsCache = {};
  33878. this._highLimitsCache = {};
  33879. this._stopped = false;
  33880. this._blendingFactor = 0;
  33881. // The set of event that will be linked to this animation
  33882. this._events = new Array();
  33883. this.allowMatricesInterpolation = false;
  33884. this.blendingSpeed = 0.01;
  33885. this._ranges = {};
  33886. this.targetPropertyPath = targetProperty.split(".");
  33887. this.dataType = dataType;
  33888. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  33889. }
  33890. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  33891. var dataType = undefined;
  33892. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  33893. dataType = Animation.ANIMATIONTYPE_FLOAT;
  33894. }
  33895. else if (from instanceof BABYLON.Quaternion) {
  33896. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  33897. }
  33898. else if (from instanceof BABYLON.Vector3) {
  33899. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  33900. }
  33901. else if (from instanceof BABYLON.Vector2) {
  33902. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  33903. }
  33904. else if (from instanceof BABYLON.Color3) {
  33905. dataType = Animation.ANIMATIONTYPE_COLOR3;
  33906. }
  33907. else if (from instanceof BABYLON.Size) {
  33908. dataType = Animation.ANIMATIONTYPE_SIZE;
  33909. }
  33910. if (dataType == undefined) {
  33911. return null;
  33912. }
  33913. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  33914. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  33915. animation.setKeys(keys);
  33916. if (easingFunction !== undefined) {
  33917. animation.setEasingFunction(easingFunction);
  33918. }
  33919. return animation;
  33920. };
  33921. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  33922. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  33923. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  33924. };
  33925. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  33926. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  33927. node.animations.push(animation);
  33928. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  33929. };
  33930. // Methods
  33931. /**
  33932. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  33933. */
  33934. Animation.prototype.toString = function (fullDetails) {
  33935. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  33936. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  33937. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  33938. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  33939. if (fullDetails) {
  33940. ret += ", Ranges: {";
  33941. var first = true;
  33942. for (var name in this._ranges) {
  33943. if (first) {
  33944. ret += ", ";
  33945. first = false;
  33946. }
  33947. ret += name;
  33948. }
  33949. ret += "}";
  33950. }
  33951. return ret;
  33952. };
  33953. /**
  33954. * Add an event to this animation.
  33955. */
  33956. Animation.prototype.addEvent = function (event) {
  33957. this._events.push(event);
  33958. };
  33959. /**
  33960. * Remove all events found at the given frame
  33961. * @param frame
  33962. */
  33963. Animation.prototype.removeEvents = function (frame) {
  33964. for (var index = 0; index < this._events.length; index++) {
  33965. if (this._events[index].frame === frame) {
  33966. this._events.splice(index, 1);
  33967. index--;
  33968. }
  33969. }
  33970. };
  33971. Animation.prototype.createRange = function (name, from, to) {
  33972. // check name not already in use; could happen for bones after serialized
  33973. if (!this._ranges[name]) {
  33974. this._ranges[name] = new AnimationRange(name, from, to);
  33975. }
  33976. };
  33977. Animation.prototype.deleteRange = function (name, deleteFrames) {
  33978. if (deleteFrames === void 0) { deleteFrames = true; }
  33979. if (this._ranges[name]) {
  33980. if (deleteFrames) {
  33981. var from = this._ranges[name].from;
  33982. var to = this._ranges[name].to;
  33983. // this loop MUST go high to low for multiple splices to work
  33984. for (var key = this._keys.length - 1; key >= 0; key--) {
  33985. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  33986. this._keys.splice(key, 1);
  33987. }
  33988. }
  33989. }
  33990. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  33991. }
  33992. };
  33993. Animation.prototype.getRange = function (name) {
  33994. return this._ranges[name];
  33995. };
  33996. Animation.prototype.reset = function () {
  33997. this._offsetsCache = {};
  33998. this._highLimitsCache = {};
  33999. this.currentFrame = 0;
  34000. this._blendingFactor = 0;
  34001. this._originalBlendValue = null;
  34002. };
  34003. Animation.prototype.isStopped = function () {
  34004. return this._stopped;
  34005. };
  34006. Animation.prototype.getKeys = function () {
  34007. return this._keys;
  34008. };
  34009. Animation.prototype.getHighestFrame = function () {
  34010. var ret = 0;
  34011. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34012. if (ret < this._keys[key].frame) {
  34013. ret = this._keys[key].frame;
  34014. }
  34015. }
  34016. return ret;
  34017. };
  34018. Animation.prototype.getEasingFunction = function () {
  34019. return this._easingFunction;
  34020. };
  34021. Animation.prototype.setEasingFunction = function (easingFunction) {
  34022. this._easingFunction = easingFunction;
  34023. };
  34024. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34025. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  34026. };
  34027. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34028. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34029. };
  34030. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34031. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34032. };
  34033. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34034. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  34035. };
  34036. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34037. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34038. };
  34039. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34040. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34041. };
  34042. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34043. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34044. };
  34045. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34046. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34047. };
  34048. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34049. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34050. };
  34051. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34052. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34053. };
  34054. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34055. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34056. };
  34057. Animation.prototype.clone = function () {
  34058. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34059. clone.enableBlending = this.enableBlending;
  34060. clone.blendingSpeed = this.blendingSpeed;
  34061. if (this._keys) {
  34062. clone.setKeys(this._keys);
  34063. }
  34064. if (this._ranges) {
  34065. clone._ranges = {};
  34066. for (var name in this._ranges) {
  34067. clone._ranges[name] = this._ranges[name].clone();
  34068. }
  34069. }
  34070. return clone;
  34071. };
  34072. Animation.prototype.setKeys = function (values) {
  34073. this._keys = values.slice(0);
  34074. this._offsetsCache = {};
  34075. this._highLimitsCache = {};
  34076. };
  34077. Animation.prototype._getKeyValue = function (value) {
  34078. if (typeof value === "function") {
  34079. return value();
  34080. }
  34081. return value;
  34082. };
  34083. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34084. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34085. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34086. }
  34087. this.currentFrame = currentFrame;
  34088. // Try to get a hash to find the right key
  34089. 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));
  34090. if (this._keys[startKeyIndex].frame >= currentFrame) {
  34091. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  34092. startKeyIndex--;
  34093. }
  34094. }
  34095. for (var key = startKeyIndex; key < this._keys.length; key++) {
  34096. var endKey = this._keys[key + 1];
  34097. if (endKey.frame >= currentFrame) {
  34098. var startKey = this._keys[key];
  34099. var startValue = this._getKeyValue(startKey.value);
  34100. var endValue = this._getKeyValue(endKey.value);
  34101. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  34102. var frameDelta = endKey.frame - startKey.frame;
  34103. // gradient : percent of currentFrame between the frame inf and the frame sup
  34104. var gradient = (currentFrame - startKey.frame) / frameDelta;
  34105. // check for easingFunction and correction of gradient
  34106. if (this._easingFunction != null) {
  34107. gradient = this._easingFunction.ease(gradient);
  34108. }
  34109. switch (this.dataType) {
  34110. // Float
  34111. case Animation.ANIMATIONTYPE_FLOAT:
  34112. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  34113. switch (loopMode) {
  34114. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34115. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34116. return floatValue;
  34117. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34118. return offsetValue * repeatCount + floatValue;
  34119. }
  34120. break;
  34121. // Quaternion
  34122. case Animation.ANIMATIONTYPE_QUATERNION:
  34123. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34124. switch (loopMode) {
  34125. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34126. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34127. return quatValue;
  34128. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34129. return quatValue.add(offsetValue.scale(repeatCount));
  34130. }
  34131. return quatValue;
  34132. // Vector3
  34133. case Animation.ANIMATIONTYPE_VECTOR3:
  34134. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  34135. switch (loopMode) {
  34136. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34137. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34138. return vec3Value;
  34139. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34140. return vec3Value.add(offsetValue.scale(repeatCount));
  34141. }
  34142. // Vector2
  34143. case Animation.ANIMATIONTYPE_VECTOR2:
  34144. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  34145. switch (loopMode) {
  34146. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34147. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34148. return vec2Value;
  34149. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34150. return vec2Value.add(offsetValue.scale(repeatCount));
  34151. }
  34152. // Size
  34153. case Animation.ANIMATIONTYPE_SIZE:
  34154. switch (loopMode) {
  34155. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34156. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34157. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34158. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34159. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34160. }
  34161. // Color3
  34162. case Animation.ANIMATIONTYPE_COLOR3:
  34163. switch (loopMode) {
  34164. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34165. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34166. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34167. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34168. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34169. }
  34170. // Matrix
  34171. case Animation.ANIMATIONTYPE_MATRIX:
  34172. switch (loopMode) {
  34173. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34174. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34175. if (this.allowMatricesInterpolation) {
  34176. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34177. }
  34178. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34179. return startValue;
  34180. }
  34181. default:
  34182. break;
  34183. }
  34184. break;
  34185. }
  34186. }
  34187. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34188. };
  34189. Animation.prototype.setValue = function (currentValue, blend) {
  34190. if (blend === void 0) { blend = false; }
  34191. // Set value
  34192. var path;
  34193. var destination;
  34194. if (this.targetPropertyPath.length > 1) {
  34195. var property = this._target[this.targetPropertyPath[0]];
  34196. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34197. property = property[this.targetPropertyPath[index]];
  34198. }
  34199. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34200. destination = property;
  34201. }
  34202. else {
  34203. path = this.targetPropertyPath[0];
  34204. destination = this._target;
  34205. }
  34206. // Blending
  34207. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34208. if (!this._originalBlendValue) {
  34209. if (destination[path].clone) {
  34210. this._originalBlendValue = destination[path].clone();
  34211. }
  34212. else {
  34213. this._originalBlendValue = destination[path];
  34214. }
  34215. }
  34216. if (this._originalBlendValue.prototype) {
  34217. if (this._originalBlendValue.prototype.Lerp) {
  34218. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34219. }
  34220. else {
  34221. destination[path] = currentValue;
  34222. }
  34223. }
  34224. else if (this._originalBlendValue.m) {
  34225. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34226. }
  34227. else {
  34228. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34229. }
  34230. this._blendingFactor += this.blendingSpeed;
  34231. }
  34232. else {
  34233. destination[path] = currentValue;
  34234. }
  34235. if (this._target.markAsDirty) {
  34236. this._target.markAsDirty(this.targetProperty);
  34237. }
  34238. };
  34239. Animation.prototype.goToFrame = function (frame) {
  34240. if (frame < this._keys[0].frame) {
  34241. frame = this._keys[0].frame;
  34242. }
  34243. else if (frame > this._keys[this._keys.length - 1].frame) {
  34244. frame = this._keys[this._keys.length - 1].frame;
  34245. }
  34246. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34247. this.setValue(currentValue);
  34248. };
  34249. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34250. if (blend === void 0) { blend = false; }
  34251. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34252. this._stopped = true;
  34253. return false;
  34254. }
  34255. var returnValue = true;
  34256. // Adding a start key at frame 0 if missing
  34257. if (this._keys[0].frame !== 0) {
  34258. var newKey = { frame: 0, value: this._keys[0].value };
  34259. this._keys.splice(0, 0, newKey);
  34260. }
  34261. // Check limits
  34262. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34263. from = this._keys[0].frame;
  34264. }
  34265. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34266. to = this._keys[this._keys.length - 1].frame;
  34267. }
  34268. //to and from cannot be the same key
  34269. if (from === to) {
  34270. from++;
  34271. }
  34272. // Compute ratio
  34273. var range = to - from;
  34274. var offsetValue;
  34275. // ratio represents the frame delta between from and to
  34276. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34277. var highLimitValue = 0;
  34278. if (ratio > range && !loop) {
  34279. returnValue = false;
  34280. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34281. }
  34282. else {
  34283. // Get max value if required
  34284. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34285. var keyOffset = to.toString() + from.toString();
  34286. if (!this._offsetsCache[keyOffset]) {
  34287. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34288. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34289. switch (this.dataType) {
  34290. // Float
  34291. case Animation.ANIMATIONTYPE_FLOAT:
  34292. this._offsetsCache[keyOffset] = toValue - fromValue;
  34293. break;
  34294. // Quaternion
  34295. case Animation.ANIMATIONTYPE_QUATERNION:
  34296. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34297. break;
  34298. // Vector3
  34299. case Animation.ANIMATIONTYPE_VECTOR3:
  34300. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34301. // Vector2
  34302. case Animation.ANIMATIONTYPE_VECTOR2:
  34303. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34304. // Size
  34305. case Animation.ANIMATIONTYPE_SIZE:
  34306. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34307. // Color3
  34308. case Animation.ANIMATIONTYPE_COLOR3:
  34309. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34310. default:
  34311. break;
  34312. }
  34313. this._highLimitsCache[keyOffset] = toValue;
  34314. }
  34315. highLimitValue = this._highLimitsCache[keyOffset];
  34316. offsetValue = this._offsetsCache[keyOffset];
  34317. }
  34318. }
  34319. if (offsetValue === undefined) {
  34320. switch (this.dataType) {
  34321. // Float
  34322. case Animation.ANIMATIONTYPE_FLOAT:
  34323. offsetValue = 0;
  34324. break;
  34325. // Quaternion
  34326. case Animation.ANIMATIONTYPE_QUATERNION:
  34327. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34328. break;
  34329. // Vector3
  34330. case Animation.ANIMATIONTYPE_VECTOR3:
  34331. offsetValue = BABYLON.Vector3.Zero();
  34332. break;
  34333. // Vector2
  34334. case Animation.ANIMATIONTYPE_VECTOR2:
  34335. offsetValue = BABYLON.Vector2.Zero();
  34336. break;
  34337. // Size
  34338. case Animation.ANIMATIONTYPE_SIZE:
  34339. offsetValue = BABYLON.Size.Zero();
  34340. break;
  34341. // Color3
  34342. case Animation.ANIMATIONTYPE_COLOR3:
  34343. offsetValue = BABYLON.Color3.Black();
  34344. }
  34345. }
  34346. // Compute value
  34347. var repeatCount = (ratio / range) >> 0;
  34348. var currentFrame = returnValue ? from + ratio % range : to;
  34349. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34350. // Set value
  34351. this.setValue(currentValue);
  34352. // Check events
  34353. for (var index = 0; index < this._events.length; index++) {
  34354. if (currentFrame >= this._events[index].frame) {
  34355. var event = this._events[index];
  34356. if (!event.isDone) {
  34357. // If event should be done only once, remove it.
  34358. if (event.onlyOnce) {
  34359. this._events.splice(index, 1);
  34360. index--;
  34361. }
  34362. event.isDone = true;
  34363. event.action();
  34364. } // Don't do anything if the event has already be done.
  34365. }
  34366. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34367. // reset event, the animation is looping
  34368. this._events[index].isDone = false;
  34369. }
  34370. }
  34371. if (!returnValue) {
  34372. this._stopped = true;
  34373. }
  34374. return returnValue;
  34375. };
  34376. Animation.prototype.serialize = function () {
  34377. var serializationObject = {};
  34378. serializationObject.name = this.name;
  34379. serializationObject.property = this.targetProperty;
  34380. serializationObject.framePerSecond = this.framePerSecond;
  34381. serializationObject.dataType = this.dataType;
  34382. serializationObject.loopBehavior = this.loopMode;
  34383. serializationObject.enableBlending = this.enableBlending;
  34384. serializationObject.blendingSpeed = this.blendingSpeed;
  34385. var dataType = this.dataType;
  34386. serializationObject.keys = [];
  34387. var keys = this.getKeys();
  34388. for (var index = 0; index < keys.length; index++) {
  34389. var animationKey = keys[index];
  34390. var key = {};
  34391. key.frame = animationKey.frame;
  34392. switch (dataType) {
  34393. case Animation.ANIMATIONTYPE_FLOAT:
  34394. key.values = [animationKey.value];
  34395. break;
  34396. case Animation.ANIMATIONTYPE_QUATERNION:
  34397. case Animation.ANIMATIONTYPE_MATRIX:
  34398. case Animation.ANIMATIONTYPE_VECTOR3:
  34399. case Animation.ANIMATIONTYPE_COLOR3:
  34400. key.values = animationKey.value.asArray();
  34401. break;
  34402. }
  34403. serializationObject.keys.push(key);
  34404. }
  34405. serializationObject.ranges = [];
  34406. for (var name in this._ranges) {
  34407. var range = {};
  34408. range.name = name;
  34409. range.from = this._ranges[name].from;
  34410. range.to = this._ranges[name].to;
  34411. serializationObject.ranges.push(range);
  34412. }
  34413. return serializationObject;
  34414. };
  34415. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  34416. get: function () {
  34417. return Animation._ANIMATIONTYPE_FLOAT;
  34418. },
  34419. enumerable: true,
  34420. configurable: true
  34421. });
  34422. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  34423. get: function () {
  34424. return Animation._ANIMATIONTYPE_VECTOR3;
  34425. },
  34426. enumerable: true,
  34427. configurable: true
  34428. });
  34429. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  34430. get: function () {
  34431. return Animation._ANIMATIONTYPE_VECTOR2;
  34432. },
  34433. enumerable: true,
  34434. configurable: true
  34435. });
  34436. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  34437. get: function () {
  34438. return Animation._ANIMATIONTYPE_SIZE;
  34439. },
  34440. enumerable: true,
  34441. configurable: true
  34442. });
  34443. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  34444. get: function () {
  34445. return Animation._ANIMATIONTYPE_QUATERNION;
  34446. },
  34447. enumerable: true,
  34448. configurable: true
  34449. });
  34450. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  34451. get: function () {
  34452. return Animation._ANIMATIONTYPE_MATRIX;
  34453. },
  34454. enumerable: true,
  34455. configurable: true
  34456. });
  34457. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  34458. get: function () {
  34459. return Animation._ANIMATIONTYPE_COLOR3;
  34460. },
  34461. enumerable: true,
  34462. configurable: true
  34463. });
  34464. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  34465. get: function () {
  34466. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  34467. },
  34468. enumerable: true,
  34469. configurable: true
  34470. });
  34471. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  34472. get: function () {
  34473. return Animation._ANIMATIONLOOPMODE_CYCLE;
  34474. },
  34475. enumerable: true,
  34476. configurable: true
  34477. });
  34478. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  34479. get: function () {
  34480. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  34481. },
  34482. enumerable: true,
  34483. configurable: true
  34484. });
  34485. Animation.Parse = function (parsedAnimation) {
  34486. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  34487. var dataType = parsedAnimation.dataType;
  34488. var keys = [];
  34489. var data;
  34490. var index;
  34491. if (parsedAnimation.enableBlending) {
  34492. animation.enableBlending = parsedAnimation.enableBlending;
  34493. }
  34494. if (parsedAnimation.blendingSpeed) {
  34495. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  34496. }
  34497. for (index = 0; index < parsedAnimation.keys.length; index++) {
  34498. var key = parsedAnimation.keys[index];
  34499. switch (dataType) {
  34500. case Animation.ANIMATIONTYPE_FLOAT:
  34501. data = key.values[0];
  34502. break;
  34503. case Animation.ANIMATIONTYPE_QUATERNION:
  34504. data = BABYLON.Quaternion.FromArray(key.values);
  34505. break;
  34506. case Animation.ANIMATIONTYPE_MATRIX:
  34507. data = BABYLON.Matrix.FromArray(key.values);
  34508. break;
  34509. case Animation.ANIMATIONTYPE_COLOR3:
  34510. data = BABYLON.Color3.FromArray(key.values);
  34511. break;
  34512. case Animation.ANIMATIONTYPE_VECTOR3:
  34513. default:
  34514. data = BABYLON.Vector3.FromArray(key.values);
  34515. break;
  34516. }
  34517. keys.push({
  34518. frame: key.frame,
  34519. value: data
  34520. });
  34521. }
  34522. animation.setKeys(keys);
  34523. if (parsedAnimation.ranges) {
  34524. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  34525. data = parsedAnimation.ranges[index];
  34526. animation.createRange(data.name, data.from, data.to);
  34527. }
  34528. }
  34529. return animation;
  34530. };
  34531. Animation.AppendSerializedAnimations = function (source, destination) {
  34532. if (source.animations) {
  34533. destination.animations = [];
  34534. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  34535. var animation = source.animations[animationIndex];
  34536. destination.animations.push(animation.serialize());
  34537. }
  34538. }
  34539. };
  34540. return Animation;
  34541. }());
  34542. // Statics
  34543. Animation._ANIMATIONTYPE_FLOAT = 0;
  34544. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  34545. Animation._ANIMATIONTYPE_QUATERNION = 2;
  34546. Animation._ANIMATIONTYPE_MATRIX = 3;
  34547. Animation._ANIMATIONTYPE_COLOR3 = 4;
  34548. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  34549. Animation._ANIMATIONTYPE_SIZE = 6;
  34550. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  34551. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  34552. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  34553. BABYLON.Animation = Animation;
  34554. })(BABYLON || (BABYLON = {}));
  34555. //# sourceMappingURL=babylon.animation.js.map
  34556. var BABYLON;
  34557. (function (BABYLON) {
  34558. var Animatable = (function () {
  34559. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  34560. if (fromFrame === void 0) { fromFrame = 0; }
  34561. if (toFrame === void 0) { toFrame = 100; }
  34562. if (loopAnimation === void 0) { loopAnimation = false; }
  34563. if (speedRatio === void 0) { speedRatio = 1.0; }
  34564. this.target = target;
  34565. this.fromFrame = fromFrame;
  34566. this.toFrame = toFrame;
  34567. this.loopAnimation = loopAnimation;
  34568. this.speedRatio = speedRatio;
  34569. this.onAnimationEnd = onAnimationEnd;
  34570. this._localDelayOffset = null;
  34571. this._pausedDelay = null;
  34572. this._animations = new Array();
  34573. this._paused = false;
  34574. this.animationStarted = false;
  34575. if (animations) {
  34576. this.appendAnimations(target, animations);
  34577. }
  34578. this._scene = scene;
  34579. scene._activeAnimatables.push(this);
  34580. }
  34581. // Methods
  34582. Animatable.prototype.getAnimations = function () {
  34583. return this._animations;
  34584. };
  34585. Animatable.prototype.appendAnimations = function (target, animations) {
  34586. for (var index = 0; index < animations.length; index++) {
  34587. var animation = animations[index];
  34588. animation._target = target;
  34589. this._animations.push(animation);
  34590. }
  34591. };
  34592. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  34593. var animations = this._animations;
  34594. for (var index = 0; index < animations.length; index++) {
  34595. if (animations[index].targetProperty === property) {
  34596. return animations[index];
  34597. }
  34598. }
  34599. return null;
  34600. };
  34601. Animatable.prototype.reset = function () {
  34602. var animations = this._animations;
  34603. for (var index = 0; index < animations.length; index++) {
  34604. animations[index].reset();
  34605. }
  34606. this._localDelayOffset = null;
  34607. this._pausedDelay = null;
  34608. };
  34609. Animatable.prototype.enableBlending = function (blendingSpeed) {
  34610. var animations = this._animations;
  34611. for (var index = 0; index < animations.length; index++) {
  34612. animations[index].enableBlending = true;
  34613. animations[index].blendingSpeed = blendingSpeed;
  34614. }
  34615. };
  34616. Animatable.prototype.disableBlending = function () {
  34617. var animations = this._animations;
  34618. for (var index = 0; index < animations.length; index++) {
  34619. animations[index].enableBlending = false;
  34620. }
  34621. };
  34622. Animatable.prototype.goToFrame = function (frame) {
  34623. var animations = this._animations;
  34624. if (animations[0]) {
  34625. var fps = animations[0].framePerSecond;
  34626. var currentFrame = animations[0].currentFrame;
  34627. var adjustTime = frame - currentFrame;
  34628. var delay = adjustTime * 1000 / fps;
  34629. this._localDelayOffset -= delay;
  34630. }
  34631. for (var index = 0; index < animations.length; index++) {
  34632. animations[index].goToFrame(frame);
  34633. }
  34634. };
  34635. Animatable.prototype.pause = function () {
  34636. if (this._paused) {
  34637. return;
  34638. }
  34639. this._paused = true;
  34640. };
  34641. Animatable.prototype.restart = function () {
  34642. this._paused = false;
  34643. };
  34644. Animatable.prototype.stop = function (animationName) {
  34645. if (animationName) {
  34646. var idx = this._scene._activeAnimatables.indexOf(this);
  34647. if (idx > -1) {
  34648. var animations = this._animations;
  34649. for (var index = animations.length - 1; index >= 0; index--) {
  34650. if (typeof animationName === "string" && animations[index].name != animationName) {
  34651. continue;
  34652. }
  34653. animations[index].reset();
  34654. animations.splice(index, 1);
  34655. }
  34656. if (animations.length == 0) {
  34657. this._scene._activeAnimatables.splice(idx, 1);
  34658. if (this.onAnimationEnd) {
  34659. this.onAnimationEnd();
  34660. }
  34661. }
  34662. }
  34663. }
  34664. else {
  34665. var index = this._scene._activeAnimatables.indexOf(this);
  34666. if (index > -1) {
  34667. this._scene._activeAnimatables.splice(index, 1);
  34668. var animations = this._animations;
  34669. for (var index = 0; index < animations.length; index++) {
  34670. animations[index].reset();
  34671. }
  34672. if (this.onAnimationEnd) {
  34673. this.onAnimationEnd();
  34674. }
  34675. }
  34676. }
  34677. };
  34678. Animatable.prototype._animate = function (delay) {
  34679. if (this._paused) {
  34680. this.animationStarted = false;
  34681. if (this._pausedDelay === null) {
  34682. this._pausedDelay = delay;
  34683. }
  34684. return true;
  34685. }
  34686. if (this._localDelayOffset === null) {
  34687. this._localDelayOffset = delay;
  34688. }
  34689. else if (this._pausedDelay !== null) {
  34690. this._localDelayOffset += delay - this._pausedDelay;
  34691. this._pausedDelay = null;
  34692. }
  34693. // Animating
  34694. var running = false;
  34695. var animations = this._animations;
  34696. var index;
  34697. for (index = 0; index < animations.length; index++) {
  34698. var animation = animations[index];
  34699. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  34700. running = running || isRunning;
  34701. }
  34702. this.animationStarted = running;
  34703. if (!running) {
  34704. // Remove from active animatables
  34705. index = this._scene._activeAnimatables.indexOf(this);
  34706. this._scene._activeAnimatables.splice(index, 1);
  34707. }
  34708. if (!running && this.onAnimationEnd) {
  34709. this.onAnimationEnd();
  34710. this.onAnimationEnd = null;
  34711. }
  34712. return running;
  34713. };
  34714. return Animatable;
  34715. }());
  34716. BABYLON.Animatable = Animatable;
  34717. })(BABYLON || (BABYLON = {}));
  34718. //# sourceMappingURL=babylon.animatable.js.map
  34719. var BABYLON;
  34720. (function (BABYLON) {
  34721. var EasingFunction = (function () {
  34722. function EasingFunction() {
  34723. // Properties
  34724. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  34725. }
  34726. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  34727. get: function () {
  34728. return EasingFunction._EASINGMODE_EASEIN;
  34729. },
  34730. enumerable: true,
  34731. configurable: true
  34732. });
  34733. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  34734. get: function () {
  34735. return EasingFunction._EASINGMODE_EASEOUT;
  34736. },
  34737. enumerable: true,
  34738. configurable: true
  34739. });
  34740. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  34741. get: function () {
  34742. return EasingFunction._EASINGMODE_EASEINOUT;
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. EasingFunction.prototype.setEasingMode = function (easingMode) {
  34748. var n = Math.min(Math.max(easingMode, 0), 2);
  34749. this._easingMode = n;
  34750. };
  34751. EasingFunction.prototype.getEasingMode = function () {
  34752. return this._easingMode;
  34753. };
  34754. EasingFunction.prototype.easeInCore = function (gradient) {
  34755. throw new Error('You must implement this method');
  34756. };
  34757. EasingFunction.prototype.ease = function (gradient) {
  34758. switch (this._easingMode) {
  34759. case EasingFunction.EASINGMODE_EASEIN:
  34760. return this.easeInCore(gradient);
  34761. case EasingFunction.EASINGMODE_EASEOUT:
  34762. return (1 - this.easeInCore(1 - gradient));
  34763. }
  34764. if (gradient >= 0.5) {
  34765. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  34766. }
  34767. return (this.easeInCore(gradient * 2) * 0.5);
  34768. };
  34769. return EasingFunction;
  34770. }());
  34771. //Statics
  34772. EasingFunction._EASINGMODE_EASEIN = 0;
  34773. EasingFunction._EASINGMODE_EASEOUT = 1;
  34774. EasingFunction._EASINGMODE_EASEINOUT = 2;
  34775. BABYLON.EasingFunction = EasingFunction;
  34776. var CircleEase = (function (_super) {
  34777. __extends(CircleEase, _super);
  34778. function CircleEase() {
  34779. return _super !== null && _super.apply(this, arguments) || this;
  34780. }
  34781. CircleEase.prototype.easeInCore = function (gradient) {
  34782. gradient = Math.max(0, Math.min(1, gradient));
  34783. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  34784. };
  34785. return CircleEase;
  34786. }(EasingFunction));
  34787. BABYLON.CircleEase = CircleEase;
  34788. var BackEase = (function (_super) {
  34789. __extends(BackEase, _super);
  34790. function BackEase(amplitude) {
  34791. if (amplitude === void 0) { amplitude = 1; }
  34792. var _this = _super.call(this) || this;
  34793. _this.amplitude = amplitude;
  34794. return _this;
  34795. }
  34796. BackEase.prototype.easeInCore = function (gradient) {
  34797. var num = Math.max(0, this.amplitude);
  34798. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  34799. };
  34800. return BackEase;
  34801. }(EasingFunction));
  34802. BABYLON.BackEase = BackEase;
  34803. var BounceEase = (function (_super) {
  34804. __extends(BounceEase, _super);
  34805. function BounceEase(bounces, bounciness) {
  34806. if (bounces === void 0) { bounces = 3; }
  34807. if (bounciness === void 0) { bounciness = 2; }
  34808. var _this = _super.call(this) || this;
  34809. _this.bounces = bounces;
  34810. _this.bounciness = bounciness;
  34811. return _this;
  34812. }
  34813. BounceEase.prototype.easeInCore = function (gradient) {
  34814. var y = Math.max(0.0, this.bounces);
  34815. var bounciness = this.bounciness;
  34816. if (bounciness <= 1.0) {
  34817. bounciness = 1.001;
  34818. }
  34819. var num9 = Math.pow(bounciness, y);
  34820. var num5 = 1.0 - bounciness;
  34821. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  34822. var num15 = gradient * num4;
  34823. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  34824. var num3 = Math.floor(num65);
  34825. var num13 = num3 + 1.0;
  34826. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  34827. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  34828. var num7 = (num8 + num12) * 0.5;
  34829. var num6 = gradient - num7;
  34830. var num2 = num7 - num8;
  34831. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  34832. };
  34833. return BounceEase;
  34834. }(EasingFunction));
  34835. BABYLON.BounceEase = BounceEase;
  34836. var CubicEase = (function (_super) {
  34837. __extends(CubicEase, _super);
  34838. function CubicEase() {
  34839. return _super !== null && _super.apply(this, arguments) || this;
  34840. }
  34841. CubicEase.prototype.easeInCore = function (gradient) {
  34842. return (gradient * gradient * gradient);
  34843. };
  34844. return CubicEase;
  34845. }(EasingFunction));
  34846. BABYLON.CubicEase = CubicEase;
  34847. var ElasticEase = (function (_super) {
  34848. __extends(ElasticEase, _super);
  34849. function ElasticEase(oscillations, springiness) {
  34850. if (oscillations === void 0) { oscillations = 3; }
  34851. if (springiness === void 0) { springiness = 3; }
  34852. var _this = _super.call(this) || this;
  34853. _this.oscillations = oscillations;
  34854. _this.springiness = springiness;
  34855. return _this;
  34856. }
  34857. ElasticEase.prototype.easeInCore = function (gradient) {
  34858. var num2;
  34859. var num3 = Math.max(0.0, this.oscillations);
  34860. var num = Math.max(0.0, this.springiness);
  34861. if (num == 0) {
  34862. num2 = gradient;
  34863. }
  34864. else {
  34865. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  34866. }
  34867. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  34868. };
  34869. return ElasticEase;
  34870. }(EasingFunction));
  34871. BABYLON.ElasticEase = ElasticEase;
  34872. var ExponentialEase = (function (_super) {
  34873. __extends(ExponentialEase, _super);
  34874. function ExponentialEase(exponent) {
  34875. if (exponent === void 0) { exponent = 2; }
  34876. var _this = _super.call(this) || this;
  34877. _this.exponent = exponent;
  34878. return _this;
  34879. }
  34880. ExponentialEase.prototype.easeInCore = function (gradient) {
  34881. if (this.exponent <= 0) {
  34882. return gradient;
  34883. }
  34884. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  34885. };
  34886. return ExponentialEase;
  34887. }(EasingFunction));
  34888. BABYLON.ExponentialEase = ExponentialEase;
  34889. var PowerEase = (function (_super) {
  34890. __extends(PowerEase, _super);
  34891. function PowerEase(power) {
  34892. if (power === void 0) { power = 2; }
  34893. var _this = _super.call(this) || this;
  34894. _this.power = power;
  34895. return _this;
  34896. }
  34897. PowerEase.prototype.easeInCore = function (gradient) {
  34898. var y = Math.max(0.0, this.power);
  34899. return Math.pow(gradient, y);
  34900. };
  34901. return PowerEase;
  34902. }(EasingFunction));
  34903. BABYLON.PowerEase = PowerEase;
  34904. var QuadraticEase = (function (_super) {
  34905. __extends(QuadraticEase, _super);
  34906. function QuadraticEase() {
  34907. return _super !== null && _super.apply(this, arguments) || this;
  34908. }
  34909. QuadraticEase.prototype.easeInCore = function (gradient) {
  34910. return (gradient * gradient);
  34911. };
  34912. return QuadraticEase;
  34913. }(EasingFunction));
  34914. BABYLON.QuadraticEase = QuadraticEase;
  34915. var QuarticEase = (function (_super) {
  34916. __extends(QuarticEase, _super);
  34917. function QuarticEase() {
  34918. return _super !== null && _super.apply(this, arguments) || this;
  34919. }
  34920. QuarticEase.prototype.easeInCore = function (gradient) {
  34921. return (gradient * gradient * gradient * gradient);
  34922. };
  34923. return QuarticEase;
  34924. }(EasingFunction));
  34925. BABYLON.QuarticEase = QuarticEase;
  34926. var QuinticEase = (function (_super) {
  34927. __extends(QuinticEase, _super);
  34928. function QuinticEase() {
  34929. return _super !== null && _super.apply(this, arguments) || this;
  34930. }
  34931. QuinticEase.prototype.easeInCore = function (gradient) {
  34932. return (gradient * gradient * gradient * gradient * gradient);
  34933. };
  34934. return QuinticEase;
  34935. }(EasingFunction));
  34936. BABYLON.QuinticEase = QuinticEase;
  34937. var SineEase = (function (_super) {
  34938. __extends(SineEase, _super);
  34939. function SineEase() {
  34940. return _super !== null && _super.apply(this, arguments) || this;
  34941. }
  34942. SineEase.prototype.easeInCore = function (gradient) {
  34943. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  34944. };
  34945. return SineEase;
  34946. }(EasingFunction));
  34947. BABYLON.SineEase = SineEase;
  34948. var BezierCurveEase = (function (_super) {
  34949. __extends(BezierCurveEase, _super);
  34950. function BezierCurveEase(x1, y1, x2, y2) {
  34951. if (x1 === void 0) { x1 = 0; }
  34952. if (y1 === void 0) { y1 = 0; }
  34953. if (x2 === void 0) { x2 = 1; }
  34954. if (y2 === void 0) { y2 = 1; }
  34955. var _this = _super.call(this) || this;
  34956. _this.x1 = x1;
  34957. _this.y1 = y1;
  34958. _this.x2 = x2;
  34959. _this.y2 = y2;
  34960. return _this;
  34961. }
  34962. BezierCurveEase.prototype.easeInCore = function (gradient) {
  34963. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  34964. };
  34965. return BezierCurveEase;
  34966. }(EasingFunction));
  34967. BABYLON.BezierCurveEase = BezierCurveEase;
  34968. })(BABYLON || (BABYLON = {}));
  34969. //# sourceMappingURL=babylon.easing.js.map
  34970. var BABYLON;
  34971. (function (BABYLON) {
  34972. var Condition = (function () {
  34973. function Condition(actionManager) {
  34974. this._actionManager = actionManager;
  34975. }
  34976. Condition.prototype.isValid = function () {
  34977. return true;
  34978. };
  34979. Condition.prototype._getProperty = function (propertyPath) {
  34980. return this._actionManager._getProperty(propertyPath);
  34981. };
  34982. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34983. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34984. };
  34985. Condition.prototype.serialize = function () {
  34986. };
  34987. Condition.prototype._serialize = function (serializedCondition) {
  34988. return {
  34989. type: 2,
  34990. children: [],
  34991. name: serializedCondition.name,
  34992. properties: serializedCondition.properties
  34993. };
  34994. };
  34995. return Condition;
  34996. }());
  34997. BABYLON.Condition = Condition;
  34998. var ValueCondition = (function (_super) {
  34999. __extends(ValueCondition, _super);
  35000. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35001. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35002. var _this = _super.call(this, actionManager) || this;
  35003. _this.propertyPath = propertyPath;
  35004. _this.value = value;
  35005. _this.operator = operator;
  35006. _this._target = target;
  35007. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35008. _this._property = _this._getProperty(_this.propertyPath);
  35009. return _this;
  35010. }
  35011. Object.defineProperty(ValueCondition, "IsEqual", {
  35012. get: function () {
  35013. return ValueCondition._IsEqual;
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. Object.defineProperty(ValueCondition, "IsDifferent", {
  35019. get: function () {
  35020. return ValueCondition._IsDifferent;
  35021. },
  35022. enumerable: true,
  35023. configurable: true
  35024. });
  35025. Object.defineProperty(ValueCondition, "IsGreater", {
  35026. get: function () {
  35027. return ValueCondition._IsGreater;
  35028. },
  35029. enumerable: true,
  35030. configurable: true
  35031. });
  35032. Object.defineProperty(ValueCondition, "IsLesser", {
  35033. get: function () {
  35034. return ValueCondition._IsLesser;
  35035. },
  35036. enumerable: true,
  35037. configurable: true
  35038. });
  35039. // Methods
  35040. ValueCondition.prototype.isValid = function () {
  35041. switch (this.operator) {
  35042. case ValueCondition.IsGreater:
  35043. return this._effectiveTarget[this._property] > this.value;
  35044. case ValueCondition.IsLesser:
  35045. return this._effectiveTarget[this._property] < this.value;
  35046. case ValueCondition.IsEqual:
  35047. case ValueCondition.IsDifferent:
  35048. var check;
  35049. if (this.value.equals) {
  35050. check = this.value.equals(this._effectiveTarget[this._property]);
  35051. }
  35052. else {
  35053. check = this.value === this._effectiveTarget[this._property];
  35054. }
  35055. return this.operator === ValueCondition.IsEqual ? check : !check;
  35056. }
  35057. return false;
  35058. };
  35059. ValueCondition.prototype.serialize = function () {
  35060. return this._serialize({
  35061. name: "ValueCondition",
  35062. properties: [
  35063. BABYLON.Action._GetTargetProperty(this._target),
  35064. { name: "propertyPath", value: this.propertyPath },
  35065. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35066. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35067. ]
  35068. });
  35069. };
  35070. ValueCondition.GetOperatorName = function (operator) {
  35071. switch (operator) {
  35072. case ValueCondition._IsEqual: return "IsEqual";
  35073. case ValueCondition._IsDifferent: return "IsDifferent";
  35074. case ValueCondition._IsGreater: return "IsGreater";
  35075. case ValueCondition._IsLesser: return "IsLesser";
  35076. default: return "";
  35077. }
  35078. };
  35079. return ValueCondition;
  35080. }(Condition));
  35081. // Statics
  35082. ValueCondition._IsEqual = 0;
  35083. ValueCondition._IsDifferent = 1;
  35084. ValueCondition._IsGreater = 2;
  35085. ValueCondition._IsLesser = 3;
  35086. BABYLON.ValueCondition = ValueCondition;
  35087. var PredicateCondition = (function (_super) {
  35088. __extends(PredicateCondition, _super);
  35089. function PredicateCondition(actionManager, predicate) {
  35090. var _this = _super.call(this, actionManager) || this;
  35091. _this.predicate = predicate;
  35092. return _this;
  35093. }
  35094. PredicateCondition.prototype.isValid = function () {
  35095. return this.predicate();
  35096. };
  35097. return PredicateCondition;
  35098. }(Condition));
  35099. BABYLON.PredicateCondition = PredicateCondition;
  35100. var StateCondition = (function (_super) {
  35101. __extends(StateCondition, _super);
  35102. function StateCondition(actionManager, target, value) {
  35103. var _this = _super.call(this, actionManager) || this;
  35104. _this.value = value;
  35105. _this._target = target;
  35106. return _this;
  35107. }
  35108. // Methods
  35109. StateCondition.prototype.isValid = function () {
  35110. return this._target.state === this.value;
  35111. };
  35112. StateCondition.prototype.serialize = function () {
  35113. return this._serialize({
  35114. name: "StateCondition",
  35115. properties: [
  35116. BABYLON.Action._GetTargetProperty(this._target),
  35117. { name: "value", value: this.value }
  35118. ]
  35119. });
  35120. };
  35121. return StateCondition;
  35122. }(Condition));
  35123. BABYLON.StateCondition = StateCondition;
  35124. })(BABYLON || (BABYLON = {}));
  35125. //# sourceMappingURL=babylon.condition.js.map
  35126. var BABYLON;
  35127. (function (BABYLON) {
  35128. var Action = (function () {
  35129. function Action(triggerOptions, condition) {
  35130. this.triggerOptions = triggerOptions;
  35131. if (triggerOptions.parameter) {
  35132. this.trigger = triggerOptions.trigger;
  35133. this._triggerParameter = triggerOptions.parameter;
  35134. }
  35135. else {
  35136. this.trigger = triggerOptions;
  35137. }
  35138. this._nextActiveAction = this;
  35139. this._condition = condition;
  35140. }
  35141. // Methods
  35142. Action.prototype._prepare = function () {
  35143. };
  35144. Action.prototype.getTriggerParameter = function () {
  35145. return this._triggerParameter;
  35146. };
  35147. Action.prototype._executeCurrent = function (evt) {
  35148. if (this._nextActiveAction._condition) {
  35149. var condition = this._nextActiveAction._condition;
  35150. var currentRenderId = this._actionManager.getScene().getRenderId();
  35151. // We cache the current evaluation for the current frame
  35152. if (condition._evaluationId === currentRenderId) {
  35153. if (!condition._currentResult) {
  35154. return;
  35155. }
  35156. }
  35157. else {
  35158. condition._evaluationId = currentRenderId;
  35159. if (!condition.isValid()) {
  35160. condition._currentResult = false;
  35161. return;
  35162. }
  35163. condition._currentResult = true;
  35164. }
  35165. }
  35166. this._nextActiveAction.execute(evt);
  35167. this.skipToNextActiveAction();
  35168. };
  35169. Action.prototype.execute = function (evt) {
  35170. };
  35171. Action.prototype.skipToNextActiveAction = function () {
  35172. if (this._nextActiveAction._child) {
  35173. if (!this._nextActiveAction._child._actionManager) {
  35174. this._nextActiveAction._child._actionManager = this._actionManager;
  35175. }
  35176. this._nextActiveAction = this._nextActiveAction._child;
  35177. }
  35178. else {
  35179. this._nextActiveAction = this;
  35180. }
  35181. };
  35182. Action.prototype.then = function (action) {
  35183. this._child = action;
  35184. action._actionManager = this._actionManager;
  35185. action._prepare();
  35186. return action;
  35187. };
  35188. Action.prototype._getProperty = function (propertyPath) {
  35189. return this._actionManager._getProperty(propertyPath);
  35190. };
  35191. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35192. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35193. };
  35194. Action.prototype.serialize = function (parent) {
  35195. };
  35196. // Called by BABYLON.Action objects in serialize(...). Internal use
  35197. Action.prototype._serialize = function (serializedAction, parent) {
  35198. var serializationObject = {
  35199. type: 1,
  35200. children: [],
  35201. name: serializedAction.name,
  35202. properties: serializedAction.properties || []
  35203. };
  35204. // Serialize child
  35205. if (this._child) {
  35206. this._child.serialize(serializationObject);
  35207. }
  35208. // Check if "this" has a condition
  35209. if (this._condition) {
  35210. var serializedCondition = this._condition.serialize();
  35211. serializedCondition.children.push(serializationObject);
  35212. if (parent) {
  35213. parent.children.push(serializedCondition);
  35214. }
  35215. return serializedCondition;
  35216. }
  35217. if (parent) {
  35218. parent.children.push(serializationObject);
  35219. }
  35220. return serializationObject;
  35221. };
  35222. return Action;
  35223. }());
  35224. Action._SerializeValueAsString = function (value) {
  35225. if (typeof value === "number") {
  35226. return value.toString();
  35227. }
  35228. if (typeof value === "boolean") {
  35229. return value ? "true" : "false";
  35230. }
  35231. if (value instanceof BABYLON.Vector2) {
  35232. return value.x + ", " + value.y;
  35233. }
  35234. if (value instanceof BABYLON.Vector3) {
  35235. return value.x + ", " + value.y + ", " + value.z;
  35236. }
  35237. if (value instanceof BABYLON.Color3) {
  35238. return value.r + ", " + value.g + ", " + value.b;
  35239. }
  35240. if (value instanceof BABYLON.Color4) {
  35241. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35242. }
  35243. return value; // string
  35244. };
  35245. Action._GetTargetProperty = function (target) {
  35246. return {
  35247. name: "target",
  35248. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35249. : target instanceof BABYLON.Light ? "LightProperties"
  35250. : target instanceof BABYLON.Camera ? "CameraProperties"
  35251. : "SceneProperties",
  35252. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35253. };
  35254. };
  35255. BABYLON.Action = Action;
  35256. })(BABYLON || (BABYLON = {}));
  35257. //# sourceMappingURL=babylon.action.js.map
  35258. var BABYLON;
  35259. (function (BABYLON) {
  35260. /**
  35261. * ActionEvent is the event beint sent when an action is triggered.
  35262. */
  35263. var ActionEvent = (function () {
  35264. /**
  35265. * @constructor
  35266. * @param source The mesh or sprite that triggered the action.
  35267. * @param pointerX The X mouse cursor position at the time of the event
  35268. * @param pointerY The Y mouse cursor position at the time of the event
  35269. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35270. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35271. */
  35272. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35273. this.source = source;
  35274. this.pointerX = pointerX;
  35275. this.pointerY = pointerY;
  35276. this.meshUnderPointer = meshUnderPointer;
  35277. this.sourceEvent = sourceEvent;
  35278. this.additionalData = additionalData;
  35279. }
  35280. /**
  35281. * Helper function to auto-create an ActionEvent from a source mesh.
  35282. * @param source The source mesh that triggered the event
  35283. * @param evt {Event} The original (browser) event
  35284. */
  35285. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35286. var scene = source.getScene();
  35287. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35288. };
  35289. /**
  35290. * Helper function to auto-create an ActionEvent from a source mesh.
  35291. * @param source The source sprite that triggered the event
  35292. * @param scene Scene associated with the sprite
  35293. * @param evt {Event} The original (browser) event
  35294. */
  35295. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35296. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35297. };
  35298. /**
  35299. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35300. * @param scene the scene where the event occurred
  35301. * @param evt {Event} The original (browser) event
  35302. */
  35303. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35304. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35305. };
  35306. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35307. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35308. };
  35309. return ActionEvent;
  35310. }());
  35311. BABYLON.ActionEvent = ActionEvent;
  35312. /**
  35313. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35314. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35315. */
  35316. var ActionManager = (function () {
  35317. function ActionManager(scene) {
  35318. // Members
  35319. this.actions = new Array();
  35320. this.hoverCursor = '';
  35321. this._scene = scene;
  35322. scene._actionManagers.push(this);
  35323. }
  35324. Object.defineProperty(ActionManager, "NothingTrigger", {
  35325. get: function () {
  35326. return ActionManager._NothingTrigger;
  35327. },
  35328. enumerable: true,
  35329. configurable: true
  35330. });
  35331. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35332. get: function () {
  35333. return ActionManager._OnPickTrigger;
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35339. get: function () {
  35340. return ActionManager._OnLeftPickTrigger;
  35341. },
  35342. enumerable: true,
  35343. configurable: true
  35344. });
  35345. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35346. get: function () {
  35347. return ActionManager._OnRightPickTrigger;
  35348. },
  35349. enumerable: true,
  35350. configurable: true
  35351. });
  35352. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35353. get: function () {
  35354. return ActionManager._OnCenterPickTrigger;
  35355. },
  35356. enumerable: true,
  35357. configurable: true
  35358. });
  35359. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35360. get: function () {
  35361. return ActionManager._OnPickDownTrigger;
  35362. },
  35363. enumerable: true,
  35364. configurable: true
  35365. });
  35366. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  35367. get: function () {
  35368. return ActionManager._OnDoublePickTrigger;
  35369. },
  35370. enumerable: true,
  35371. configurable: true
  35372. });
  35373. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35374. get: function () {
  35375. return ActionManager._OnPickUpTrigger;
  35376. },
  35377. enumerable: true,
  35378. configurable: true
  35379. });
  35380. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35381. /// This trigger will only be raised if you also declared a OnPickDown
  35382. get: function () {
  35383. return ActionManager._OnPickOutTrigger;
  35384. },
  35385. enumerable: true,
  35386. configurable: true
  35387. });
  35388. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35389. get: function () {
  35390. return ActionManager._OnLongPressTrigger;
  35391. },
  35392. enumerable: true,
  35393. configurable: true
  35394. });
  35395. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35396. get: function () {
  35397. return ActionManager._OnPointerOverTrigger;
  35398. },
  35399. enumerable: true,
  35400. configurable: true
  35401. });
  35402. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35403. get: function () {
  35404. return ActionManager._OnPointerOutTrigger;
  35405. },
  35406. enumerable: true,
  35407. configurable: true
  35408. });
  35409. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35410. get: function () {
  35411. return ActionManager._OnEveryFrameTrigger;
  35412. },
  35413. enumerable: true,
  35414. configurable: true
  35415. });
  35416. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35417. get: function () {
  35418. return ActionManager._OnIntersectionEnterTrigger;
  35419. },
  35420. enumerable: true,
  35421. configurable: true
  35422. });
  35423. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35424. get: function () {
  35425. return ActionManager._OnIntersectionExitTrigger;
  35426. },
  35427. enumerable: true,
  35428. configurable: true
  35429. });
  35430. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35431. get: function () {
  35432. return ActionManager._OnKeyDownTrigger;
  35433. },
  35434. enumerable: true,
  35435. configurable: true
  35436. });
  35437. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35438. get: function () {
  35439. return ActionManager._OnKeyUpTrigger;
  35440. },
  35441. enumerable: true,
  35442. configurable: true
  35443. });
  35444. // Methods
  35445. ActionManager.prototype.dispose = function () {
  35446. var index = this._scene._actionManagers.indexOf(this);
  35447. for (var i = 0; i < this.actions.length; i++) {
  35448. var action = this.actions[i];
  35449. ActionManager.Triggers[action.trigger]--;
  35450. if (ActionManager.Triggers[action.trigger] === 0) {
  35451. delete ActionManager.Triggers[action.trigger];
  35452. }
  35453. }
  35454. if (index > -1) {
  35455. this._scene._actionManagers.splice(index, 1);
  35456. }
  35457. };
  35458. ActionManager.prototype.getScene = function () {
  35459. return this._scene;
  35460. };
  35461. /**
  35462. * Does this action manager handles actions of any of the given triggers
  35463. * @param {number[]} triggers - the triggers to be tested
  35464. * @return {boolean} whether one (or more) of the triggers is handeled
  35465. */
  35466. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35467. for (var index = 0; index < this.actions.length; index++) {
  35468. var action = this.actions[index];
  35469. if (triggers.indexOf(action.trigger) > -1) {
  35470. return true;
  35471. }
  35472. }
  35473. return false;
  35474. };
  35475. /**
  35476. * Does this action manager handles actions of a given trigger
  35477. * @param {number} trigger - the trigger to be tested
  35478. * @return {boolean} whether the trigger is handeled
  35479. */
  35480. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35481. for (var index = 0; index < this.actions.length; index++) {
  35482. var action = this.actions[index];
  35483. if (action.trigger === trigger) {
  35484. return true;
  35485. }
  35486. }
  35487. return false;
  35488. };
  35489. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35490. /**
  35491. * Does this action manager has pointer triggers
  35492. * @return {boolean} whether or not it has pointer triggers
  35493. */
  35494. get: function () {
  35495. for (var index = 0; index < this.actions.length; index++) {
  35496. var action = this.actions[index];
  35497. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35498. return true;
  35499. }
  35500. }
  35501. return false;
  35502. },
  35503. enumerable: true,
  35504. configurable: true
  35505. });
  35506. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35507. /**
  35508. * Does this action manager has pick triggers
  35509. * @return {boolean} whether or not it has pick triggers
  35510. */
  35511. get: function () {
  35512. for (var index = 0; index < this.actions.length; index++) {
  35513. var action = this.actions[index];
  35514. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35515. return true;
  35516. }
  35517. }
  35518. return false;
  35519. },
  35520. enumerable: true,
  35521. configurable: true
  35522. });
  35523. Object.defineProperty(ActionManager, "HasTriggers", {
  35524. /**
  35525. * Does exist one action manager with at least one trigger
  35526. * @return {boolean} whether or not it exists one action manager with one trigger
  35527. **/
  35528. get: function () {
  35529. for (var t in ActionManager.Triggers) {
  35530. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35531. return true;
  35532. }
  35533. }
  35534. return false;
  35535. },
  35536. enumerable: true,
  35537. configurable: true
  35538. });
  35539. Object.defineProperty(ActionManager, "HasPickTriggers", {
  35540. /**
  35541. * Does exist one action manager with at least one pick trigger
  35542. * @return {boolean} whether or not it exists one action manager with one pick trigger
  35543. **/
  35544. get: function () {
  35545. for (var t in ActionManager.Triggers) {
  35546. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35547. var t_int = parseInt(t);
  35548. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  35549. return true;
  35550. }
  35551. }
  35552. }
  35553. return false;
  35554. },
  35555. enumerable: true,
  35556. configurable: true
  35557. });
  35558. /**
  35559. * Does exist one action manager that handles actions of a given trigger
  35560. * @param {number} trigger - the trigger to be tested
  35561. * @return {boolean} whether the trigger is handeled by at least one action manager
  35562. **/
  35563. ActionManager.HasSpecificTrigger = function (trigger) {
  35564. for (var t in ActionManager.Triggers) {
  35565. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35566. var t_int = parseInt(t);
  35567. if (t_int === trigger) {
  35568. return true;
  35569. }
  35570. }
  35571. }
  35572. return false;
  35573. };
  35574. /**
  35575. * Registers an action to this action manager
  35576. * @param {BABYLON.Action} action - the action to be registered
  35577. * @return {BABYLON.Action} the action amended (prepared) after registration
  35578. */
  35579. ActionManager.prototype.registerAction = function (action) {
  35580. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35581. if (this.getScene().actionManager !== this) {
  35582. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35583. return null;
  35584. }
  35585. }
  35586. this.actions.push(action);
  35587. if (ActionManager.Triggers[action.trigger]) {
  35588. ActionManager.Triggers[action.trigger]++;
  35589. }
  35590. else {
  35591. ActionManager.Triggers[action.trigger] = 1;
  35592. }
  35593. action._actionManager = this;
  35594. action._prepare();
  35595. return action;
  35596. };
  35597. /**
  35598. * Process a specific trigger
  35599. * @param {number} trigger - the trigger to process
  35600. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35601. */
  35602. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35603. for (var index = 0; index < this.actions.length; index++) {
  35604. var action = this.actions[index];
  35605. if (action.trigger === trigger) {
  35606. if (trigger === ActionManager.OnKeyUpTrigger
  35607. || trigger === ActionManager.OnKeyDownTrigger) {
  35608. var parameter = action.getTriggerParameter();
  35609. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  35610. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35611. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35612. if (actualkey !== parameter.toLowerCase()) {
  35613. continue;
  35614. }
  35615. }
  35616. }
  35617. action._executeCurrent(evt);
  35618. }
  35619. }
  35620. };
  35621. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35622. var properties = propertyPath.split(".");
  35623. for (var index = 0; index < properties.length - 1; index++) {
  35624. target = target[properties[index]];
  35625. }
  35626. return target;
  35627. };
  35628. ActionManager.prototype._getProperty = function (propertyPath) {
  35629. var properties = propertyPath.split(".");
  35630. return properties[properties.length - 1];
  35631. };
  35632. ActionManager.prototype.serialize = function (name) {
  35633. var root = {
  35634. children: [],
  35635. name: name,
  35636. type: 3,
  35637. properties: [] // Empty for root but required
  35638. };
  35639. for (var i = 0; i < this.actions.length; i++) {
  35640. var triggerObject = {
  35641. type: 0,
  35642. children: [],
  35643. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35644. properties: []
  35645. };
  35646. var triggerOptions = this.actions[i].triggerOptions;
  35647. if (triggerOptions && typeof triggerOptions !== "number") {
  35648. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35649. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35650. }
  35651. else {
  35652. var parameter = {};
  35653. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35654. if (triggerOptions.parameter.mesh) {
  35655. parameter._meshId = triggerOptions.parameter.mesh.id;
  35656. }
  35657. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35658. }
  35659. }
  35660. // Serialize child action, recursively
  35661. this.actions[i].serialize(triggerObject);
  35662. // Add serialized trigger
  35663. root.children.push(triggerObject);
  35664. }
  35665. return root;
  35666. };
  35667. ActionManager.Parse = function (parsedActions, object, scene) {
  35668. var actionManager = new BABYLON.ActionManager(scene);
  35669. if (object === null)
  35670. scene.actionManager = actionManager;
  35671. else
  35672. object.actionManager = actionManager;
  35673. // instanciate a new object
  35674. var instanciate = function (name, params) {
  35675. var newInstance = Object.create(BABYLON[name].prototype);
  35676. newInstance.constructor.apply(newInstance, params);
  35677. return newInstance;
  35678. };
  35679. var parseParameter = function (name, value, target, propertyPath) {
  35680. if (propertyPath === null) {
  35681. // String, boolean or float
  35682. var floatValue = parseFloat(value);
  35683. if (value === "true" || value === "false")
  35684. return value === "true";
  35685. else
  35686. return isNaN(floatValue) ? value : floatValue;
  35687. }
  35688. var effectiveTarget = propertyPath.split(".");
  35689. var values = value.split(",");
  35690. // Get effective Target
  35691. for (var i = 0; i < effectiveTarget.length; i++) {
  35692. target = target[effectiveTarget[i]];
  35693. }
  35694. // Return appropriate value with its type
  35695. if (typeof (target) === "boolean")
  35696. return values[0] === "true";
  35697. if (typeof (target) === "string")
  35698. return values[0];
  35699. // Parameters with multiple values such as Vector3 etc.
  35700. var split = new Array();
  35701. for (var i = 0; i < values.length; i++)
  35702. split.push(parseFloat(values[i]));
  35703. if (target instanceof BABYLON.Vector3)
  35704. return BABYLON.Vector3.FromArray(split);
  35705. if (target instanceof BABYLON.Vector4)
  35706. return BABYLON.Vector4.FromArray(split);
  35707. if (target instanceof BABYLON.Color3)
  35708. return BABYLON.Color3.FromArray(split);
  35709. if (target instanceof BABYLON.Color4)
  35710. return BABYLON.Color4.FromArray(split);
  35711. return parseFloat(values[0]);
  35712. };
  35713. // traverse graph per trigger
  35714. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35715. if (combineArray === void 0) { combineArray = null; }
  35716. if (parsedAction.detached)
  35717. return;
  35718. var parameters = new Array();
  35719. var target = null;
  35720. var propertyPath = null;
  35721. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35722. // Parameters
  35723. if (parsedAction.type === 2)
  35724. parameters.push(actionManager);
  35725. else
  35726. parameters.push(trigger);
  35727. if (combine) {
  35728. var actions = new Array();
  35729. for (var j = 0; j < parsedAction.combine.length; j++) {
  35730. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35731. }
  35732. parameters.push(actions);
  35733. }
  35734. else {
  35735. for (var i = 0; i < parsedAction.properties.length; i++) {
  35736. var value = parsedAction.properties[i].value;
  35737. var name = parsedAction.properties[i].name;
  35738. var targetType = parsedAction.properties[i].targetType;
  35739. if (name === "target")
  35740. if (targetType !== null && targetType === "SceneProperties")
  35741. value = target = scene;
  35742. else
  35743. value = target = scene.getNodeByName(value);
  35744. else if (name === "parent")
  35745. value = scene.getNodeByName(value);
  35746. else if (name === "sound")
  35747. value = scene.getSoundByName(value);
  35748. else if (name !== "propertyPath") {
  35749. if (parsedAction.type === 2 && name === "operator")
  35750. value = BABYLON.ValueCondition[value];
  35751. else
  35752. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35753. }
  35754. else {
  35755. propertyPath = value;
  35756. }
  35757. parameters.push(value);
  35758. }
  35759. }
  35760. if (combineArray === null) {
  35761. parameters.push(condition);
  35762. }
  35763. else {
  35764. parameters.push(null);
  35765. }
  35766. // If interpolate value action
  35767. if (parsedAction.name === "InterpolateValueAction") {
  35768. var param = parameters[parameters.length - 2];
  35769. parameters[parameters.length - 1] = param;
  35770. parameters[parameters.length - 2] = condition;
  35771. }
  35772. // Action or condition(s) and not CombineAction
  35773. var newAction = instanciate(parsedAction.name, parameters);
  35774. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35775. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35776. if (action)
  35777. action.then(nothing);
  35778. else
  35779. actionManager.registerAction(nothing);
  35780. action = nothing;
  35781. }
  35782. if (combineArray === null) {
  35783. if (newAction instanceof BABYLON.Condition) {
  35784. condition = newAction;
  35785. newAction = action;
  35786. }
  35787. else {
  35788. condition = null;
  35789. if (action)
  35790. action.then(newAction);
  35791. else
  35792. actionManager.registerAction(newAction);
  35793. }
  35794. }
  35795. else {
  35796. combineArray.push(newAction);
  35797. }
  35798. for (var i = 0; i < parsedAction.children.length; i++)
  35799. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35800. };
  35801. // triggers
  35802. for (var i = 0; i < parsedActions.children.length; i++) {
  35803. var triggerParams;
  35804. var trigger = parsedActions.children[i];
  35805. if (trigger.properties.length > 0) {
  35806. var param = trigger.properties[0].value;
  35807. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35808. if (value._meshId) {
  35809. value.mesh = scene.getMeshByID(value._meshId);
  35810. }
  35811. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35812. }
  35813. else
  35814. triggerParams = BABYLON.ActionManager[trigger.name];
  35815. for (var j = 0; j < trigger.children.length; j++) {
  35816. if (!trigger.detached)
  35817. traverse(trigger.children[j], triggerParams, null, null);
  35818. }
  35819. }
  35820. };
  35821. ActionManager.GetTriggerName = function (trigger) {
  35822. switch (trigger) {
  35823. case 0: return "NothingTrigger";
  35824. case 1: return "OnPickTrigger";
  35825. case 2: return "OnLeftPickTrigger";
  35826. case 3: return "OnRightPickTrigger";
  35827. case 4: return "OnCenterPickTrigger";
  35828. case 5: return "OnPickDownTrigger";
  35829. case 6: return "OnPickUpTrigger";
  35830. case 7: return "OnLongPressTrigger";
  35831. case 8: return "OnPointerOverTrigger";
  35832. case 9: return "OnPointerOutTrigger";
  35833. case 10: return "OnEveryFrameTrigger";
  35834. case 11: return "OnIntersectionEnterTrigger";
  35835. case 12: return "OnIntersectionExitTrigger";
  35836. case 13: return "OnKeyDownTrigger";
  35837. case 14: return "OnKeyUpTrigger";
  35838. case 15: return "OnPickOutTrigger";
  35839. default: return "";
  35840. }
  35841. };
  35842. return ActionManager;
  35843. }());
  35844. // Statics
  35845. ActionManager._NothingTrigger = 0;
  35846. ActionManager._OnPickTrigger = 1;
  35847. ActionManager._OnLeftPickTrigger = 2;
  35848. ActionManager._OnRightPickTrigger = 3;
  35849. ActionManager._OnCenterPickTrigger = 4;
  35850. ActionManager._OnPickDownTrigger = 5;
  35851. ActionManager._OnDoublePickTrigger = 6;
  35852. ActionManager._OnPickUpTrigger = 7;
  35853. ActionManager._OnLongPressTrigger = 8;
  35854. ActionManager._OnPointerOverTrigger = 9;
  35855. ActionManager._OnPointerOutTrigger = 10;
  35856. ActionManager._OnEveryFrameTrigger = 11;
  35857. ActionManager._OnIntersectionEnterTrigger = 12;
  35858. ActionManager._OnIntersectionExitTrigger = 13;
  35859. ActionManager._OnKeyDownTrigger = 14;
  35860. ActionManager._OnKeyUpTrigger = 15;
  35861. ActionManager._OnPickOutTrigger = 16;
  35862. ActionManager.Triggers = {};
  35863. BABYLON.ActionManager = ActionManager;
  35864. })(BABYLON || (BABYLON = {}));
  35865. //# sourceMappingURL=babylon.actionManager.js.map
  35866. var BABYLON;
  35867. (function (BABYLON) {
  35868. var InterpolateValueAction = (function (_super) {
  35869. __extends(InterpolateValueAction, _super);
  35870. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35871. if (duration === void 0) { duration = 1000; }
  35872. var _this = _super.call(this, triggerOptions, condition) || this;
  35873. _this.propertyPath = propertyPath;
  35874. _this.value = value;
  35875. _this.duration = duration;
  35876. _this.stopOtherAnimations = stopOtherAnimations;
  35877. _this.onInterpolationDone = onInterpolationDone;
  35878. _this._target = _this._effectiveTarget = target;
  35879. return _this;
  35880. }
  35881. InterpolateValueAction.prototype._prepare = function () {
  35882. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35883. this._property = this._getProperty(this.propertyPath);
  35884. };
  35885. InterpolateValueAction.prototype.execute = function () {
  35886. var scene = this._actionManager.getScene();
  35887. var keys = [
  35888. {
  35889. frame: 0,
  35890. value: this._effectiveTarget[this._property]
  35891. }, {
  35892. frame: 100,
  35893. value: this.value
  35894. }
  35895. ];
  35896. var dataType;
  35897. if (typeof this.value === "number") {
  35898. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35899. }
  35900. else if (this.value instanceof BABYLON.Color3) {
  35901. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35902. }
  35903. else if (this.value instanceof BABYLON.Vector3) {
  35904. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35905. }
  35906. else if (this.value instanceof BABYLON.Matrix) {
  35907. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35908. }
  35909. else if (this.value instanceof BABYLON.Quaternion) {
  35910. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35911. }
  35912. else {
  35913. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35914. return;
  35915. }
  35916. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35917. animation.setKeys(keys);
  35918. if (this.stopOtherAnimations) {
  35919. scene.stopAnimation(this._effectiveTarget);
  35920. }
  35921. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35922. };
  35923. InterpolateValueAction.prototype.serialize = function (parent) {
  35924. return _super.prototype._serialize.call(this, {
  35925. name: "InterpolateValueAction",
  35926. properties: [
  35927. BABYLON.Action._GetTargetProperty(this._target),
  35928. { name: "propertyPath", value: this.propertyPath },
  35929. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35930. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35931. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35932. ]
  35933. }, parent);
  35934. };
  35935. return InterpolateValueAction;
  35936. }(BABYLON.Action));
  35937. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35938. })(BABYLON || (BABYLON = {}));
  35939. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35940. var BABYLON;
  35941. (function (BABYLON) {
  35942. var SwitchBooleanAction = (function (_super) {
  35943. __extends(SwitchBooleanAction, _super);
  35944. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35945. var _this = _super.call(this, triggerOptions, condition) || this;
  35946. _this.propertyPath = propertyPath;
  35947. _this._target = _this._effectiveTarget = target;
  35948. return _this;
  35949. }
  35950. SwitchBooleanAction.prototype._prepare = function () {
  35951. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35952. this._property = this._getProperty(this.propertyPath);
  35953. };
  35954. SwitchBooleanAction.prototype.execute = function () {
  35955. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35956. };
  35957. SwitchBooleanAction.prototype.serialize = function (parent) {
  35958. return _super.prototype._serialize.call(this, {
  35959. name: "SwitchBooleanAction",
  35960. properties: [
  35961. BABYLON.Action._GetTargetProperty(this._target),
  35962. { name: "propertyPath", value: this.propertyPath }
  35963. ]
  35964. }, parent);
  35965. };
  35966. return SwitchBooleanAction;
  35967. }(BABYLON.Action));
  35968. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35969. var SetStateAction = (function (_super) {
  35970. __extends(SetStateAction, _super);
  35971. function SetStateAction(triggerOptions, target, value, condition) {
  35972. var _this = _super.call(this, triggerOptions, condition) || this;
  35973. _this.value = value;
  35974. _this._target = target;
  35975. return _this;
  35976. }
  35977. SetStateAction.prototype.execute = function () {
  35978. this._target.state = this.value;
  35979. };
  35980. SetStateAction.prototype.serialize = function (parent) {
  35981. return _super.prototype._serialize.call(this, {
  35982. name: "SetStateAction",
  35983. properties: [
  35984. BABYLON.Action._GetTargetProperty(this._target),
  35985. { name: "value", value: this.value }
  35986. ]
  35987. }, parent);
  35988. };
  35989. return SetStateAction;
  35990. }(BABYLON.Action));
  35991. BABYLON.SetStateAction = SetStateAction;
  35992. var SetValueAction = (function (_super) {
  35993. __extends(SetValueAction, _super);
  35994. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35995. var _this = _super.call(this, triggerOptions, condition) || this;
  35996. _this.propertyPath = propertyPath;
  35997. _this.value = value;
  35998. _this._target = _this._effectiveTarget = target;
  35999. return _this;
  36000. }
  36001. SetValueAction.prototype._prepare = function () {
  36002. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36003. this._property = this._getProperty(this.propertyPath);
  36004. };
  36005. SetValueAction.prototype.execute = function () {
  36006. this._effectiveTarget[this._property] = this.value;
  36007. if (this._target.markAsDirty) {
  36008. this._target.markAsDirty(this._property);
  36009. }
  36010. };
  36011. SetValueAction.prototype.serialize = function (parent) {
  36012. return _super.prototype._serialize.call(this, {
  36013. name: "SetValueAction",
  36014. properties: [
  36015. BABYLON.Action._GetTargetProperty(this._target),
  36016. { name: "propertyPath", value: this.propertyPath },
  36017. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36018. ]
  36019. }, parent);
  36020. };
  36021. return SetValueAction;
  36022. }(BABYLON.Action));
  36023. BABYLON.SetValueAction = SetValueAction;
  36024. var IncrementValueAction = (function (_super) {
  36025. __extends(IncrementValueAction, _super);
  36026. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36027. var _this = _super.call(this, triggerOptions, condition) || this;
  36028. _this.propertyPath = propertyPath;
  36029. _this.value = value;
  36030. _this._target = _this._effectiveTarget = target;
  36031. return _this;
  36032. }
  36033. IncrementValueAction.prototype._prepare = function () {
  36034. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36035. this._property = this._getProperty(this.propertyPath);
  36036. if (typeof this._effectiveTarget[this._property] !== "number") {
  36037. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36038. }
  36039. };
  36040. IncrementValueAction.prototype.execute = function () {
  36041. this._effectiveTarget[this._property] += this.value;
  36042. if (this._target.markAsDirty) {
  36043. this._target.markAsDirty(this._property);
  36044. }
  36045. };
  36046. IncrementValueAction.prototype.serialize = function (parent) {
  36047. return _super.prototype._serialize.call(this, {
  36048. name: "IncrementValueAction",
  36049. properties: [
  36050. BABYLON.Action._GetTargetProperty(this._target),
  36051. { name: "propertyPath", value: this.propertyPath },
  36052. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36053. ]
  36054. }, parent);
  36055. };
  36056. return IncrementValueAction;
  36057. }(BABYLON.Action));
  36058. BABYLON.IncrementValueAction = IncrementValueAction;
  36059. var PlayAnimationAction = (function (_super) {
  36060. __extends(PlayAnimationAction, _super);
  36061. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36062. var _this = _super.call(this, triggerOptions, condition) || this;
  36063. _this.from = from;
  36064. _this.to = to;
  36065. _this.loop = loop;
  36066. _this._target = target;
  36067. return _this;
  36068. }
  36069. PlayAnimationAction.prototype._prepare = function () {
  36070. };
  36071. PlayAnimationAction.prototype.execute = function () {
  36072. var scene = this._actionManager.getScene();
  36073. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36074. };
  36075. PlayAnimationAction.prototype.serialize = function (parent) {
  36076. return _super.prototype._serialize.call(this, {
  36077. name: "PlayAnimationAction",
  36078. properties: [
  36079. BABYLON.Action._GetTargetProperty(this._target),
  36080. { name: "from", value: String(this.from) },
  36081. { name: "to", value: String(this.to) },
  36082. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36083. ]
  36084. }, parent);
  36085. };
  36086. return PlayAnimationAction;
  36087. }(BABYLON.Action));
  36088. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36089. var StopAnimationAction = (function (_super) {
  36090. __extends(StopAnimationAction, _super);
  36091. function StopAnimationAction(triggerOptions, target, condition) {
  36092. var _this = _super.call(this, triggerOptions, condition) || this;
  36093. _this._target = target;
  36094. return _this;
  36095. }
  36096. StopAnimationAction.prototype._prepare = function () {
  36097. };
  36098. StopAnimationAction.prototype.execute = function () {
  36099. var scene = this._actionManager.getScene();
  36100. scene.stopAnimation(this._target);
  36101. };
  36102. StopAnimationAction.prototype.serialize = function (parent) {
  36103. return _super.prototype._serialize.call(this, {
  36104. name: "StopAnimationAction",
  36105. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36106. }, parent);
  36107. };
  36108. return StopAnimationAction;
  36109. }(BABYLON.Action));
  36110. BABYLON.StopAnimationAction = StopAnimationAction;
  36111. var DoNothingAction = (function (_super) {
  36112. __extends(DoNothingAction, _super);
  36113. function DoNothingAction(triggerOptions, condition) {
  36114. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36115. return _super.call(this, triggerOptions, condition) || this;
  36116. }
  36117. DoNothingAction.prototype.execute = function () {
  36118. };
  36119. DoNothingAction.prototype.serialize = function (parent) {
  36120. return _super.prototype._serialize.call(this, {
  36121. name: "DoNothingAction",
  36122. properties: []
  36123. }, parent);
  36124. };
  36125. return DoNothingAction;
  36126. }(BABYLON.Action));
  36127. BABYLON.DoNothingAction = DoNothingAction;
  36128. var CombineAction = (function (_super) {
  36129. __extends(CombineAction, _super);
  36130. function CombineAction(triggerOptions, children, condition) {
  36131. var _this = _super.call(this, triggerOptions, condition) || this;
  36132. _this.children = children;
  36133. return _this;
  36134. }
  36135. CombineAction.prototype._prepare = function () {
  36136. for (var index = 0; index < this.children.length; index++) {
  36137. this.children[index]._actionManager = this._actionManager;
  36138. this.children[index]._prepare();
  36139. }
  36140. };
  36141. CombineAction.prototype.execute = function (evt) {
  36142. for (var index = 0; index < this.children.length; index++) {
  36143. this.children[index].execute(evt);
  36144. }
  36145. };
  36146. CombineAction.prototype.serialize = function (parent) {
  36147. var serializationObject = _super.prototype._serialize.call(this, {
  36148. name: "CombineAction",
  36149. properties: [],
  36150. combine: []
  36151. }, parent);
  36152. for (var i = 0; i < this.children.length; i++) {
  36153. serializationObject.combine.push(this.children[i].serialize(null));
  36154. }
  36155. return serializationObject;
  36156. };
  36157. return CombineAction;
  36158. }(BABYLON.Action));
  36159. BABYLON.CombineAction = CombineAction;
  36160. var ExecuteCodeAction = (function (_super) {
  36161. __extends(ExecuteCodeAction, _super);
  36162. function ExecuteCodeAction(triggerOptions, func, condition) {
  36163. var _this = _super.call(this, triggerOptions, condition) || this;
  36164. _this.func = func;
  36165. return _this;
  36166. }
  36167. ExecuteCodeAction.prototype.execute = function (evt) {
  36168. this.func(evt);
  36169. };
  36170. return ExecuteCodeAction;
  36171. }(BABYLON.Action));
  36172. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36173. var SetParentAction = (function (_super) {
  36174. __extends(SetParentAction, _super);
  36175. function SetParentAction(triggerOptions, target, parent, condition) {
  36176. var _this = _super.call(this, triggerOptions, condition) || this;
  36177. _this._target = target;
  36178. _this._parent = parent;
  36179. return _this;
  36180. }
  36181. SetParentAction.prototype._prepare = function () {
  36182. };
  36183. SetParentAction.prototype.execute = function () {
  36184. if (this._target.parent === this._parent) {
  36185. return;
  36186. }
  36187. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36188. invertParentWorldMatrix.invert();
  36189. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36190. this._target.parent = this._parent;
  36191. };
  36192. SetParentAction.prototype.serialize = function (parent) {
  36193. return _super.prototype._serialize.call(this, {
  36194. name: "SetParentAction",
  36195. properties: [
  36196. BABYLON.Action._GetTargetProperty(this._target),
  36197. BABYLON.Action._GetTargetProperty(this._parent),
  36198. ]
  36199. }, parent);
  36200. };
  36201. return SetParentAction;
  36202. }(BABYLON.Action));
  36203. BABYLON.SetParentAction = SetParentAction;
  36204. var PlaySoundAction = (function (_super) {
  36205. __extends(PlaySoundAction, _super);
  36206. function PlaySoundAction(triggerOptions, sound, condition) {
  36207. var _this = _super.call(this, triggerOptions, condition) || this;
  36208. _this._sound = sound;
  36209. return _this;
  36210. }
  36211. PlaySoundAction.prototype._prepare = function () {
  36212. };
  36213. PlaySoundAction.prototype.execute = function () {
  36214. if (this._sound !== undefined)
  36215. this._sound.play();
  36216. };
  36217. PlaySoundAction.prototype.serialize = function (parent) {
  36218. return _super.prototype._serialize.call(this, {
  36219. name: "PlaySoundAction",
  36220. properties: [{ name: "sound", value: this._sound.name }]
  36221. }, parent);
  36222. };
  36223. return PlaySoundAction;
  36224. }(BABYLON.Action));
  36225. BABYLON.PlaySoundAction = PlaySoundAction;
  36226. var StopSoundAction = (function (_super) {
  36227. __extends(StopSoundAction, _super);
  36228. function StopSoundAction(triggerOptions, sound, condition) {
  36229. var _this = _super.call(this, triggerOptions, condition) || this;
  36230. _this._sound = sound;
  36231. return _this;
  36232. }
  36233. StopSoundAction.prototype._prepare = function () {
  36234. };
  36235. StopSoundAction.prototype.execute = function () {
  36236. if (this._sound !== undefined)
  36237. this._sound.stop();
  36238. };
  36239. StopSoundAction.prototype.serialize = function (parent) {
  36240. return _super.prototype._serialize.call(this, {
  36241. name: "StopSoundAction",
  36242. properties: [{ name: "sound", value: this._sound.name }]
  36243. }, parent);
  36244. };
  36245. return StopSoundAction;
  36246. }(BABYLON.Action));
  36247. BABYLON.StopSoundAction = StopSoundAction;
  36248. })(BABYLON || (BABYLON = {}));
  36249. //# sourceMappingURL=babylon.directActions.js.map
  36250. var BABYLON;
  36251. (function (BABYLON) {
  36252. var SpriteManager = (function () {
  36253. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  36254. if (epsilon === void 0) { epsilon = 0.01; }
  36255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36256. this.name = name;
  36257. this.sprites = new Array();
  36258. this.renderingGroupId = 0;
  36259. this.layerMask = 0x0FFFFFFF;
  36260. this.fogEnabled = true;
  36261. this.isPickable = false;
  36262. /**
  36263. * An event triggered when the manager is disposed.
  36264. * @type {BABYLON.Observable}
  36265. */
  36266. this.onDisposeObservable = new BABYLON.Observable();
  36267. this._vertexBuffers = {};
  36268. this._capacity = capacity;
  36269. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  36270. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36271. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36272. if (cellSize.width && cellSize.height) {
  36273. this.cellWidth = cellSize.width;
  36274. this.cellHeight = cellSize.height;
  36275. }
  36276. else if (cellSize !== undefined) {
  36277. this.cellWidth = cellSize;
  36278. this.cellHeight = cellSize;
  36279. }
  36280. else {
  36281. return;
  36282. }
  36283. this._epsilon = epsilon;
  36284. this._scene = scene;
  36285. this._scene.spriteManagers.push(this);
  36286. var indices = [];
  36287. var index = 0;
  36288. for (var count = 0; count < capacity; count++) {
  36289. indices.push(index);
  36290. indices.push(index + 1);
  36291. indices.push(index + 2);
  36292. indices.push(index);
  36293. indices.push(index + 2);
  36294. indices.push(index + 3);
  36295. index += 4;
  36296. }
  36297. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36298. // VBO
  36299. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  36300. this._vertexData = new Float32Array(capacity * 16 * 4);
  36301. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  36302. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  36303. var options = this._buffer.createVertexBuffer("options", 4, 4);
  36304. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  36305. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  36306. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36307. this._vertexBuffers["options"] = options;
  36308. this._vertexBuffers["cellInfo"] = cellInfo;
  36309. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36310. // Effects
  36311. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  36312. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  36313. }
  36314. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  36315. set: function (callback) {
  36316. if (this._onDisposeObserver) {
  36317. this.onDisposeObservable.remove(this._onDisposeObserver);
  36318. }
  36319. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36320. },
  36321. enumerable: true,
  36322. configurable: true
  36323. });
  36324. Object.defineProperty(SpriteManager.prototype, "texture", {
  36325. get: function () {
  36326. return this._spriteTexture;
  36327. },
  36328. set: function (value) {
  36329. this._spriteTexture = value;
  36330. },
  36331. enumerable: true,
  36332. configurable: true
  36333. });
  36334. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  36335. var arrayOffset = index * 16;
  36336. if (offsetX === 0)
  36337. offsetX = this._epsilon;
  36338. else if (offsetX === 1)
  36339. offsetX = 1 - this._epsilon;
  36340. if (offsetY === 0)
  36341. offsetY = this._epsilon;
  36342. else if (offsetY === 1)
  36343. offsetY = 1 - this._epsilon;
  36344. this._vertexData[arrayOffset] = sprite.position.x;
  36345. this._vertexData[arrayOffset + 1] = sprite.position.y;
  36346. this._vertexData[arrayOffset + 2] = sprite.position.z;
  36347. this._vertexData[arrayOffset + 3] = sprite.angle;
  36348. this._vertexData[arrayOffset + 4] = sprite.width;
  36349. this._vertexData[arrayOffset + 5] = sprite.height;
  36350. this._vertexData[arrayOffset + 6] = offsetX;
  36351. this._vertexData[arrayOffset + 7] = offsetY;
  36352. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  36353. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  36354. var offset = (sprite.cellIndex / rowSize) >> 0;
  36355. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  36356. this._vertexData[arrayOffset + 11] = offset;
  36357. // Color
  36358. this._vertexData[arrayOffset + 12] = sprite.color.r;
  36359. this._vertexData[arrayOffset + 13] = sprite.color.g;
  36360. this._vertexData[arrayOffset + 14] = sprite.color.b;
  36361. this._vertexData[arrayOffset + 15] = sprite.color.a;
  36362. };
  36363. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  36364. var count = Math.min(this._capacity, this.sprites.length);
  36365. var min = BABYLON.Vector3.Zero();
  36366. var max = BABYLON.Vector3.Zero();
  36367. var distance = Number.MAX_VALUE;
  36368. var currentSprite;
  36369. var cameraSpacePosition = BABYLON.Vector3.Zero();
  36370. var cameraView = camera.getViewMatrix();
  36371. for (var index = 0; index < count; index++) {
  36372. var sprite = this.sprites[index];
  36373. if (!sprite) {
  36374. continue;
  36375. }
  36376. if (predicate) {
  36377. if (!predicate(sprite)) {
  36378. continue;
  36379. }
  36380. }
  36381. else if (!sprite.isPickable) {
  36382. continue;
  36383. }
  36384. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  36385. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  36386. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  36387. if (ray.intersectsBoxMinMax(min, max)) {
  36388. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  36389. if (distance > currentDistance) {
  36390. distance = currentDistance;
  36391. currentSprite = sprite;
  36392. if (fastCheck) {
  36393. break;
  36394. }
  36395. }
  36396. }
  36397. }
  36398. if (currentSprite) {
  36399. var result = new BABYLON.PickingInfo();
  36400. result.hit = true;
  36401. result.pickedSprite = currentSprite;
  36402. result.distance = distance;
  36403. return result;
  36404. }
  36405. return null;
  36406. };
  36407. SpriteManager.prototype.render = function () {
  36408. // Check
  36409. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  36410. return;
  36411. var engine = this._scene.getEngine();
  36412. var baseSize = this._spriteTexture.getBaseSize();
  36413. // Sprites
  36414. var deltaTime = engine.getDeltaTime();
  36415. var max = Math.min(this._capacity, this.sprites.length);
  36416. var rowSize = baseSize.width / this.cellWidth;
  36417. var offset = 0;
  36418. for (var index = 0; index < max; index++) {
  36419. var sprite = this.sprites[index];
  36420. if (!sprite) {
  36421. continue;
  36422. }
  36423. sprite._animate(deltaTime);
  36424. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  36425. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  36426. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  36427. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  36428. }
  36429. this._buffer.update(this._vertexData);
  36430. // Render
  36431. var effect = this._effectBase;
  36432. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36433. effect = this._effectFog;
  36434. }
  36435. engine.enableEffect(effect);
  36436. var viewMatrix = this._scene.getViewMatrix();
  36437. effect.setTexture("diffuseSampler", this._spriteTexture);
  36438. effect.setMatrix("view", viewMatrix);
  36439. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36440. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  36441. // Fog
  36442. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36443. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  36444. effect.setColor3("vFogColor", this._scene.fogColor);
  36445. }
  36446. // VBOs
  36447. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36448. // Draw order
  36449. engine.setDepthFunctionToLessOrEqual();
  36450. effect.setBool("alphaTest", true);
  36451. engine.setColorWrite(false);
  36452. engine.draw(true, 0, max * 6);
  36453. engine.setColorWrite(true);
  36454. effect.setBool("alphaTest", false);
  36455. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36456. engine.draw(true, 0, max * 6);
  36457. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36458. };
  36459. SpriteManager.prototype.dispose = function () {
  36460. if (this._buffer) {
  36461. this._buffer.dispose();
  36462. this._buffer = null;
  36463. }
  36464. if (this._indexBuffer) {
  36465. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36466. this._indexBuffer = null;
  36467. }
  36468. if (this._spriteTexture) {
  36469. this._spriteTexture.dispose();
  36470. this._spriteTexture = null;
  36471. }
  36472. // Remove from scene
  36473. var index = this._scene.spriteManagers.indexOf(this);
  36474. this._scene.spriteManagers.splice(index, 1);
  36475. // Callback
  36476. this.onDisposeObservable.notifyObservers(this);
  36477. this.onDisposeObservable.clear();
  36478. };
  36479. return SpriteManager;
  36480. }());
  36481. BABYLON.SpriteManager = SpriteManager;
  36482. })(BABYLON || (BABYLON = {}));
  36483. //# sourceMappingURL=babylon.spriteManager.js.map
  36484. var BABYLON;
  36485. (function (BABYLON) {
  36486. var Sprite = (function () {
  36487. function Sprite(name, manager) {
  36488. this.name = name;
  36489. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36490. this.width = 1.0;
  36491. this.height = 1.0;
  36492. this.angle = 0;
  36493. this.cellIndex = 0;
  36494. this.invertU = 0;
  36495. this.invertV = 0;
  36496. this.animations = new Array();
  36497. this.isPickable = false;
  36498. this._animationStarted = false;
  36499. this._loopAnimation = false;
  36500. this._fromIndex = 0;
  36501. this._toIndex = 0;
  36502. this._delay = 0;
  36503. this._direction = 1;
  36504. this._frameCount = 0;
  36505. this._time = 0;
  36506. this._manager = manager;
  36507. this._manager.sprites.push(this);
  36508. this.position = BABYLON.Vector3.Zero();
  36509. }
  36510. Object.defineProperty(Sprite.prototype, "size", {
  36511. get: function () {
  36512. return this.width;
  36513. },
  36514. set: function (value) {
  36515. this.width = value;
  36516. this.height = value;
  36517. },
  36518. enumerable: true,
  36519. configurable: true
  36520. });
  36521. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  36522. this._fromIndex = from;
  36523. this._toIndex = to;
  36524. this._loopAnimation = loop;
  36525. this._delay = delay;
  36526. this._animationStarted = true;
  36527. this._direction = from < to ? 1 : -1;
  36528. this.cellIndex = from;
  36529. this._time = 0;
  36530. this._onAnimationEnd = onAnimationEnd;
  36531. };
  36532. Sprite.prototype.stopAnimation = function () {
  36533. this._animationStarted = false;
  36534. };
  36535. Sprite.prototype._animate = function (deltaTime) {
  36536. if (!this._animationStarted)
  36537. return;
  36538. this._time += deltaTime;
  36539. if (this._time > this._delay) {
  36540. this._time = this._time % this._delay;
  36541. this.cellIndex += this._direction;
  36542. if (this.cellIndex === this._toIndex) {
  36543. if (this._loopAnimation) {
  36544. this.cellIndex = this._fromIndex;
  36545. }
  36546. else {
  36547. this._animationStarted = false;
  36548. if (this._onAnimationEnd) {
  36549. this._onAnimationEnd();
  36550. }
  36551. if (this.disposeWhenFinishedAnimating) {
  36552. this.dispose();
  36553. }
  36554. }
  36555. }
  36556. }
  36557. };
  36558. Sprite.prototype.dispose = function () {
  36559. for (var i = 0; i < this._manager.sprites.length; i++) {
  36560. if (this._manager.sprites[i] == this) {
  36561. this._manager.sprites.splice(i, 1);
  36562. }
  36563. }
  36564. };
  36565. return Sprite;
  36566. }());
  36567. BABYLON.Sprite = Sprite;
  36568. })(BABYLON || (BABYLON = {}));
  36569. //# sourceMappingURL=babylon.sprite.js.map
  36570. var BABYLON;
  36571. (function (BABYLON) {
  36572. var IntersectionInfo = (function () {
  36573. function IntersectionInfo(bu, bv, distance) {
  36574. this.bu = bu;
  36575. this.bv = bv;
  36576. this.distance = distance;
  36577. this.faceId = 0;
  36578. this.subMeshId = 0;
  36579. }
  36580. return IntersectionInfo;
  36581. }());
  36582. BABYLON.IntersectionInfo = IntersectionInfo;
  36583. var PickingInfo = (function () {
  36584. function PickingInfo() {
  36585. this.hit = false;
  36586. this.distance = 0;
  36587. this.pickedPoint = null;
  36588. this.pickedMesh = null;
  36589. this.bu = 0;
  36590. this.bv = 0;
  36591. this.faceId = -1;
  36592. this.subMeshId = 0;
  36593. this.pickedSprite = null;
  36594. }
  36595. // Methods
  36596. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  36597. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  36598. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  36599. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36600. return null;
  36601. }
  36602. var indices = this.pickedMesh.getIndices();
  36603. var result;
  36604. if (useVerticesNormals) {
  36605. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36606. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  36607. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  36608. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  36609. normal0 = normal0.scale(this.bu);
  36610. normal1 = normal1.scale(this.bv);
  36611. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  36612. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  36613. }
  36614. else {
  36615. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36616. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  36617. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  36618. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  36619. var p1p2 = vertex1.subtract(vertex2);
  36620. var p3p2 = vertex3.subtract(vertex2);
  36621. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  36622. }
  36623. if (useWorldCoordinates) {
  36624. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  36625. }
  36626. return BABYLON.Vector3.Normalize(result);
  36627. };
  36628. PickingInfo.prototype.getTextureCoordinates = function () {
  36629. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36630. return null;
  36631. }
  36632. var indices = this.pickedMesh.getIndices();
  36633. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36634. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  36635. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  36636. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  36637. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  36638. uv1 = uv1.scale(this.bu);
  36639. uv2 = uv2.scale(this.bv);
  36640. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  36641. };
  36642. return PickingInfo;
  36643. }());
  36644. BABYLON.PickingInfo = PickingInfo;
  36645. })(BABYLON || (BABYLON = {}));
  36646. //# sourceMappingURL=babylon.pickingInfo.js.map
  36647. var BABYLON;
  36648. (function (BABYLON) {
  36649. var Ray = (function () {
  36650. function Ray(origin, direction, length) {
  36651. if (length === void 0) { length = Number.MAX_VALUE; }
  36652. this.origin = origin;
  36653. this.direction = direction;
  36654. this.length = length;
  36655. }
  36656. // Methods
  36657. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  36658. var d = 0.0;
  36659. var maxValue = Number.MAX_VALUE;
  36660. var inv;
  36661. var min;
  36662. var max;
  36663. var temp;
  36664. if (Math.abs(this.direction.x) < 0.0000001) {
  36665. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  36666. return false;
  36667. }
  36668. }
  36669. else {
  36670. inv = 1.0 / this.direction.x;
  36671. min = (minimum.x - this.origin.x) * inv;
  36672. max = (maximum.x - this.origin.x) * inv;
  36673. if (max === -Infinity) {
  36674. max = Infinity;
  36675. }
  36676. if (min > max) {
  36677. temp = min;
  36678. min = max;
  36679. max = temp;
  36680. }
  36681. d = Math.max(min, d);
  36682. maxValue = Math.min(max, maxValue);
  36683. if (d > maxValue) {
  36684. return false;
  36685. }
  36686. }
  36687. if (Math.abs(this.direction.y) < 0.0000001) {
  36688. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  36689. return false;
  36690. }
  36691. }
  36692. else {
  36693. inv = 1.0 / this.direction.y;
  36694. min = (minimum.y - this.origin.y) * inv;
  36695. max = (maximum.y - this.origin.y) * inv;
  36696. if (max === -Infinity) {
  36697. max = Infinity;
  36698. }
  36699. if (min > max) {
  36700. temp = min;
  36701. min = max;
  36702. max = temp;
  36703. }
  36704. d = Math.max(min, d);
  36705. maxValue = Math.min(max, maxValue);
  36706. if (d > maxValue) {
  36707. return false;
  36708. }
  36709. }
  36710. if (Math.abs(this.direction.z) < 0.0000001) {
  36711. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  36712. return false;
  36713. }
  36714. }
  36715. else {
  36716. inv = 1.0 / this.direction.z;
  36717. min = (minimum.z - this.origin.z) * inv;
  36718. max = (maximum.z - this.origin.z) * inv;
  36719. if (max === -Infinity) {
  36720. max = Infinity;
  36721. }
  36722. if (min > max) {
  36723. temp = min;
  36724. min = max;
  36725. max = temp;
  36726. }
  36727. d = Math.max(min, d);
  36728. maxValue = Math.min(max, maxValue);
  36729. if (d > maxValue) {
  36730. return false;
  36731. }
  36732. }
  36733. return true;
  36734. };
  36735. Ray.prototype.intersectsBox = function (box) {
  36736. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  36737. };
  36738. Ray.prototype.intersectsSphere = function (sphere) {
  36739. var x = sphere.center.x - this.origin.x;
  36740. var y = sphere.center.y - this.origin.y;
  36741. var z = sphere.center.z - this.origin.z;
  36742. var pyth = (x * x) + (y * y) + (z * z);
  36743. var rr = sphere.radius * sphere.radius;
  36744. if (pyth <= rr) {
  36745. return true;
  36746. }
  36747. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  36748. if (dot < 0.0) {
  36749. return false;
  36750. }
  36751. var temp = pyth - (dot * dot);
  36752. return temp <= rr;
  36753. };
  36754. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  36755. if (!this._edge1) {
  36756. this._edge1 = BABYLON.Vector3.Zero();
  36757. this._edge2 = BABYLON.Vector3.Zero();
  36758. this._pvec = BABYLON.Vector3.Zero();
  36759. this._tvec = BABYLON.Vector3.Zero();
  36760. this._qvec = BABYLON.Vector3.Zero();
  36761. }
  36762. vertex1.subtractToRef(vertex0, this._edge1);
  36763. vertex2.subtractToRef(vertex0, this._edge2);
  36764. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  36765. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  36766. if (det === 0) {
  36767. return null;
  36768. }
  36769. var invdet = 1 / det;
  36770. this.origin.subtractToRef(vertex0, this._tvec);
  36771. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  36772. if (bu < 0 || bu > 1.0) {
  36773. return null;
  36774. }
  36775. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  36776. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  36777. if (bv < 0 || bu + bv > 1.0) {
  36778. return null;
  36779. }
  36780. //check if the distance is longer than the predefined length.
  36781. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  36782. if (distance > this.length) {
  36783. return null;
  36784. }
  36785. return new BABYLON.IntersectionInfo(bu, bv, distance);
  36786. };
  36787. Ray.prototype.intersectsPlane = function (plane) {
  36788. var distance;
  36789. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  36790. if (Math.abs(result1) < 9.99999997475243E-07) {
  36791. return null;
  36792. }
  36793. else {
  36794. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  36795. distance = (-plane.d - result2) / result1;
  36796. if (distance < 0.0) {
  36797. if (distance < -9.99999997475243E-07) {
  36798. return null;
  36799. }
  36800. else {
  36801. return 0;
  36802. }
  36803. }
  36804. return distance;
  36805. }
  36806. };
  36807. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  36808. var tm = BABYLON.Tmp.Matrix[0];
  36809. mesh.getWorldMatrix().invertToRef(tm);
  36810. if (this._tmpRay) {
  36811. Ray.TransformToRef(this, tm, this._tmpRay);
  36812. }
  36813. else {
  36814. this._tmpRay = Ray.Transform(this, tm);
  36815. }
  36816. return mesh.intersects(this._tmpRay, fastCheck);
  36817. };
  36818. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  36819. if (results) {
  36820. results.length = 0;
  36821. }
  36822. else {
  36823. results = [];
  36824. }
  36825. for (var i = 0; i < meshes.length; i++) {
  36826. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  36827. if (pickInfo.hit) {
  36828. results.push(pickInfo);
  36829. }
  36830. }
  36831. results.sort(this._comparePickingInfo);
  36832. return results;
  36833. };
  36834. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  36835. if (pickingInfoA.distance < pickingInfoB.distance) {
  36836. return -1;
  36837. }
  36838. else if (pickingInfoA.distance > pickingInfoB.distance) {
  36839. return 1;
  36840. }
  36841. else {
  36842. return 0;
  36843. }
  36844. };
  36845. /**
  36846. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  36847. * @param sega the first point of the segment to test the intersection against
  36848. * @param segb the second point of the segment to test the intersection against
  36849. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  36850. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  36851. */
  36852. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  36853. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  36854. var u = segb.subtract(sega);
  36855. var v = rsegb.subtract(this.origin);
  36856. var w = sega.subtract(this.origin);
  36857. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  36858. var b = BABYLON.Vector3.Dot(u, v);
  36859. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  36860. var d = BABYLON.Vector3.Dot(u, w);
  36861. var e = BABYLON.Vector3.Dot(v, w);
  36862. var D = a * c - b * b; // always >= 0
  36863. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  36864. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  36865. // compute the line parameters of the two closest points
  36866. if (D < Ray.smallnum) {
  36867. sN = 0.0; // force using point P0 on segment S1
  36868. sD = 1.0; // to prevent possible division by 0.0 later
  36869. tN = e;
  36870. tD = c;
  36871. }
  36872. else {
  36873. sN = (b * e - c * d);
  36874. tN = (a * e - b * d);
  36875. if (sN < 0.0) {
  36876. sN = 0.0;
  36877. tN = e;
  36878. tD = c;
  36879. }
  36880. else if (sN > sD) {
  36881. sN = sD;
  36882. tN = e + b;
  36883. tD = c;
  36884. }
  36885. }
  36886. if (tN < 0.0) {
  36887. tN = 0.0;
  36888. // recompute sc for this edge
  36889. if (-d < 0.0) {
  36890. sN = 0.0;
  36891. }
  36892. else if (-d > a)
  36893. sN = sD;
  36894. else {
  36895. sN = -d;
  36896. sD = a;
  36897. }
  36898. }
  36899. else if (tN > tD) {
  36900. tN = tD;
  36901. // recompute sc for this edge
  36902. if ((-d + b) < 0.0) {
  36903. sN = 0;
  36904. }
  36905. else if ((-d + b) > a) {
  36906. sN = sD;
  36907. }
  36908. else {
  36909. sN = (-d + b);
  36910. sD = a;
  36911. }
  36912. }
  36913. // finally do the division to get sc and tc
  36914. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  36915. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  36916. // get the difference of the two closest points
  36917. var qtc = v.multiplyByFloats(tc, tc, tc);
  36918. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  36919. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  36920. if (isIntersected) {
  36921. return qtc.length();
  36922. }
  36923. return -1;
  36924. };
  36925. // Statics
  36926. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  36927. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  36928. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  36929. var direction = end.subtract(start);
  36930. direction.normalize();
  36931. return new Ray(start, direction);
  36932. };
  36933. /**
  36934. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  36935. * transformed to the given world matrix.
  36936. * @param origin The origin point
  36937. * @param end The end point
  36938. * @param world a matrix to transform the ray to. Default is the identity matrix.
  36939. */
  36940. Ray.CreateNewFromTo = function (origin, end, world) {
  36941. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  36942. var direction = end.subtract(origin);
  36943. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  36944. direction.normalize();
  36945. return Ray.Transform(new Ray(origin, direction, length), world);
  36946. };
  36947. Ray.Transform = function (ray, matrix) {
  36948. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  36949. Ray.TransformToRef(ray, matrix, result);
  36950. return result;
  36951. };
  36952. Ray.TransformToRef = function (ray, matrix, result) {
  36953. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  36954. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  36955. result.length = ray.length;
  36956. var dir = result.direction;
  36957. var len = dir.length();
  36958. if (!(len === 0 || len === 1)) {
  36959. var num = 1.0 / len;
  36960. dir.x *= num;
  36961. dir.y *= num;
  36962. dir.z *= num;
  36963. result.length *= len;
  36964. }
  36965. };
  36966. return Ray;
  36967. }());
  36968. Ray.smallnum = 0.00000001;
  36969. Ray.rayl = 10e8;
  36970. BABYLON.Ray = Ray;
  36971. })(BABYLON || (BABYLON = {}));
  36972. //# sourceMappingURL=babylon.ray.js.map
  36973. var BABYLON;
  36974. (function (BABYLON) {
  36975. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  36976. if (boxMin.x > sphereCenter.x + sphereRadius)
  36977. return false;
  36978. if (sphereCenter.x - sphereRadius > boxMax.x)
  36979. return false;
  36980. if (boxMin.y > sphereCenter.y + sphereRadius)
  36981. return false;
  36982. if (sphereCenter.y - sphereRadius > boxMax.y)
  36983. return false;
  36984. if (boxMin.z > sphereCenter.z + sphereRadius)
  36985. return false;
  36986. if (sphereCenter.z - sphereRadius > boxMax.z)
  36987. return false;
  36988. return true;
  36989. };
  36990. var getLowestRoot = (function () {
  36991. var result = { root: 0, found: false };
  36992. return function (a, b, c, maxR) {
  36993. result.root = 0;
  36994. result.found = false;
  36995. var determinant = b * b - 4.0 * a * c;
  36996. if (determinant < 0)
  36997. return result;
  36998. var sqrtD = Math.sqrt(determinant);
  36999. var r1 = (-b - sqrtD) / (2.0 * a);
  37000. var r2 = (-b + sqrtD) / (2.0 * a);
  37001. if (r1 > r2) {
  37002. var temp = r2;
  37003. r2 = r1;
  37004. r1 = temp;
  37005. }
  37006. if (r1 > 0 && r1 < maxR) {
  37007. result.root = r1;
  37008. result.found = true;
  37009. return result;
  37010. }
  37011. if (r2 > 0 && r2 < maxR) {
  37012. result.root = r2;
  37013. result.found = true;
  37014. return result;
  37015. }
  37016. return result;
  37017. };
  37018. })();
  37019. var Collider = (function () {
  37020. function Collider() {
  37021. this.radius = new BABYLON.Vector3(1, 1, 1);
  37022. this.retry = 0;
  37023. this.basePointWorld = BABYLON.Vector3.Zero();
  37024. this.velocityWorld = BABYLON.Vector3.Zero();
  37025. this.normalizedVelocity = BABYLON.Vector3.Zero();
  37026. this._collisionPoint = BABYLON.Vector3.Zero();
  37027. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  37028. this._tempVector = BABYLON.Vector3.Zero();
  37029. this._tempVector2 = BABYLON.Vector3.Zero();
  37030. this._tempVector3 = BABYLON.Vector3.Zero();
  37031. this._tempVector4 = BABYLON.Vector3.Zero();
  37032. this._edge = BABYLON.Vector3.Zero();
  37033. this._baseToVertex = BABYLON.Vector3.Zero();
  37034. this._destinationPoint = BABYLON.Vector3.Zero();
  37035. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  37036. this._displacementVector = BABYLON.Vector3.Zero();
  37037. this._collisionMask = -1;
  37038. }
  37039. Object.defineProperty(Collider.prototype, "collisionMask", {
  37040. get: function () {
  37041. return this._collisionMask;
  37042. },
  37043. set: function (mask) {
  37044. this._collisionMask = !isNaN(mask) ? mask : -1;
  37045. },
  37046. enumerable: true,
  37047. configurable: true
  37048. });
  37049. // Methods
  37050. Collider.prototype._initialize = function (source, dir, e) {
  37051. this.velocity = dir;
  37052. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  37053. this.basePoint = source;
  37054. source.multiplyToRef(this.radius, this.basePointWorld);
  37055. dir.multiplyToRef(this.radius, this.velocityWorld);
  37056. this.velocityWorldLength = this.velocityWorld.length();
  37057. this.epsilon = e;
  37058. this.collisionFound = false;
  37059. };
  37060. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  37061. pa.subtractToRef(point, this._tempVector);
  37062. pb.subtractToRef(point, this._tempVector2);
  37063. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  37064. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37065. if (d < 0)
  37066. return false;
  37067. pc.subtractToRef(point, this._tempVector3);
  37068. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  37069. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37070. if (d < 0)
  37071. return false;
  37072. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  37073. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37074. return d >= 0;
  37075. };
  37076. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  37077. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  37078. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  37079. if (distance > this.velocityWorldLength + max + sphereRadius) {
  37080. return false;
  37081. }
  37082. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  37083. return false;
  37084. return true;
  37085. };
  37086. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  37087. var t0;
  37088. var embeddedInPlane = false;
  37089. //defensive programming, actually not needed.
  37090. if (!trianglePlaneArray) {
  37091. trianglePlaneArray = [];
  37092. }
  37093. if (!trianglePlaneArray[faceIndex]) {
  37094. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  37095. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  37096. }
  37097. var trianglePlane = trianglePlaneArray[faceIndex];
  37098. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  37099. return;
  37100. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  37101. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  37102. if (normalDotVelocity == 0) {
  37103. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  37104. return;
  37105. embeddedInPlane = true;
  37106. t0 = 0;
  37107. }
  37108. else {
  37109. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37110. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37111. if (t0 > t1) {
  37112. var temp = t1;
  37113. t1 = t0;
  37114. t0 = temp;
  37115. }
  37116. if (t0 > 1.0 || t1 < 0.0)
  37117. return;
  37118. if (t0 < 0)
  37119. t0 = 0;
  37120. if (t0 > 1.0)
  37121. t0 = 1.0;
  37122. }
  37123. this._collisionPoint.copyFromFloats(0, 0, 0);
  37124. var found = false;
  37125. var t = 1.0;
  37126. if (!embeddedInPlane) {
  37127. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  37128. this.velocity.scaleToRef(t0, this._tempVector);
  37129. this._planeIntersectionPoint.addInPlace(this._tempVector);
  37130. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  37131. found = true;
  37132. t = t0;
  37133. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  37134. }
  37135. }
  37136. if (!found) {
  37137. var velocitySquaredLength = this.velocity.lengthSquared();
  37138. var a = velocitySquaredLength;
  37139. this.basePoint.subtractToRef(p1, this._tempVector);
  37140. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37141. var c = this._tempVector.lengthSquared() - 1.0;
  37142. var lowestRoot = getLowestRoot(a, b, c, t);
  37143. if (lowestRoot.found) {
  37144. t = lowestRoot.root;
  37145. found = true;
  37146. this._collisionPoint.copyFrom(p1);
  37147. }
  37148. this.basePoint.subtractToRef(p2, this._tempVector);
  37149. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37150. c = this._tempVector.lengthSquared() - 1.0;
  37151. lowestRoot = getLowestRoot(a, b, c, t);
  37152. if (lowestRoot.found) {
  37153. t = lowestRoot.root;
  37154. found = true;
  37155. this._collisionPoint.copyFrom(p2);
  37156. }
  37157. this.basePoint.subtractToRef(p3, this._tempVector);
  37158. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37159. c = this._tempVector.lengthSquared() - 1.0;
  37160. lowestRoot = getLowestRoot(a, b, c, t);
  37161. if (lowestRoot.found) {
  37162. t = lowestRoot.root;
  37163. found = true;
  37164. this._collisionPoint.copyFrom(p3);
  37165. }
  37166. p2.subtractToRef(p1, this._edge);
  37167. p1.subtractToRef(this.basePoint, this._baseToVertex);
  37168. var edgeSquaredLength = this._edge.lengthSquared();
  37169. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37170. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37171. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37172. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37173. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37174. lowestRoot = getLowestRoot(a, b, c, t);
  37175. if (lowestRoot.found) {
  37176. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37177. if (f >= 0.0 && f <= 1.0) {
  37178. t = lowestRoot.root;
  37179. found = true;
  37180. this._edge.scaleInPlace(f);
  37181. p1.addToRef(this._edge, this._collisionPoint);
  37182. }
  37183. }
  37184. p3.subtractToRef(p2, this._edge);
  37185. p2.subtractToRef(this.basePoint, this._baseToVertex);
  37186. edgeSquaredLength = this._edge.lengthSquared();
  37187. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37188. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37189. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37190. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37191. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37192. lowestRoot = getLowestRoot(a, b, c, t);
  37193. if (lowestRoot.found) {
  37194. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37195. if (f >= 0.0 && f <= 1.0) {
  37196. t = lowestRoot.root;
  37197. found = true;
  37198. this._edge.scaleInPlace(f);
  37199. p2.addToRef(this._edge, this._collisionPoint);
  37200. }
  37201. }
  37202. p1.subtractToRef(p3, this._edge);
  37203. p3.subtractToRef(this.basePoint, this._baseToVertex);
  37204. edgeSquaredLength = this._edge.lengthSquared();
  37205. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37206. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37207. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37208. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37209. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37210. lowestRoot = getLowestRoot(a, b, c, t);
  37211. if (lowestRoot.found) {
  37212. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37213. if (f >= 0.0 && f <= 1.0) {
  37214. t = lowestRoot.root;
  37215. found = true;
  37216. this._edge.scaleInPlace(f);
  37217. p3.addToRef(this._edge, this._collisionPoint);
  37218. }
  37219. }
  37220. }
  37221. if (found) {
  37222. var distToCollision = t * this.velocity.length();
  37223. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  37224. if (!this.intersectionPoint) {
  37225. this.intersectionPoint = this._collisionPoint.clone();
  37226. }
  37227. else {
  37228. this.intersectionPoint.copyFrom(this._collisionPoint);
  37229. }
  37230. this.nearestDistance = distToCollision;
  37231. this.collisionFound = true;
  37232. }
  37233. }
  37234. };
  37235. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  37236. for (var i = indexStart; i < indexEnd; i += 3) {
  37237. var p1 = pts[indices[i] - decal];
  37238. var p2 = pts[indices[i + 1] - decal];
  37239. var p3 = pts[indices[i + 2] - decal];
  37240. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  37241. }
  37242. };
  37243. Collider.prototype._getResponse = function (pos, vel) {
  37244. pos.addToRef(vel, this._destinationPoint);
  37245. vel.scaleInPlace((this.nearestDistance / vel.length()));
  37246. this.basePoint.addToRef(vel, pos);
  37247. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  37248. this._slidePlaneNormal.normalize();
  37249. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  37250. pos.addInPlace(this._displacementVector);
  37251. this.intersectionPoint.addInPlace(this._displacementVector);
  37252. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  37253. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  37254. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  37255. };
  37256. return Collider;
  37257. }());
  37258. BABYLON.Collider = Collider;
  37259. })(BABYLON || (BABYLON = {}));
  37260. //# sourceMappingURL=babylon.collider.js.map
  37261. var BABYLON;
  37262. (function (BABYLON) {
  37263. //WebWorker code will be inserted to this variable.
  37264. BABYLON.CollisionWorker = "";
  37265. var WorkerTaskType;
  37266. (function (WorkerTaskType) {
  37267. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  37268. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  37269. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  37270. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  37271. var WorkerReplyType;
  37272. (function (WorkerReplyType) {
  37273. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  37274. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  37275. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  37276. var CollisionCoordinatorWorker = (function () {
  37277. function CollisionCoordinatorWorker() {
  37278. var _this = this;
  37279. this._scaledPosition = BABYLON.Vector3.Zero();
  37280. this._scaledVelocity = BABYLON.Vector3.Zero();
  37281. this.onMeshUpdated = function (mesh) {
  37282. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  37283. };
  37284. this.onGeometryUpdated = function (geometry) {
  37285. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  37286. };
  37287. this._afterRender = function () {
  37288. if (!_this._init)
  37289. return;
  37290. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  37291. return;
  37292. }
  37293. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  37294. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  37295. if (_this._runningUpdated > 4) {
  37296. return;
  37297. }
  37298. ++_this._runningUpdated;
  37299. var payload = {
  37300. updatedMeshes: _this._addUpdateMeshesList,
  37301. updatedGeometries: _this._addUpdateGeometriesList,
  37302. removedGeometries: _this._toRemoveGeometryArray,
  37303. removedMeshes: _this._toRemoveMeshesArray
  37304. };
  37305. var message = {
  37306. payload: payload,
  37307. taskType: WorkerTaskType.UPDATE
  37308. };
  37309. var serializable = [];
  37310. for (var id in payload.updatedGeometries) {
  37311. if (payload.updatedGeometries.hasOwnProperty(id)) {
  37312. //prepare transferables
  37313. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  37314. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  37315. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  37316. }
  37317. }
  37318. _this._worker.postMessage(message, serializable);
  37319. _this._addUpdateMeshesList = {};
  37320. _this._addUpdateGeometriesList = {};
  37321. _this._toRemoveGeometryArray = [];
  37322. _this._toRemoveMeshesArray = [];
  37323. };
  37324. this._onMessageFromWorker = function (e) {
  37325. var returnData = e.data;
  37326. if (returnData.error != WorkerReplyType.SUCCESS) {
  37327. //TODO what errors can be returned from the worker?
  37328. BABYLON.Tools.Warn("error returned from worker!");
  37329. return;
  37330. }
  37331. switch (returnData.taskType) {
  37332. case WorkerTaskType.INIT:
  37333. _this._init = true;
  37334. //Update the worked with ALL of the scene's current state
  37335. _this._scene.meshes.forEach(function (mesh) {
  37336. _this.onMeshAdded(mesh);
  37337. });
  37338. _this._scene.getGeometries().forEach(function (geometry) {
  37339. _this.onGeometryAdded(geometry);
  37340. });
  37341. break;
  37342. case WorkerTaskType.UPDATE:
  37343. _this._runningUpdated--;
  37344. break;
  37345. case WorkerTaskType.COLLIDE:
  37346. _this._runningCollisionTask = false;
  37347. var returnPayload = returnData.payload;
  37348. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  37349. return;
  37350. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  37351. //cleanup
  37352. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  37353. break;
  37354. }
  37355. };
  37356. this._collisionsCallbackArray = [];
  37357. this._init = false;
  37358. this._runningUpdated = 0;
  37359. this._runningCollisionTask = false;
  37360. this._addUpdateMeshesList = {};
  37361. this._addUpdateGeometriesList = {};
  37362. this._toRemoveGeometryArray = [];
  37363. this._toRemoveMeshesArray = [];
  37364. }
  37365. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37366. if (!this._init)
  37367. return;
  37368. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  37369. return;
  37370. position.divideToRef(collider.radius, this._scaledPosition);
  37371. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37372. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  37373. var payload = {
  37374. collider: {
  37375. position: this._scaledPosition.asArray(),
  37376. velocity: this._scaledVelocity.asArray(),
  37377. radius: collider.radius.asArray()
  37378. },
  37379. collisionId: collisionIndex,
  37380. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  37381. maximumRetry: maximumRetry
  37382. };
  37383. var message = {
  37384. payload: payload,
  37385. taskType: WorkerTaskType.COLLIDE
  37386. };
  37387. this._worker.postMessage(message);
  37388. };
  37389. CollisionCoordinatorWorker.prototype.init = function (scene) {
  37390. this._scene = scene;
  37391. this._scene.registerAfterRender(this._afterRender);
  37392. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  37393. this._worker = new Worker(workerUrl);
  37394. this._worker.onmessage = this._onMessageFromWorker;
  37395. var message = {
  37396. payload: {},
  37397. taskType: WorkerTaskType.INIT
  37398. };
  37399. this._worker.postMessage(message);
  37400. };
  37401. CollisionCoordinatorWorker.prototype.destroy = function () {
  37402. this._scene.unregisterAfterRender(this._afterRender);
  37403. this._worker.terminate();
  37404. };
  37405. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  37406. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  37407. this.onMeshUpdated(mesh);
  37408. };
  37409. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  37410. this._toRemoveMeshesArray.push(mesh.uniqueId);
  37411. };
  37412. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  37413. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  37414. geometry.onGeometryUpdated = this.onGeometryUpdated;
  37415. this.onGeometryUpdated(geometry);
  37416. };
  37417. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  37418. this._toRemoveGeometryArray.push(geometry.id);
  37419. };
  37420. return CollisionCoordinatorWorker;
  37421. }());
  37422. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  37423. var submeshes = [];
  37424. if (mesh.subMeshes) {
  37425. submeshes = mesh.subMeshes.map(function (sm, idx) {
  37426. return {
  37427. position: idx,
  37428. verticesStart: sm.verticesStart,
  37429. verticesCount: sm.verticesCount,
  37430. indexStart: sm.indexStart,
  37431. indexCount: sm.indexCount,
  37432. hasMaterial: !!sm.getMaterial(),
  37433. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37434. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  37435. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37436. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  37437. };
  37438. });
  37439. }
  37440. var geometryId = null;
  37441. if (mesh instanceof BABYLON.Mesh) {
  37442. geometryId = mesh.geometry ? mesh.geometry.id : null;
  37443. }
  37444. else if (mesh instanceof BABYLON.InstancedMesh) {
  37445. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  37446. }
  37447. return {
  37448. uniqueId: mesh.uniqueId,
  37449. id: mesh.id,
  37450. name: mesh.name,
  37451. geometryId: geometryId,
  37452. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37453. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  37454. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37455. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  37456. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  37457. subMeshes: submeshes,
  37458. checkCollisions: mesh.checkCollisions
  37459. };
  37460. };
  37461. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  37462. return {
  37463. id: geometry.id,
  37464. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  37465. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  37466. indices: new Uint32Array(geometry.getIndices() || []),
  37467. };
  37468. };
  37469. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  37470. var CollisionCoordinatorLegacy = (function () {
  37471. function CollisionCoordinatorLegacy() {
  37472. this._scaledPosition = BABYLON.Vector3.Zero();
  37473. this._scaledVelocity = BABYLON.Vector3.Zero();
  37474. this._finalPosition = BABYLON.Vector3.Zero();
  37475. }
  37476. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37477. position.divideToRef(collider.radius, this._scaledPosition);
  37478. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37479. collider.collidedMesh = null;
  37480. collider.retry = 0;
  37481. collider.initialVelocity = this._scaledVelocity;
  37482. collider.initialPosition = this._scaledPosition;
  37483. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  37484. this._finalPosition.multiplyInPlace(collider.radius);
  37485. //run the callback
  37486. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  37487. };
  37488. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  37489. this._scene = scene;
  37490. };
  37491. CollisionCoordinatorLegacy.prototype.destroy = function () {
  37492. //Legacy need no destruction method.
  37493. };
  37494. //No update in legacy mode
  37495. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  37496. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  37497. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  37498. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  37499. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  37500. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  37501. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  37502. if (excludedMesh === void 0) { excludedMesh = null; }
  37503. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  37504. if (collider.retry >= maximumRetry) {
  37505. finalPosition.copyFrom(position);
  37506. return;
  37507. }
  37508. // Check if this is a mesh else camera or -1
  37509. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  37510. collider._initialize(position, velocity, closeDistance);
  37511. // Check all meshes
  37512. for (var index = 0; index < this._scene.meshes.length; index++) {
  37513. var mesh = this._scene.meshes[index];
  37514. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  37515. mesh._checkCollision(collider);
  37516. }
  37517. }
  37518. if (!collider.collisionFound) {
  37519. position.addToRef(velocity, finalPosition);
  37520. return;
  37521. }
  37522. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  37523. collider._getResponse(position, velocity);
  37524. }
  37525. if (velocity.length() <= closeDistance) {
  37526. finalPosition.copyFrom(position);
  37527. return;
  37528. }
  37529. collider.retry++;
  37530. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  37531. };
  37532. return CollisionCoordinatorLegacy;
  37533. }());
  37534. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  37535. })(BABYLON || (BABYLON = {}));
  37536. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  37537. var BABYLON;
  37538. (function (BABYLON) {
  37539. var Particle = (function () {
  37540. function Particle() {
  37541. this.position = BABYLON.Vector3.Zero();
  37542. this.direction = BABYLON.Vector3.Zero();
  37543. this.color = new BABYLON.Color4(0, 0, 0, 0);
  37544. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  37545. this.lifeTime = 1.0;
  37546. this.age = 0;
  37547. this.size = 0;
  37548. this.angle = 0;
  37549. this.angularSpeed = 0;
  37550. }
  37551. Particle.prototype.copyTo = function (other) {
  37552. other.position.copyFrom(this.position);
  37553. other.direction.copyFrom(this.direction);
  37554. other.color.copyFrom(this.color);
  37555. other.colorStep.copyFrom(this.colorStep);
  37556. other.lifeTime = this.lifeTime;
  37557. other.age = this.age;
  37558. other.size = this.size;
  37559. other.angle = this.angle;
  37560. other.angularSpeed = this.angularSpeed;
  37561. };
  37562. return Particle;
  37563. }());
  37564. BABYLON.Particle = Particle;
  37565. })(BABYLON || (BABYLON = {}));
  37566. //# sourceMappingURL=babylon.particle.js.map
  37567. var BABYLON;
  37568. (function (BABYLON) {
  37569. var randomNumber = function (min, max) {
  37570. if (min === max) {
  37571. return (min);
  37572. }
  37573. var random = Math.random();
  37574. return ((random * (max - min)) + min);
  37575. };
  37576. var ParticleSystem = (function () {
  37577. function ParticleSystem(name, capacity, scene, customEffect) {
  37578. var _this = this;
  37579. this.name = name;
  37580. // Members
  37581. this.animations = [];
  37582. this.renderingGroupId = 0;
  37583. this.emitter = null;
  37584. this.emitRate = 10;
  37585. this.manualEmitCount = -1;
  37586. this.updateSpeed = 0.01;
  37587. this.targetStopDuration = 0;
  37588. this.disposeOnStop = false;
  37589. this.minEmitPower = 1;
  37590. this.maxEmitPower = 1;
  37591. this.minLifeTime = 1;
  37592. this.maxLifeTime = 1;
  37593. this.minSize = 1;
  37594. this.maxSize = 1;
  37595. this.minAngularSpeed = 0;
  37596. this.maxAngularSpeed = 0;
  37597. this.layerMask = 0x0FFFFFFF;
  37598. this.customShader = null;
  37599. this.preventAutoStart = false;
  37600. /**
  37601. * An event triggered when the system is disposed.
  37602. * @type {BABYLON.Observable}
  37603. */
  37604. this.onDisposeObservable = new BABYLON.Observable();
  37605. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  37606. this.forceDepthWrite = false;
  37607. this.gravity = BABYLON.Vector3.Zero();
  37608. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  37609. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  37610. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  37611. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37612. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37613. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37614. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  37615. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37616. this.particles = new Array();
  37617. this._stockParticles = new Array();
  37618. this._newPartsExcess = 0;
  37619. this._vertexBuffers = {};
  37620. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  37621. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  37622. this._scaledDirection = BABYLON.Vector3.Zero();
  37623. this._scaledGravity = BABYLON.Vector3.Zero();
  37624. this._currentRenderId = -1;
  37625. this._started = false;
  37626. this._stopped = false;
  37627. this._actualFrame = 0;
  37628. this.id = name;
  37629. this._capacity = capacity;
  37630. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37631. this._customEffect = customEffect;
  37632. scene.particleSystems.push(this);
  37633. var indices = [];
  37634. var index = 0;
  37635. for (var count = 0; count < capacity; count++) {
  37636. indices.push(index);
  37637. indices.push(index + 1);
  37638. indices.push(index + 2);
  37639. indices.push(index);
  37640. indices.push(index + 2);
  37641. indices.push(index + 3);
  37642. index += 4;
  37643. }
  37644. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37645. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  37646. this._vertexData = new Float32Array(capacity * 11 * 4);
  37647. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  37648. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  37649. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  37650. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  37651. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  37652. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  37653. this._vertexBuffers["options"] = options;
  37654. // Default behaviors
  37655. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  37656. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  37657. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  37658. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  37659. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  37660. };
  37661. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  37662. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  37663. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  37664. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  37665. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  37666. };
  37667. this.updateFunction = function (particles) {
  37668. for (var index = 0; index < particles.length; index++) {
  37669. var particle = particles[index];
  37670. particle.age += _this._scaledUpdateSpeed;
  37671. if (particle.age >= particle.lifeTime) {
  37672. _this.recycleParticle(particle);
  37673. index--;
  37674. continue;
  37675. }
  37676. else {
  37677. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  37678. particle.color.addInPlace(_this._scaledColorStep);
  37679. if (particle.color.a < 0)
  37680. particle.color.a = 0;
  37681. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  37682. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  37683. particle.position.addInPlace(_this._scaledDirection);
  37684. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  37685. particle.direction.addInPlace(_this._scaledGravity);
  37686. }
  37687. }
  37688. };
  37689. }
  37690. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  37691. set: function (callback) {
  37692. if (this._onDisposeObserver) {
  37693. this.onDisposeObservable.remove(this._onDisposeObserver);
  37694. }
  37695. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37696. },
  37697. enumerable: true,
  37698. configurable: true
  37699. });
  37700. ParticleSystem.prototype.recycleParticle = function (particle) {
  37701. var lastParticle = this.particles.pop();
  37702. if (lastParticle !== particle) {
  37703. lastParticle.copyTo(particle);
  37704. this._stockParticles.push(lastParticle);
  37705. }
  37706. };
  37707. ParticleSystem.prototype.getCapacity = function () {
  37708. return this._capacity;
  37709. };
  37710. ParticleSystem.prototype.isAlive = function () {
  37711. return this._alive;
  37712. };
  37713. ParticleSystem.prototype.isStarted = function () {
  37714. return this._started;
  37715. };
  37716. ParticleSystem.prototype.start = function () {
  37717. this._started = true;
  37718. this._stopped = false;
  37719. this._actualFrame = 0;
  37720. };
  37721. ParticleSystem.prototype.stop = function () {
  37722. this._stopped = true;
  37723. };
  37724. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  37725. var offset = index * 11;
  37726. this._vertexData[offset] = particle.position.x;
  37727. this._vertexData[offset + 1] = particle.position.y;
  37728. this._vertexData[offset + 2] = particle.position.z;
  37729. this._vertexData[offset + 3] = particle.color.r;
  37730. this._vertexData[offset + 4] = particle.color.g;
  37731. this._vertexData[offset + 5] = particle.color.b;
  37732. this._vertexData[offset + 6] = particle.color.a;
  37733. this._vertexData[offset + 7] = particle.angle;
  37734. this._vertexData[offset + 8] = particle.size;
  37735. this._vertexData[offset + 9] = offsetX;
  37736. this._vertexData[offset + 10] = offsetY;
  37737. };
  37738. ParticleSystem.prototype._update = function (newParticles) {
  37739. // Update current
  37740. this._alive = this.particles.length > 0;
  37741. this.updateFunction(this.particles);
  37742. // Add new ones
  37743. var worldMatrix;
  37744. if (this.emitter.position) {
  37745. worldMatrix = this.emitter.getWorldMatrix();
  37746. }
  37747. else {
  37748. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  37749. }
  37750. var particle;
  37751. for (var index = 0; index < newParticles; index++) {
  37752. if (this.particles.length === this._capacity) {
  37753. break;
  37754. }
  37755. if (this._stockParticles.length !== 0) {
  37756. particle = this._stockParticles.pop();
  37757. particle.age = 0;
  37758. }
  37759. else {
  37760. particle = new BABYLON.Particle();
  37761. }
  37762. this.particles.push(particle);
  37763. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  37764. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  37765. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  37766. particle.size = randomNumber(this.minSize, this.maxSize);
  37767. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  37768. this.startPositionFunction(worldMatrix, particle.position, particle);
  37769. var step = randomNumber(0, 1.0);
  37770. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  37771. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  37772. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  37773. }
  37774. };
  37775. ParticleSystem.prototype._getEffect = function () {
  37776. if (this._customEffect) {
  37777. return this._customEffect;
  37778. }
  37779. ;
  37780. var defines = [];
  37781. if (this._scene.clipPlane) {
  37782. defines.push("#define CLIPPLANE");
  37783. }
  37784. // Effect
  37785. var join = defines.join("\n");
  37786. if (this._cachedDefines !== join) {
  37787. this._cachedDefines = join;
  37788. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  37789. }
  37790. return this._effect;
  37791. };
  37792. ParticleSystem.prototype.animate = function () {
  37793. if (!this._started)
  37794. return;
  37795. var effect = this._getEffect();
  37796. // Check
  37797. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  37798. return;
  37799. if (this._currentRenderId === this._scene.getRenderId()) {
  37800. return;
  37801. }
  37802. this._currentRenderId = this._scene.getRenderId();
  37803. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  37804. // determine the number of particles we need to create
  37805. var newParticles;
  37806. if (this.manualEmitCount > -1) {
  37807. newParticles = this.manualEmitCount;
  37808. this._newPartsExcess = 0;
  37809. this.manualEmitCount = 0;
  37810. }
  37811. else {
  37812. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  37813. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  37814. }
  37815. if (this._newPartsExcess > 1.0) {
  37816. newParticles += this._newPartsExcess >> 0;
  37817. this._newPartsExcess -= this._newPartsExcess >> 0;
  37818. }
  37819. this._alive = false;
  37820. if (!this._stopped) {
  37821. this._actualFrame += this._scaledUpdateSpeed;
  37822. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  37823. this.stop();
  37824. }
  37825. else {
  37826. newParticles = 0;
  37827. }
  37828. this._update(newParticles);
  37829. // Stopped?
  37830. if (this._stopped) {
  37831. if (!this._alive) {
  37832. this._started = false;
  37833. if (this.disposeOnStop) {
  37834. this._scene._toBeDisposed.push(this);
  37835. }
  37836. }
  37837. }
  37838. // Update VBO
  37839. var offset = 0;
  37840. for (var index = 0; index < this.particles.length; index++) {
  37841. var particle = this.particles[index];
  37842. this._appendParticleVertex(offset++, particle, 0, 0);
  37843. this._appendParticleVertex(offset++, particle, 1, 0);
  37844. this._appendParticleVertex(offset++, particle, 1, 1);
  37845. this._appendParticleVertex(offset++, particle, 0, 1);
  37846. }
  37847. this._vertexBuffer.update(this._vertexData);
  37848. };
  37849. ParticleSystem.prototype.render = function () {
  37850. var effect = this._getEffect();
  37851. // Check
  37852. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  37853. return 0;
  37854. var engine = this._scene.getEngine();
  37855. // Render
  37856. engine.enableEffect(effect);
  37857. engine.setState(false);
  37858. var viewMatrix = this._scene.getViewMatrix();
  37859. effect.setTexture("diffuseSampler", this.particleTexture);
  37860. effect.setMatrix("view", viewMatrix);
  37861. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  37862. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  37863. if (this._scene.clipPlane) {
  37864. var clipPlane = this._scene.clipPlane;
  37865. var invView = viewMatrix.clone();
  37866. invView.invert();
  37867. effect.setMatrix("invView", invView);
  37868. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37869. }
  37870. // VBOs
  37871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37872. // Draw order
  37873. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  37874. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  37875. }
  37876. else {
  37877. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37878. }
  37879. if (this.forceDepthWrite) {
  37880. engine.setDepthWrite(true);
  37881. }
  37882. engine.draw(true, 0, this.particles.length * 6);
  37883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37884. return this.particles.length;
  37885. };
  37886. ParticleSystem.prototype.dispose = function () {
  37887. if (this._vertexBuffer) {
  37888. this._vertexBuffer.dispose();
  37889. this._vertexBuffer = null;
  37890. }
  37891. if (this._indexBuffer) {
  37892. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37893. this._indexBuffer = null;
  37894. }
  37895. if (this.particleTexture) {
  37896. this.particleTexture.dispose();
  37897. this.particleTexture = null;
  37898. }
  37899. // Remove from scene
  37900. var index = this._scene.particleSystems.indexOf(this);
  37901. this._scene.particleSystems.splice(index, 1);
  37902. // Callback
  37903. this.onDisposeObservable.notifyObservers(this);
  37904. this.onDisposeObservable.clear();
  37905. };
  37906. // Clone
  37907. ParticleSystem.prototype.clone = function (name, newEmitter) {
  37908. var custom = null;
  37909. var program = null;
  37910. if (this.customShader != null) {
  37911. program = this.customShader;
  37912. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  37913. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  37914. }
  37915. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  37916. result.customShader = program;
  37917. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  37918. if (newEmitter === undefined) {
  37919. newEmitter = this.emitter;
  37920. }
  37921. result.emitter = newEmitter;
  37922. if (this.particleTexture) {
  37923. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  37924. }
  37925. if (!this.preventAutoStart) {
  37926. result.start();
  37927. }
  37928. return result;
  37929. };
  37930. ParticleSystem.prototype.serialize = function () {
  37931. var serializationObject = {};
  37932. serializationObject.name = this.name;
  37933. serializationObject.id = this.id;
  37934. // Emitter
  37935. if (this.emitter.position) {
  37936. serializationObject.emitterId = this.emitter.id;
  37937. }
  37938. else {
  37939. serializationObject.emitter = this.emitter.asArray();
  37940. }
  37941. serializationObject.capacity = this.getCapacity();
  37942. if (this.particleTexture) {
  37943. serializationObject.textureName = this.particleTexture.name;
  37944. }
  37945. // Animations
  37946. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  37947. // Particle system
  37948. serializationObject.minAngularSpeed = this.minAngularSpeed;
  37949. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  37950. serializationObject.minSize = this.minSize;
  37951. serializationObject.maxSize = this.maxSize;
  37952. serializationObject.minEmitPower = this.minEmitPower;
  37953. serializationObject.maxEmitPower = this.maxEmitPower;
  37954. serializationObject.minLifeTime = this.minLifeTime;
  37955. serializationObject.maxLifeTime = this.maxLifeTime;
  37956. serializationObject.emitRate = this.emitRate;
  37957. serializationObject.minEmitBox = this.minEmitBox.asArray();
  37958. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  37959. serializationObject.gravity = this.gravity.asArray();
  37960. serializationObject.direction1 = this.direction1.asArray();
  37961. serializationObject.direction2 = this.direction2.asArray();
  37962. serializationObject.color1 = this.color1.asArray();
  37963. serializationObject.color2 = this.color2.asArray();
  37964. serializationObject.colorDead = this.colorDead.asArray();
  37965. serializationObject.updateSpeed = this.updateSpeed;
  37966. serializationObject.targetStopDuration = this.targetStopDuration;
  37967. serializationObject.textureMask = this.textureMask.asArray();
  37968. serializationObject.blendMode = this.blendMode;
  37969. serializationObject.customShader = this.customShader;
  37970. serializationObject.preventAutoStart = this.preventAutoStart;
  37971. return serializationObject;
  37972. };
  37973. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  37974. var name = parsedParticleSystem.name;
  37975. var custom = null;
  37976. var program = null;
  37977. if (parsedParticleSystem.customShader) {
  37978. program = parsedParticleSystem.customShader;
  37979. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  37980. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  37981. }
  37982. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  37983. particleSystem.customShader = program;
  37984. if (parsedParticleSystem.id) {
  37985. particleSystem.id = parsedParticleSystem.id;
  37986. }
  37987. // Auto start
  37988. if (parsedParticleSystem.preventAutoStart) {
  37989. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  37990. }
  37991. // Texture
  37992. if (parsedParticleSystem.textureName) {
  37993. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  37994. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  37995. }
  37996. // Emitter
  37997. if (parsedParticleSystem.emitterId) {
  37998. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  37999. }
  38000. else {
  38001. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  38002. }
  38003. // Animations
  38004. if (parsedParticleSystem.animations) {
  38005. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  38006. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  38007. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  38008. }
  38009. }
  38010. if (parsedParticleSystem.autoAnimate) {
  38011. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  38012. }
  38013. // Particle system
  38014. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  38015. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  38016. particleSystem.minSize = parsedParticleSystem.minSize;
  38017. particleSystem.maxSize = parsedParticleSystem.maxSize;
  38018. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  38019. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  38020. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  38021. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  38022. particleSystem.emitRate = parsedParticleSystem.emitRate;
  38023. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  38024. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  38025. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  38026. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  38027. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  38028. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  38029. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  38030. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  38031. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  38032. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  38033. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  38034. particleSystem.blendMode = parsedParticleSystem.blendMode;
  38035. if (!particleSystem.preventAutoStart) {
  38036. particleSystem.start();
  38037. }
  38038. return particleSystem;
  38039. };
  38040. return ParticleSystem;
  38041. }());
  38042. // Statics
  38043. ParticleSystem.BLENDMODE_ONEONE = 0;
  38044. ParticleSystem.BLENDMODE_STANDARD = 1;
  38045. BABYLON.ParticleSystem = ParticleSystem;
  38046. })(BABYLON || (BABYLON = {}));
  38047. //# sourceMappingURL=babylon.particleSystem.js.map
  38048. var BABYLON;
  38049. (function (BABYLON) {
  38050. var SolidParticle = (function () {
  38051. /**
  38052. * Creates a Solid Particle object.
  38053. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  38054. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  38055. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  38056. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  38057. * `shapeId` (integer) is the model shape identifier in the SPS.
  38058. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  38059. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  38060. */
  38061. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  38062. this.idx = 0; // particle global index
  38063. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  38064. this.position = BABYLON.Vector3.Zero(); // position
  38065. this.rotation = BABYLON.Vector3.Zero(); // rotation
  38066. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  38067. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  38068. this.velocity = BABYLON.Vector3.Zero(); // velocity
  38069. this.alive = true; // alive
  38070. this.isVisible = true; // visibility
  38071. this._pos = 0; // index of this particle in the global "positions" array
  38072. this.shapeId = 0; // model shape id
  38073. this.idxInShape = 0; // index of the particle in its shape id
  38074. this.idx = particleIndex;
  38075. this._pos = positionIndex;
  38076. this._model = model;
  38077. this.shapeId = shapeId;
  38078. this.idxInShape = idxInShape;
  38079. this._sps = sps;
  38080. if (modelBoundingInfo) {
  38081. this._modelBoundingInfo = modelBoundingInfo;
  38082. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  38083. }
  38084. }
  38085. Object.defineProperty(SolidParticle.prototype, "scale", {
  38086. /**
  38087. * legacy support, changed scale to scaling
  38088. */
  38089. get: function () {
  38090. return this.scaling;
  38091. },
  38092. set: function (scale) {
  38093. this.scaling = scale;
  38094. },
  38095. enumerable: true,
  38096. configurable: true
  38097. });
  38098. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  38099. /**
  38100. * legacy support, changed quaternion to rotationQuaternion
  38101. */
  38102. get: function () {
  38103. return this.rotationQuaternion;
  38104. },
  38105. set: function (q) {
  38106. this.rotationQuaternion = q;
  38107. },
  38108. enumerable: true,
  38109. configurable: true
  38110. });
  38111. /**
  38112. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  38113. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  38114. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  38115. */
  38116. SolidParticle.prototype.intersectsMesh = function (target) {
  38117. if (!this._boundingInfo || !target._boundingInfo) {
  38118. return false;
  38119. }
  38120. if (this._sps._bSphereOnly) {
  38121. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  38122. }
  38123. return this._boundingInfo.intersects(target._boundingInfo, false);
  38124. };
  38125. return SolidParticle;
  38126. }());
  38127. BABYLON.SolidParticle = SolidParticle;
  38128. var ModelShape = (function () {
  38129. /**
  38130. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  38131. * SPS internal tool, don't use it manually.
  38132. */
  38133. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38134. this.shapeID = id;
  38135. this._shape = shape;
  38136. this._shapeUV = shapeUV;
  38137. this._positionFunction = posFunction;
  38138. this._vertexFunction = vtxFunction;
  38139. }
  38140. return ModelShape;
  38141. }());
  38142. BABYLON.ModelShape = ModelShape;
  38143. })(BABYLON || (BABYLON = {}));
  38144. //# sourceMappingURL=babylon.solidParticle.js.map
  38145. var BABYLON;
  38146. (function (BABYLON) {
  38147. /**
  38148. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  38149. */
  38150. var SolidParticleSystem = (function () {
  38151. /**
  38152. * Creates a SPS (Solid Particle System) object.
  38153. * `name` (String) is the SPS name, this will be the underlying mesh name.
  38154. * `scene` (Scene) is the scene in which the SPS is added.
  38155. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  38156. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  38157. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  38158. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  38159. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  38160. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  38161. */
  38162. function SolidParticleSystem(name, scene, options) {
  38163. // public members
  38164. /**
  38165. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38166. * Example : var p = SPS.particles[i];
  38167. */
  38168. this.particles = new Array();
  38169. /**
  38170. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38171. */
  38172. this.nbParticles = 0;
  38173. /**
  38174. * If the particles must ever face the camera (default false). Useful for planar particles.
  38175. */
  38176. this.billboard = false;
  38177. /**
  38178. * Recompute normals when adding a shape
  38179. */
  38180. this.recomputeNormals = true;
  38181. /**
  38182. * This a counter ofr your own usage. It's not set by any SPS functions.
  38183. */
  38184. this.counter = 0;
  38185. /**
  38186. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38187. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  38188. */
  38189. this.vars = {};
  38190. this._positions = new Array();
  38191. this._indices = new Array();
  38192. this._normals = new Array();
  38193. this._colors = new Array();
  38194. this._uvs = new Array();
  38195. this._index = 0; // indices index
  38196. this._updatable = true;
  38197. this._pickable = false;
  38198. this._isVisibilityBoxLocked = false;
  38199. this._alwaysVisible = false;
  38200. this._shapeCounter = 0;
  38201. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  38202. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38203. this._computeParticleColor = true;
  38204. this._computeParticleTexture = true;
  38205. this._computeParticleRotation = true;
  38206. this._computeParticleVertex = false;
  38207. this._computeBoundingBox = false;
  38208. this._cam_axisZ = BABYLON.Vector3.Zero();
  38209. this._cam_axisY = BABYLON.Vector3.Zero();
  38210. this._cam_axisX = BABYLON.Vector3.Zero();
  38211. this._axisX = BABYLON.Axis.X;
  38212. this._axisY = BABYLON.Axis.Y;
  38213. this._axisZ = BABYLON.Axis.Z;
  38214. this._camDir = BABYLON.Vector3.Zero();
  38215. this._rotMatrix = new BABYLON.Matrix();
  38216. this._invertMatrix = new BABYLON.Matrix();
  38217. this._rotated = BABYLON.Vector3.Zero();
  38218. this._quaternion = new BABYLON.Quaternion();
  38219. this._vertex = BABYLON.Vector3.Zero();
  38220. this._normal = BABYLON.Vector3.Zero();
  38221. this._yaw = 0.0;
  38222. this._pitch = 0.0;
  38223. this._roll = 0.0;
  38224. this._halfroll = 0.0;
  38225. this._halfpitch = 0.0;
  38226. this._halfyaw = 0.0;
  38227. this._sinRoll = 0.0;
  38228. this._cosRoll = 0.0;
  38229. this._sinPitch = 0.0;
  38230. this._cosPitch = 0.0;
  38231. this._sinYaw = 0.0;
  38232. this._cosYaw = 0.0;
  38233. this._w = 0.0;
  38234. this._mustUnrotateFixedNormals = false;
  38235. this._minimum = BABYLON.Tmp.Vector3[0];
  38236. this._maximum = BABYLON.Tmp.Vector3[1];
  38237. this._scale = BABYLON.Tmp.Vector3[2];
  38238. this._translation = BABYLON.Tmp.Vector3[3];
  38239. this._minBbox = BABYLON.Tmp.Vector3[4];
  38240. this._maxBbox = BABYLON.Tmp.Vector3[5];
  38241. this._particlesIntersect = false;
  38242. this._bSphereOnly = false;
  38243. this._bSphereRadiusFactor = 1.0;
  38244. this.name = name;
  38245. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38246. this._camera = scene.activeCamera;
  38247. this._pickable = options ? options.isPickable : false;
  38248. this._particlesIntersect = options ? options.particleIntersection : false;
  38249. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  38250. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  38251. if (options && options.updatable) {
  38252. this._updatable = options.updatable;
  38253. }
  38254. else {
  38255. this._updatable = true;
  38256. }
  38257. if (this._pickable) {
  38258. this.pickedParticles = [];
  38259. }
  38260. }
  38261. /**
  38262. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38263. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  38264. */
  38265. SolidParticleSystem.prototype.buildMesh = function () {
  38266. if (this.nbParticles === 0) {
  38267. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38268. this.addShape(triangle, 1);
  38269. triangle.dispose();
  38270. }
  38271. this._positions32 = new Float32Array(this._positions);
  38272. this._uvs32 = new Float32Array(this._uvs);
  38273. this._colors32 = new Float32Array(this._colors);
  38274. if (this.recomputeNormals) {
  38275. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38276. }
  38277. this._normals32 = new Float32Array(this._normals);
  38278. this._fixedNormal32 = new Float32Array(this._normals);
  38279. if (this._mustUnrotateFixedNormals) {
  38280. this._unrotateFixedNormals();
  38281. }
  38282. var vertexData = new BABYLON.VertexData();
  38283. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38284. vertexData.indices = this._indices;
  38285. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38286. if (this._uvs32) {
  38287. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38288. ;
  38289. }
  38290. if (this._colors32) {
  38291. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38292. }
  38293. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38294. vertexData.applyToMesh(mesh, this._updatable);
  38295. this.mesh = mesh;
  38296. this.mesh.isPickable = this._pickable;
  38297. // free memory
  38298. this._positions = null;
  38299. this._normals = null;
  38300. this._uvs = null;
  38301. this._colors = null;
  38302. if (!this._updatable) {
  38303. this.particles.length = 0;
  38304. }
  38305. return mesh;
  38306. };
  38307. /**
  38308. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  38309. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38310. * Thus the particles generated from `digest()` have their property `position` set yet.
  38311. * `mesh` ( Mesh ) is the mesh to be digested
  38312. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  38313. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  38314. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  38315. */
  38316. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38317. var size = (options && options.facetNb) || 1;
  38318. var number = (options && options.number);
  38319. var delta = (options && options.delta) || 0;
  38320. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38321. var meshInd = mesh.getIndices();
  38322. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38323. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38324. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38325. var f = 0; // facet counter
  38326. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38327. // compute size from number
  38328. if (number) {
  38329. number = (number > totalFacets) ? totalFacets : number;
  38330. size = Math.round(totalFacets / number);
  38331. delta = 0;
  38332. }
  38333. else {
  38334. size = (size > totalFacets) ? totalFacets : size;
  38335. }
  38336. var facetPos = []; // submesh positions
  38337. var facetInd = []; // submesh indices
  38338. var facetUV = []; // submesh UV
  38339. var facetCol = []; // submesh colors
  38340. var barycenter = BABYLON.Tmp.Vector3[0];
  38341. var rand;
  38342. var sizeO = size;
  38343. while (f < totalFacets) {
  38344. size = sizeO + Math.floor((1 + delta) * Math.random());
  38345. if (f > totalFacets - size) {
  38346. size = totalFacets - f;
  38347. }
  38348. // reset temp arrays
  38349. facetPos.length = 0;
  38350. facetInd.length = 0;
  38351. facetUV.length = 0;
  38352. facetCol.length = 0;
  38353. // iterate over "size" facets
  38354. var fi = 0;
  38355. for (var j = f * 3; j < (f + size) * 3; j++) {
  38356. facetInd.push(fi);
  38357. var i = meshInd[j];
  38358. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38359. if (meshUV) {
  38360. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38361. }
  38362. if (meshCol) {
  38363. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38364. }
  38365. fi++;
  38366. }
  38367. // create a model shape for each single particle
  38368. var idx = this.nbParticles;
  38369. var shape = this._posToShape(facetPos);
  38370. var shapeUV = this._uvsToShapeUV(facetUV);
  38371. // compute the barycenter of the shape
  38372. var v;
  38373. for (v = 0; v < shape.length; v++) {
  38374. barycenter.addInPlace(shape[v]);
  38375. }
  38376. barycenter.scaleInPlace(1 / shape.length);
  38377. // shift the shape from its barycenter to the origin
  38378. for (v = 0; v < shape.length; v++) {
  38379. shape[v].subtractInPlace(barycenter);
  38380. }
  38381. var bInfo;
  38382. if (this._particlesIntersect) {
  38383. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  38384. }
  38385. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38386. // add the particle in the SPS
  38387. var currentPos = this._positions.length;
  38388. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  38389. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  38390. // initialize the particle position
  38391. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38392. this._index += shape.length;
  38393. idx++;
  38394. this.nbParticles++;
  38395. this._shapeCounter++;
  38396. f += size;
  38397. }
  38398. return this;
  38399. };
  38400. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  38401. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  38402. var index = 0;
  38403. var idx = 0;
  38404. for (var p = 0; p < this.particles.length; p++) {
  38405. this._particle = this.particles[p];
  38406. this._shape = this._particle._model._shape;
  38407. if (this._particle.rotationQuaternion) {
  38408. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38409. }
  38410. else {
  38411. this._yaw = this._particle.rotation.y;
  38412. this._pitch = this._particle.rotation.x;
  38413. this._roll = this._particle.rotation.z;
  38414. this._quaternionRotationYPR();
  38415. }
  38416. this._quaternionToRotationMatrix();
  38417. this._rotMatrix.invertToRef(this._invertMatrix);
  38418. for (var pt = 0; pt < this._shape.length; pt++) {
  38419. idx = index + pt * 3;
  38420. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  38421. this._fixedNormal32[idx] = this._normal.x;
  38422. this._fixedNormal32[idx + 1] = this._normal.y;
  38423. this._fixedNormal32[idx + 2] = this._normal.z;
  38424. }
  38425. index = idx + 3;
  38426. }
  38427. };
  38428. //reset copy
  38429. SolidParticleSystem.prototype._resetCopy = function () {
  38430. this._copy.position.x = 0;
  38431. this._copy.position.y = 0;
  38432. this._copy.position.z = 0;
  38433. this._copy.rotation.x = 0;
  38434. this._copy.rotation.y = 0;
  38435. this._copy.rotation.z = 0;
  38436. this._copy.rotationQuaternion = null;
  38437. this._copy.scaling.x = 1;
  38438. this._copy.scaling.y = 1;
  38439. this._copy.scaling.z = 1;
  38440. this._copy.uvs.x = 0;
  38441. this._copy.uvs.y = 0;
  38442. this._copy.uvs.z = 1;
  38443. this._copy.uvs.w = 1;
  38444. this._copy.color = null;
  38445. };
  38446. // _meshBuilder : inserts the shape model in the global SPS mesh
  38447. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  38448. var i;
  38449. var u = 0;
  38450. var c = 0;
  38451. var n = 0;
  38452. this._resetCopy();
  38453. if (options && options.positionFunction) {
  38454. options.positionFunction(this._copy, idx, idxInShape);
  38455. this._mustUnrotateFixedNormals = true;
  38456. }
  38457. if (this._copy.rotationQuaternion) {
  38458. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38459. }
  38460. else {
  38461. this._yaw = this._copy.rotation.y;
  38462. this._pitch = this._copy.rotation.x;
  38463. this._roll = this._copy.rotation.z;
  38464. this._quaternionRotationYPR();
  38465. }
  38466. this._quaternionToRotationMatrix();
  38467. for (i = 0; i < shape.length; i++) {
  38468. this._vertex.x = shape[i].x;
  38469. this._vertex.y = shape[i].y;
  38470. this._vertex.z = shape[i].z;
  38471. if (options && options.vertexFunction) {
  38472. options.vertexFunction(this._copy, this._vertex, i);
  38473. }
  38474. this._vertex.x *= this._copy.scaling.x;
  38475. this._vertex.y *= this._copy.scaling.y;
  38476. this._vertex.z *= this._copy.scaling.z;
  38477. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38478. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38479. if (meshUV) {
  38480. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  38481. u += 2;
  38482. }
  38483. if (this._copy.color) {
  38484. this._color = this._copy.color;
  38485. }
  38486. else if (meshCol && meshCol[c] !== undefined) {
  38487. this._color.r = meshCol[c];
  38488. this._color.g = meshCol[c + 1];
  38489. this._color.b = meshCol[c + 2];
  38490. this._color.a = meshCol[c + 3];
  38491. }
  38492. else {
  38493. this._color.r = 1;
  38494. this._color.g = 1;
  38495. this._color.b = 1;
  38496. this._color.a = 1;
  38497. }
  38498. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38499. c += 4;
  38500. if (!this.recomputeNormals && meshNor) {
  38501. this._normal.x = meshNor[n];
  38502. this._normal.y = meshNor[n + 1];
  38503. this._normal.z = meshNor[n + 2];
  38504. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  38505. normals.push(this._normal.x, this._normal.y, this._normal.z);
  38506. n += 3;
  38507. }
  38508. }
  38509. for (i = 0; i < meshInd.length; i++) {
  38510. indices.push(p + meshInd[i]);
  38511. }
  38512. if (this._pickable) {
  38513. var nbfaces = meshInd.length / 3;
  38514. for (i = 0; i < nbfaces; i++) {
  38515. this.pickedParticles.push({ idx: idx, faceId: i });
  38516. }
  38517. }
  38518. return this._copy;
  38519. };
  38520. // returns a shape array from positions array
  38521. SolidParticleSystem.prototype._posToShape = function (positions) {
  38522. var shape = [];
  38523. for (var i = 0; i < positions.length; i += 3) {
  38524. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38525. }
  38526. return shape;
  38527. };
  38528. // returns a shapeUV array from a Vector4 uvs
  38529. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38530. var shapeUV = [];
  38531. if (uvs) {
  38532. for (var i = 0; i < uvs.length; i++)
  38533. shapeUV.push(uvs[i]);
  38534. }
  38535. return shapeUV;
  38536. };
  38537. // adds a new particle object in the particles array
  38538. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  38539. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  38540. this.particles.push(sp);
  38541. return sp;
  38542. };
  38543. /**
  38544. * Adds some particles to the SPS from the model shape. Returns the shape id.
  38545. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  38546. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  38547. * `nb` (positive integer) the number of particles to be created from this model
  38548. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  38549. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  38550. */
  38551. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38552. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38553. var meshInd = mesh.getIndices();
  38554. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38555. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38556. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38557. var bbInfo;
  38558. if (this._particlesIntersect) {
  38559. bbInfo = mesh.getBoundingInfo();
  38560. }
  38561. var shape = this._posToShape(meshPos);
  38562. var shapeUV = this._uvsToShapeUV(meshUV);
  38563. var posfunc = options ? options.positionFunction : null;
  38564. var vtxfunc = options ? options.vertexFunction : null;
  38565. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38566. // particles
  38567. var sp;
  38568. var currentCopy;
  38569. var idx = this.nbParticles;
  38570. for (var i = 0; i < nb; i++) {
  38571. var currentPos = this._positions.length;
  38572. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  38573. if (this._updatable) {
  38574. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  38575. sp.position.copyFrom(currentCopy.position);
  38576. sp.rotation.copyFrom(currentCopy.rotation);
  38577. if (currentCopy.rotationQuaternion) {
  38578. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  38579. }
  38580. if (currentCopy.color) {
  38581. sp.color.copyFrom(currentCopy.color);
  38582. }
  38583. sp.scaling.copyFrom(currentCopy.scaling);
  38584. sp.uvs.copyFrom(currentCopy.uvs);
  38585. }
  38586. this._index += shape.length;
  38587. idx++;
  38588. }
  38589. this.nbParticles += nb;
  38590. this._shapeCounter++;
  38591. return this._shapeCounter - 1;
  38592. };
  38593. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38594. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38595. this._resetCopy();
  38596. if (particle._model._positionFunction) {
  38597. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38598. }
  38599. if (this._copy.rotationQuaternion) {
  38600. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38601. }
  38602. else {
  38603. this._yaw = this._copy.rotation.y;
  38604. this._pitch = this._copy.rotation.x;
  38605. this._roll = this._copy.rotation.z;
  38606. this._quaternionRotationYPR();
  38607. }
  38608. this._quaternionToRotationMatrix();
  38609. this._shape = particle._model._shape;
  38610. for (var pt = 0; pt < this._shape.length; pt++) {
  38611. this._vertex.x = this._shape[pt].x;
  38612. this._vertex.y = this._shape[pt].y;
  38613. this._vertex.z = this._shape[pt].z;
  38614. if (particle._model._vertexFunction) {
  38615. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38616. }
  38617. this._vertex.x *= this._copy.scaling.x;
  38618. this._vertex.y *= this._copy.scaling.y;
  38619. this._vertex.z *= this._copy.scaling.z;
  38620. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38621. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38622. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38623. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38624. }
  38625. particle.position.x = 0.0;
  38626. particle.position.y = 0.0;
  38627. particle.position.z = 0.0;
  38628. particle.rotation.x = 0.0;
  38629. particle.rotation.y = 0.0;
  38630. particle.rotation.z = 0.0;
  38631. particle.rotationQuaternion = null;
  38632. particle.scaling.x = 1.0;
  38633. particle.scaling.y = 1.0;
  38634. particle.scaling.z = 1.0;
  38635. };
  38636. /**
  38637. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38638. * Returns the SPS.
  38639. */
  38640. SolidParticleSystem.prototype.rebuildMesh = function () {
  38641. for (var p = 0; p < this.particles.length; p++) {
  38642. this._rebuildParticle(this.particles[p]);
  38643. }
  38644. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38645. return this;
  38646. };
  38647. /**
  38648. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38649. * This method calls `updateParticle()` for each particle of the SPS.
  38650. * For an animated SPS, it is usually called within the render loop.
  38651. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  38652. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  38653. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  38654. * Returns the SPS.
  38655. */
  38656. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38657. if (start === void 0) { start = 0; }
  38658. if (end === void 0) { end = this.nbParticles - 1; }
  38659. if (update === void 0) { update = true; }
  38660. if (!this._updatable) {
  38661. return;
  38662. }
  38663. // custom beforeUpdate
  38664. this.beforeUpdateParticles(start, end, update);
  38665. this._cam_axisX.x = 1.0;
  38666. this._cam_axisX.y = 0.0;
  38667. this._cam_axisX.z = 0.0;
  38668. this._cam_axisY.x = 0.0;
  38669. this._cam_axisY.y = 1.0;
  38670. this._cam_axisY.z = 0.0;
  38671. this._cam_axisZ.x = 0.0;
  38672. this._cam_axisZ.y = 0.0;
  38673. this._cam_axisZ.z = 1.0;
  38674. // if the particles will always face the camera
  38675. if (this.billboard) {
  38676. this.mesh.computeWorldMatrix(true);
  38677. // compute the camera position and un-rotate it by the current mesh rotation
  38678. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  38679. this._quaternionToRotationMatrix();
  38680. this._rotMatrix.invertToRef(this._invertMatrix);
  38681. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  38682. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  38683. this._cam_axisZ.normalize();
  38684. // same for camera up vector extracted from the cam view matrix
  38685. var view = this._camera.getViewMatrix(true);
  38686. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  38687. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  38688. this._cam_axisY.normalize();
  38689. this._cam_axisX.normalize();
  38690. }
  38691. }
  38692. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38693. var idx = 0; // current position index in the global array positions32
  38694. var index = 0; // position start index in the global array positions32 of the current particle
  38695. var colidx = 0; // current color index in the global array colors32
  38696. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  38697. var uvidx = 0; // current uv index in the global array uvs32
  38698. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  38699. var pt = 0; // current index in the particle model shape
  38700. if (this.mesh.isFacetDataEnabled) {
  38701. this._computeBoundingBox = true;
  38702. }
  38703. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  38704. if (this._computeBoundingBox) {
  38705. if (start == 0 && end == this.nbParticles - 1) {
  38706. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38707. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38708. }
  38709. else {
  38710. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  38711. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  38712. }
  38713. }
  38714. // particle loop
  38715. index = this.particles[start]._pos;
  38716. var vpos = (index / 3) | 0;
  38717. colorIndex = vpos * 4;
  38718. uvIndex = vpos * 2;
  38719. for (var p = start; p <= end; p++) {
  38720. this._particle = this.particles[p];
  38721. this._shape = this._particle._model._shape;
  38722. this._shapeUV = this._particle._model._shapeUV;
  38723. // call to custom user function to update the particle properties
  38724. this.updateParticle(this._particle);
  38725. if (this._particle.isVisible) {
  38726. // particle rotation matrix
  38727. if (this.billboard) {
  38728. this._particle.rotation.x = 0.0;
  38729. this._particle.rotation.y = 0.0;
  38730. }
  38731. if (this._computeParticleRotation || this.billboard) {
  38732. if (this._particle.rotationQuaternion) {
  38733. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38734. }
  38735. else {
  38736. this._yaw = this._particle.rotation.y;
  38737. this._pitch = this._particle.rotation.x;
  38738. this._roll = this._particle.rotation.z;
  38739. this._quaternionRotationYPR();
  38740. }
  38741. this._quaternionToRotationMatrix();
  38742. }
  38743. // particle vertex loop
  38744. for (pt = 0; pt < this._shape.length; pt++) {
  38745. idx = index + pt * 3;
  38746. colidx = colorIndex + pt * 4;
  38747. uvidx = uvIndex + pt * 2;
  38748. this._vertex.x = this._shape[pt].x;
  38749. this._vertex.y = this._shape[pt].y;
  38750. this._vertex.z = this._shape[pt].z;
  38751. if (this._computeParticleVertex) {
  38752. this.updateParticleVertex(this._particle, this._vertex, pt);
  38753. }
  38754. // positions
  38755. this._vertex.x *= this._particle.scaling.x;
  38756. this._vertex.y *= this._particle.scaling.y;
  38757. this._vertex.z *= this._particle.scaling.z;
  38758. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  38759. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  38760. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  38761. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  38762. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38763. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  38764. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  38765. if (this._computeBoundingBox) {
  38766. if (this._positions32[idx] < this._minimum.x) {
  38767. this._minimum.x = this._positions32[idx];
  38768. }
  38769. if (this._positions32[idx] > this._maximum.x) {
  38770. this._maximum.x = this._positions32[idx];
  38771. }
  38772. if (this._positions32[idx + 1] < this._minimum.y) {
  38773. this._minimum.y = this._positions32[idx + 1];
  38774. }
  38775. if (this._positions32[idx + 1] > this._maximum.y) {
  38776. this._maximum.y = this._positions32[idx + 1];
  38777. }
  38778. if (this._positions32[idx + 2] < this._minimum.z) {
  38779. this._minimum.z = this._positions32[idx + 2];
  38780. }
  38781. if (this._positions32[idx + 2] > this._maximum.z) {
  38782. this._maximum.z = this._positions32[idx + 2];
  38783. }
  38784. }
  38785. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  38786. if (!this._computeParticleVertex) {
  38787. this._normal.x = this._fixedNormal32[idx];
  38788. this._normal.y = this._fixedNormal32[idx + 1];
  38789. this._normal.z = this._fixedNormal32[idx + 2];
  38790. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]);
  38791. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]);
  38792. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]);
  38793. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38794. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  38795. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  38796. }
  38797. if (this._computeParticleColor) {
  38798. this._colors32[colidx] = this._particle.color.r;
  38799. this._colors32[colidx + 1] = this._particle.color.g;
  38800. this._colors32[colidx + 2] = this._particle.color.b;
  38801. this._colors32[colidx + 3] = this._particle.color.a;
  38802. }
  38803. if (this._computeParticleTexture) {
  38804. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38805. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38806. }
  38807. }
  38808. }
  38809. else {
  38810. for (pt = 0; pt < this._shape.length; pt++) {
  38811. idx = index + pt * 3;
  38812. colidx = colorIndex + pt * 4;
  38813. uvidx = uvIndex + pt * 2;
  38814. this._positions32[idx] = this._camera.position.x;
  38815. this._positions32[idx + 1] = this._camera.position.y;
  38816. this._positions32[idx + 2] = this._camera.position.z;
  38817. this._normals32[idx] = 0.0;
  38818. this._normals32[idx + 1] = 0.0;
  38819. this._normals32[idx + 2] = 0.0;
  38820. if (this._computeParticleColor) {
  38821. this._colors32[colidx] = this._particle.color.r;
  38822. this._colors32[colidx + 1] = this._particle.color.g;
  38823. this._colors32[colidx + 2] = this._particle.color.b;
  38824. this._colors32[colidx + 3] = this._particle.color.a;
  38825. }
  38826. if (this._computeParticleTexture) {
  38827. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38828. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38829. }
  38830. }
  38831. }
  38832. // if the particle intersections must be computed : update the bbInfo
  38833. if (this._particlesIntersect) {
  38834. var bInfo = this._particle._boundingInfo;
  38835. var bBox = bInfo.boundingBox;
  38836. var bSphere = bInfo.boundingSphere;
  38837. if (!this._bSphereOnly) {
  38838. // place, scale and rotate the particle bbox within the SPS local system, then update it
  38839. for (var b = 0; b < bBox.vectors.length; b++) {
  38840. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  38841. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  38842. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  38843. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  38844. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  38845. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  38846. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  38847. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38848. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  38849. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  38850. }
  38851. bBox._update(this.mesh._worldMatrix);
  38852. }
  38853. // place and scale the particle bouding sphere in the SPS local system, then update it
  38854. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  38855. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  38856. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  38857. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  38858. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  38859. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  38860. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  38861. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  38862. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  38863. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  38864. bSphere._update(this.mesh._worldMatrix);
  38865. }
  38866. // increment indexes for the next particle
  38867. index = idx + 3;
  38868. colorIndex = colidx + 4;
  38869. uvIndex = uvidx + 2;
  38870. }
  38871. // if the VBO must be updated
  38872. if (update) {
  38873. if (this._computeParticleColor) {
  38874. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38875. }
  38876. if (this._computeParticleTexture) {
  38877. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38878. }
  38879. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38880. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  38881. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  38882. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  38883. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  38884. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  38885. for (var i = 0; i < this._normals32.length; i++) {
  38886. this._fixedNormal32[i] = this._normals32[i];
  38887. }
  38888. }
  38889. if (!this.mesh.areNormalsFrozen) {
  38890. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38891. }
  38892. }
  38893. }
  38894. if (this._computeBoundingBox) {
  38895. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38896. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38897. }
  38898. this.afterUpdateParticles(start, end, update);
  38899. return this;
  38900. };
  38901. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38902. this._halfroll = this._roll * 0.5;
  38903. this._halfpitch = this._pitch * 0.5;
  38904. this._halfyaw = this._yaw * 0.5;
  38905. this._sinRoll = Math.sin(this._halfroll);
  38906. this._cosRoll = Math.cos(this._halfroll);
  38907. this._sinPitch = Math.sin(this._halfpitch);
  38908. this._cosPitch = Math.cos(this._halfpitch);
  38909. this._sinYaw = Math.sin(this._halfyaw);
  38910. this._cosYaw = Math.cos(this._halfyaw);
  38911. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38912. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38913. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38914. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38915. };
  38916. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38917. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38918. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38919. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38920. this._rotMatrix.m[3] = 0;
  38921. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38922. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38923. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38924. this._rotMatrix.m[7] = 0;
  38925. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38926. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38927. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38928. this._rotMatrix.m[11] = 0;
  38929. this._rotMatrix.m[12] = 0;
  38930. this._rotMatrix.m[13] = 0;
  38931. this._rotMatrix.m[14] = 0;
  38932. this._rotMatrix.m[15] = 1.0;
  38933. };
  38934. /**
  38935. * Disposes the SPS.
  38936. * Returns nothing.
  38937. */
  38938. SolidParticleSystem.prototype.dispose = function () {
  38939. this.mesh.dispose();
  38940. this.vars = null;
  38941. // drop references to internal big arrays for the GC
  38942. this._positions = null;
  38943. this._indices = null;
  38944. this._normals = null;
  38945. this._uvs = null;
  38946. this._colors = null;
  38947. this._positions32 = null;
  38948. this._normals32 = null;
  38949. this._fixedNormal32 = null;
  38950. this._uvs32 = null;
  38951. this._colors32 = null;
  38952. this.pickedParticles = null;
  38953. };
  38954. /**
  38955. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38956. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38957. * Returns the SPS.
  38958. */
  38959. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38960. if (!this._isVisibilityBoxLocked) {
  38961. this.mesh.refreshBoundingInfo();
  38962. }
  38963. return this;
  38964. };
  38965. /**
  38966. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38967. * @param size the size (float) of the visibility box
  38968. * note : this doesn't lock the SPS mesh bounding box.
  38969. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38970. */
  38971. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38972. var vis = size / 2;
  38973. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38974. };
  38975. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38976. // getter and setter
  38977. get: function () {
  38978. return this._alwaysVisible;
  38979. },
  38980. /**
  38981. * Sets the SPS as always visible or not
  38982. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38983. */
  38984. set: function (val) {
  38985. this._alwaysVisible = val;
  38986. this.mesh.alwaysSelectAsActiveMesh = val;
  38987. },
  38988. enumerable: true,
  38989. configurable: true
  38990. });
  38991. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38992. get: function () {
  38993. return this._isVisibilityBoxLocked;
  38994. },
  38995. /**
  38996. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38997. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38998. */
  38999. set: function (val) {
  39000. this._isVisibilityBoxLocked = val;
  39001. this.mesh.getBoundingInfo().isLocked = val;
  39002. },
  39003. enumerable: true,
  39004. configurable: true
  39005. });
  39006. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  39007. // getters
  39008. get: function () {
  39009. return this._computeParticleRotation;
  39010. },
  39011. // Optimizer setters
  39012. /**
  39013. * Tells to `setParticles()` to compute the particle rotations or not.
  39014. * Default value : true. The SPS is faster when it's set to false.
  39015. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  39016. */
  39017. set: function (val) {
  39018. this._computeParticleRotation = val;
  39019. },
  39020. enumerable: true,
  39021. configurable: true
  39022. });
  39023. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  39024. get: function () {
  39025. return this._computeParticleColor;
  39026. },
  39027. /**
  39028. * Tells to `setParticles()` to compute the particle colors or not.
  39029. * Default value : true. The SPS is faster when it's set to false.
  39030. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  39031. */
  39032. set: function (val) {
  39033. this._computeParticleColor = val;
  39034. },
  39035. enumerable: true,
  39036. configurable: true
  39037. });
  39038. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  39039. get: function () {
  39040. return this._computeParticleTexture;
  39041. },
  39042. /**
  39043. * Tells to `setParticles()` to compute the particle textures or not.
  39044. * Default value : true. The SPS is faster when it's set to false.
  39045. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  39046. */
  39047. set: function (val) {
  39048. this._computeParticleTexture = val;
  39049. },
  39050. enumerable: true,
  39051. configurable: true
  39052. });
  39053. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  39054. get: function () {
  39055. return this._computeParticleVertex;
  39056. },
  39057. /**
  39058. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  39059. * Default value : false. The SPS is faster when it's set to false.
  39060. * Note : the particle custom vertex positions aren't stored values.
  39061. */
  39062. set: function (val) {
  39063. this._computeParticleVertex = val;
  39064. },
  39065. enumerable: true,
  39066. configurable: true
  39067. });
  39068. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  39069. get: function () {
  39070. return this._computeBoundingBox;
  39071. },
  39072. /**
  39073. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  39074. */
  39075. set: function (val) {
  39076. this._computeBoundingBox = val;
  39077. },
  39078. enumerable: true,
  39079. configurable: true
  39080. });
  39081. // =======================================================================
  39082. // Particle behavior logic
  39083. // these following methods may be overwritten by the user to fit his needs
  39084. /**
  39085. * This function does nothing. It may be overwritten to set all the particle first values.
  39086. * The SPS doesn't call this function, you may have to call it by your own.
  39087. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39088. */
  39089. SolidParticleSystem.prototype.initParticles = function () {
  39090. };
  39091. /**
  39092. * This function does nothing. It may be overwritten to recycle a particle.
  39093. * The SPS doesn't call this function, you may have to call it by your own.
  39094. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39095. */
  39096. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  39097. return particle;
  39098. };
  39099. /**
  39100. * Updates a particle : this function should be overwritten by the user.
  39101. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  39102. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39103. * ex : just set a particle position or velocity and recycle conditions
  39104. */
  39105. SolidParticleSystem.prototype.updateParticle = function (particle) {
  39106. return particle;
  39107. };
  39108. /**
  39109. * Updates a vertex of a particle : it can be overwritten by the user.
  39110. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  39111. * @param particle the current particle
  39112. * @param vertex the current index of the current particle
  39113. * @param pt the index of the current vertex in the particle shape
  39114. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  39115. * ex : just set a vertex particle position
  39116. */
  39117. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  39118. return vertex;
  39119. };
  39120. /**
  39121. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  39122. * This does nothing and may be overwritten by the user.
  39123. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39124. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39125. * @param update the boolean update value actually passed to setParticles()
  39126. */
  39127. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  39128. };
  39129. /**
  39130. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  39131. * This will be passed three parameters.
  39132. * This does nothing and may be overwritten by the user.
  39133. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39134. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39135. * @param update the boolean update value actually passed to setParticles()
  39136. */
  39137. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  39138. };
  39139. return SolidParticleSystem;
  39140. }());
  39141. BABYLON.SolidParticleSystem = SolidParticleSystem;
  39142. })(BABYLON || (BABYLON = {}));
  39143. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  39144. /// <reference path="babylon.mesh.ts" />
  39145. var BABYLON;
  39146. (function (BABYLON) {
  39147. var GroundMesh = (function (_super) {
  39148. __extends(GroundMesh, _super);
  39149. function GroundMesh(name, scene) {
  39150. var _this = _super.call(this, name, scene) || this;
  39151. _this.generateOctree = false;
  39152. _this._worldInverse = new BABYLON.Matrix();
  39153. return _this;
  39154. }
  39155. GroundMesh.prototype.getClassName = function () {
  39156. return "GroundMesh";
  39157. };
  39158. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39159. get: function () {
  39160. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39161. },
  39162. enumerable: true,
  39163. configurable: true
  39164. });
  39165. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39166. get: function () {
  39167. return this._subdivisionsX;
  39168. },
  39169. enumerable: true,
  39170. configurable: true
  39171. });
  39172. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39173. get: function () {
  39174. return this._subdivisionsY;
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39180. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39181. this._subdivisionsX = chunksCount;
  39182. this._subdivisionsY = chunksCount;
  39183. this.subdivide(chunksCount);
  39184. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39185. };
  39186. /**
  39187. * Returns a height (y) value in the Worl system :
  39188. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39189. * Returns the ground y position if (x, z) are outside the ground surface.
  39190. */
  39191. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39192. var world = this.getWorldMatrix();
  39193. var invMat = BABYLON.Tmp.Matrix[5];
  39194. world.invertToRef(invMat);
  39195. var tmpVect = BABYLON.Tmp.Vector3[8];
  39196. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39197. x = tmpVect.x;
  39198. z = tmpVect.z;
  39199. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39200. return this.position.y;
  39201. }
  39202. if (!this._heightQuads || this._heightQuads.length == 0) {
  39203. this._initHeightQuads();
  39204. this._computeHeightQuads();
  39205. }
  39206. var facet = this._getFacetAt(x, z);
  39207. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39208. // return y in the World system
  39209. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39210. return tmpVect.y;
  39211. };
  39212. /**
  39213. * Returns a normalized vector (Vector3) orthogonal to the ground
  39214. * at the ground coordinates (x, z) expressed in the World system.
  39215. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39216. */
  39217. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39218. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39219. this.getNormalAtCoordinatesToRef(x, z, normal);
  39220. return normal;
  39221. };
  39222. /**
  39223. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39224. * at the ground coordinates (x, z) expressed in the World system.
  39225. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39226. * Returns the GroundMesh.
  39227. */
  39228. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39229. var world = this.getWorldMatrix();
  39230. var tmpMat = BABYLON.Tmp.Matrix[5];
  39231. world.invertToRef(tmpMat);
  39232. var tmpVect = BABYLON.Tmp.Vector3[8];
  39233. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39234. x = tmpVect.x;
  39235. z = tmpVect.z;
  39236. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39237. return this;
  39238. }
  39239. if (!this._heightQuads || this._heightQuads.length == 0) {
  39240. this._initHeightQuads();
  39241. this._computeHeightQuads();
  39242. }
  39243. var facet = this._getFacetAt(x, z);
  39244. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39245. return this;
  39246. };
  39247. /**
  39248. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39249. * if the ground has been updated.
  39250. * This can be used in the render loop.
  39251. * Returns the GroundMesh.
  39252. */
  39253. GroundMesh.prototype.updateCoordinateHeights = function () {
  39254. if (!this._heightQuads || this._heightQuads.length == 0) {
  39255. this._initHeightQuads();
  39256. }
  39257. this._computeHeightQuads();
  39258. return this;
  39259. };
  39260. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39261. GroundMesh.prototype._getFacetAt = function (x, z) {
  39262. // retrieve col and row from x, z coordinates in the ground local system
  39263. var subdivisionsX = this._subdivisionsX;
  39264. var subdivisionsY = this._subdivisionsY;
  39265. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39266. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39267. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39268. var facet;
  39269. if (z < quad.slope.x * x + quad.slope.y) {
  39270. facet = quad.facet1;
  39271. }
  39272. else {
  39273. facet = quad.facet2;
  39274. }
  39275. return facet;
  39276. };
  39277. // Creates and populates the heightMap array with "facet" elements :
  39278. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39279. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39280. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39281. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39282. // Returns the GroundMesh.
  39283. GroundMesh.prototype._initHeightQuads = function () {
  39284. var subdivisionsX = this._subdivisionsX;
  39285. var subdivisionsY = this._subdivisionsY;
  39286. this._heightQuads = new Array();
  39287. for (var row = 0; row < subdivisionsY; row++) {
  39288. for (var col = 0; col < subdivisionsX; col++) {
  39289. 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) };
  39290. this._heightQuads[row * subdivisionsX + col] = quad;
  39291. }
  39292. }
  39293. return this;
  39294. };
  39295. // Compute each quad element values and update the the heightMap array :
  39296. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39297. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39298. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39299. // Returns the GroundMesh.
  39300. GroundMesh.prototype._computeHeightQuads = function () {
  39301. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39302. var v1 = BABYLON.Tmp.Vector3[3];
  39303. var v2 = BABYLON.Tmp.Vector3[2];
  39304. var v3 = BABYLON.Tmp.Vector3[1];
  39305. var v4 = BABYLON.Tmp.Vector3[0];
  39306. var v1v2 = BABYLON.Tmp.Vector3[4];
  39307. var v1v3 = BABYLON.Tmp.Vector3[5];
  39308. var v1v4 = BABYLON.Tmp.Vector3[6];
  39309. var norm1 = BABYLON.Tmp.Vector3[7];
  39310. var norm2 = BABYLON.Tmp.Vector3[8];
  39311. var i = 0;
  39312. var j = 0;
  39313. var k = 0;
  39314. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39315. var h = 0;
  39316. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39317. var d2 = 0;
  39318. var subdivisionsX = this._subdivisionsX;
  39319. var subdivisionsY = this._subdivisionsY;
  39320. for (var row = 0; row < subdivisionsY; row++) {
  39321. for (var col = 0; col < subdivisionsX; col++) {
  39322. i = col * 3;
  39323. j = row * (subdivisionsX + 1) * 3;
  39324. k = (row + 1) * (subdivisionsX + 1) * 3;
  39325. v1.x = positions[j + i];
  39326. v1.y = positions[j + i + 1];
  39327. v1.z = positions[j + i + 2];
  39328. v2.x = positions[j + i + 3];
  39329. v2.y = positions[j + i + 4];
  39330. v2.z = positions[j + i + 5];
  39331. v3.x = positions[k + i];
  39332. v3.y = positions[k + i + 1];
  39333. v3.z = positions[k + i + 2];
  39334. v4.x = positions[k + i + 3];
  39335. v4.y = positions[k + i + 4];
  39336. v4.z = positions[k + i + 5];
  39337. // 2D slope V1V4
  39338. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39339. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39340. // facet equations :
  39341. // we compute each facet normal vector
  39342. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39343. // we compute the value d by applying the equation to v1 which belongs to the plane
  39344. // then we store the facet equation in a Vector4
  39345. v2.subtractToRef(v1, v1v2);
  39346. v3.subtractToRef(v1, v1v3);
  39347. v4.subtractToRef(v1, v1v4);
  39348. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39349. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39350. norm1.normalize();
  39351. norm2.normalize();
  39352. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39353. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39354. var quad = this._heightQuads[row * subdivisionsX + col];
  39355. quad.slope.copyFromFloats(cd, h);
  39356. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39357. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39358. }
  39359. }
  39360. return this;
  39361. };
  39362. GroundMesh.prototype.serialize = function (serializationObject) {
  39363. _super.prototype.serialize.call(this, serializationObject);
  39364. serializationObject.subdivisionsX = this._subdivisionsX;
  39365. serializationObject.subdivisionsY = this._subdivisionsY;
  39366. serializationObject.minX = this._minX;
  39367. serializationObject.maxX = this._maxX;
  39368. serializationObject.minZ = this._minZ;
  39369. serializationObject.maxZ = this._maxZ;
  39370. serializationObject.width = this._width;
  39371. serializationObject.height = this._height;
  39372. };
  39373. GroundMesh.Parse = function (parsedMesh, scene) {
  39374. var result = new GroundMesh(parsedMesh.name, scene);
  39375. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39376. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39377. result._minX = parsedMesh.minX;
  39378. result._maxX = parsedMesh.maxX;
  39379. result._minZ = parsedMesh.minZ;
  39380. result._maxZ = parsedMesh.maxZ;
  39381. result._width = parsedMesh.width;
  39382. result._height = parsedMesh.height;
  39383. return result;
  39384. };
  39385. return GroundMesh;
  39386. }(BABYLON.Mesh));
  39387. BABYLON.GroundMesh = GroundMesh;
  39388. })(BABYLON || (BABYLON = {}));
  39389. //# sourceMappingURL=babylon.groundMesh.js.map
  39390. var BABYLON;
  39391. (function (BABYLON) {
  39392. /**
  39393. * Creates an instance based on a source mesh.
  39394. */
  39395. var InstancedMesh = (function (_super) {
  39396. __extends(InstancedMesh, _super);
  39397. function InstancedMesh(name, source) {
  39398. var _this = _super.call(this, name, source.getScene()) || this;
  39399. source.instances.push(_this);
  39400. _this._sourceMesh = source;
  39401. _this.position.copyFrom(source.position);
  39402. _this.rotation.copyFrom(source.rotation);
  39403. _this.scaling.copyFrom(source.scaling);
  39404. if (source.rotationQuaternion) {
  39405. _this.rotationQuaternion = source.rotationQuaternion.clone();
  39406. }
  39407. _this.infiniteDistance = source.infiniteDistance;
  39408. _this.setPivotMatrix(source.getPivotMatrix());
  39409. _this.refreshBoundingInfo();
  39410. _this._syncSubMeshes();
  39411. return _this;
  39412. }
  39413. /**
  39414. * Returns the string "InstancedMesh".
  39415. */
  39416. InstancedMesh.prototype.getClassName = function () {
  39417. return "InstancedMesh";
  39418. };
  39419. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  39420. // Methods
  39421. get: function () {
  39422. return this._sourceMesh.receiveShadows;
  39423. },
  39424. enumerable: true,
  39425. configurable: true
  39426. });
  39427. Object.defineProperty(InstancedMesh.prototype, "material", {
  39428. get: function () {
  39429. return this._sourceMesh.material;
  39430. },
  39431. enumerable: true,
  39432. configurable: true
  39433. });
  39434. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  39435. get: function () {
  39436. return this._sourceMesh.visibility;
  39437. },
  39438. enumerable: true,
  39439. configurable: true
  39440. });
  39441. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  39442. get: function () {
  39443. return this._sourceMesh.skeleton;
  39444. },
  39445. enumerable: true,
  39446. configurable: true
  39447. });
  39448. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  39449. get: function () {
  39450. return this._sourceMesh.renderingGroupId;
  39451. },
  39452. enumerable: true,
  39453. configurable: true
  39454. });
  39455. /**
  39456. * Returns the total number of vertices (integer).
  39457. */
  39458. InstancedMesh.prototype.getTotalVertices = function () {
  39459. return this._sourceMesh.getTotalVertices();
  39460. };
  39461. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  39462. get: function () {
  39463. return this._sourceMesh;
  39464. },
  39465. enumerable: true,
  39466. configurable: true
  39467. });
  39468. /**
  39469. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  39470. */
  39471. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  39472. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  39473. };
  39474. /**
  39475. * Sets the vertex data of the mesh geometry for the requested `kind`.
  39476. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  39477. * The `data` are either a numeric array either a Float32Array.
  39478. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  39479. * 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).
  39480. * Note that a new underlying VertexBuffer object is created each call.
  39481. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  39482. *
  39483. * Possible `kind` values :
  39484. * - BABYLON.VertexBuffer.PositionKind
  39485. * - BABYLON.VertexBuffer.UVKind
  39486. * - BABYLON.VertexBuffer.UV2Kind
  39487. * - BABYLON.VertexBuffer.UV3Kind
  39488. * - BABYLON.VertexBuffer.UV4Kind
  39489. * - BABYLON.VertexBuffer.UV5Kind
  39490. * - BABYLON.VertexBuffer.UV6Kind
  39491. * - BABYLON.VertexBuffer.ColorKind
  39492. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39493. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39494. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39495. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39496. *
  39497. * Returns the Mesh.
  39498. */
  39499. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39500. if (this.sourceMesh) {
  39501. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  39502. }
  39503. return this.sourceMesh;
  39504. };
  39505. /**
  39506. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  39507. * If the mesh has no geometry, it is simply returned as it is.
  39508. * The `data` are either a numeric array either a Float32Array.
  39509. * No new underlying VertexBuffer object is created.
  39510. * 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.
  39511. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  39512. *
  39513. * Possible `kind` values :
  39514. * - BABYLON.VertexBuffer.PositionKind
  39515. * - BABYLON.VertexBuffer.UVKind
  39516. * - BABYLON.VertexBuffer.UV2Kind
  39517. * - BABYLON.VertexBuffer.UV3Kind
  39518. * - BABYLON.VertexBuffer.UV4Kind
  39519. * - BABYLON.VertexBuffer.UV5Kind
  39520. * - BABYLON.VertexBuffer.UV6Kind
  39521. * - BABYLON.VertexBuffer.ColorKind
  39522. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39523. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39524. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39525. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39526. *
  39527. * Returns the Mesh.
  39528. */
  39529. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  39530. if (this.sourceMesh) {
  39531. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  39532. }
  39533. return this.sourceMesh;
  39534. };
  39535. /**
  39536. * Sets the mesh indices.
  39537. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  39538. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  39539. * This method creates a new index buffer each call.
  39540. * Returns the Mesh.
  39541. */
  39542. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  39543. if (this.sourceMesh) {
  39544. this.sourceMesh.setIndices(indices, totalVertices);
  39545. }
  39546. return this.sourceMesh;
  39547. };
  39548. /**
  39549. * Boolean : True if the mesh owns the requested kind of data.
  39550. */
  39551. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  39552. return this._sourceMesh.isVerticesDataPresent(kind);
  39553. };
  39554. /**
  39555. * Returns an array of indices (IndicesArray).
  39556. */
  39557. InstancedMesh.prototype.getIndices = function () {
  39558. return this._sourceMesh.getIndices();
  39559. };
  39560. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  39561. get: function () {
  39562. return this._sourceMesh._positions;
  39563. },
  39564. enumerable: true,
  39565. configurable: true
  39566. });
  39567. /**
  39568. * Sets a new updated BoundingInfo to the mesh.
  39569. * Returns the mesh.
  39570. */
  39571. InstancedMesh.prototype.refreshBoundingInfo = function () {
  39572. var meshBB = this._sourceMesh.getBoundingInfo();
  39573. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  39574. this._updateBoundingInfo();
  39575. return this;
  39576. };
  39577. InstancedMesh.prototype._preActivate = function () {
  39578. if (this._currentLOD) {
  39579. this._currentLOD._preActivate();
  39580. }
  39581. return this;
  39582. };
  39583. InstancedMesh.prototype._activate = function (renderId) {
  39584. if (this._currentLOD) {
  39585. this._currentLOD._registerInstanceForRenderId(this, renderId);
  39586. }
  39587. return this;
  39588. };
  39589. /**
  39590. * Returns the current associated LOD AbstractMesh.
  39591. */
  39592. InstancedMesh.prototype.getLOD = function (camera) {
  39593. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  39594. if (this._currentLOD === this.sourceMesh) {
  39595. return this;
  39596. }
  39597. return this._currentLOD;
  39598. };
  39599. InstancedMesh.prototype._syncSubMeshes = function () {
  39600. this.releaseSubMeshes();
  39601. if (this._sourceMesh.subMeshes) {
  39602. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  39603. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  39604. }
  39605. }
  39606. return this;
  39607. };
  39608. InstancedMesh.prototype._generatePointsArray = function () {
  39609. return this._sourceMesh._generatePointsArray();
  39610. };
  39611. /**
  39612. * Creates a new InstancedMesh from the current mesh.
  39613. * - name (string) : the cloned mesh name
  39614. * - newParent (optional Node) : the optional Node to parent the clone to.
  39615. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  39616. *
  39617. * Returns the clone.
  39618. */
  39619. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39620. var result = this._sourceMesh.createInstance(name);
  39621. // Deep copy
  39622. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  39623. // Bounding info
  39624. this.refreshBoundingInfo();
  39625. // Parent
  39626. if (newParent) {
  39627. result.parent = newParent;
  39628. }
  39629. if (!doNotCloneChildren) {
  39630. // Children
  39631. for (var index = 0; index < this.getScene().meshes.length; index++) {
  39632. var mesh = this.getScene().meshes[index];
  39633. if (mesh.parent === this) {
  39634. mesh.clone(mesh.name, result);
  39635. }
  39636. }
  39637. }
  39638. result.computeWorldMatrix(true);
  39639. return result;
  39640. };
  39641. /**
  39642. * Disposes the InstancedMesh.
  39643. * Returns nothing.
  39644. */
  39645. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  39646. // Remove from mesh
  39647. var index = this._sourceMesh.instances.indexOf(this);
  39648. this._sourceMesh.instances.splice(index, 1);
  39649. _super.prototype.dispose.call(this, doNotRecurse);
  39650. };
  39651. return InstancedMesh;
  39652. }(BABYLON.AbstractMesh));
  39653. BABYLON.InstancedMesh = InstancedMesh;
  39654. })(BABYLON || (BABYLON = {}));
  39655. //# sourceMappingURL=babylon.instancedMesh.js.map
  39656. /// <reference path="babylon.mesh.ts" />
  39657. var BABYLON;
  39658. (function (BABYLON) {
  39659. var LinesMesh = (function (_super) {
  39660. __extends(LinesMesh, _super);
  39661. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  39662. if (parent === void 0) { parent = null; }
  39663. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  39664. _this.useVertexColor = useVertexColor;
  39665. _this.color = new BABYLON.Color3(1, 1, 1);
  39666. _this.alpha = 1;
  39667. if (source) {
  39668. _this.color = source.color.clone();
  39669. _this.alpha = source.alpha;
  39670. _this.useVertexColor = source.useVertexColor;
  39671. }
  39672. _this._intersectionThreshold = 0.1;
  39673. var options = {
  39674. attributes: [BABYLON.VertexBuffer.PositionKind],
  39675. uniforms: ["world", "viewProjection"],
  39676. needAlphaBlending: false,
  39677. };
  39678. if (!useVertexColor) {
  39679. options.uniforms.push("color");
  39680. options.needAlphaBlending = true;
  39681. }
  39682. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  39683. return _this;
  39684. }
  39685. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  39686. /**
  39687. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39688. * This margin is expressed in world space coordinates, so its value may vary.
  39689. * Default value is 0.1
  39690. * @returns the intersection Threshold value.
  39691. */
  39692. get: function () {
  39693. return this._intersectionThreshold;
  39694. },
  39695. /**
  39696. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39697. * This margin is expressed in world space coordinates, so its value may vary.
  39698. * @param value the new threshold to apply
  39699. */
  39700. set: function (value) {
  39701. if (this._intersectionThreshold === value) {
  39702. return;
  39703. }
  39704. this._intersectionThreshold = value;
  39705. if (this.geometry) {
  39706. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  39707. }
  39708. },
  39709. enumerable: true,
  39710. configurable: true
  39711. });
  39712. /**
  39713. * Returns the string "LineMesh"
  39714. */
  39715. LinesMesh.prototype.getClassName = function () {
  39716. return "LinesMesh";
  39717. };
  39718. Object.defineProperty(LinesMesh.prototype, "material", {
  39719. get: function () {
  39720. return this._colorShader;
  39721. },
  39722. enumerable: true,
  39723. configurable: true
  39724. });
  39725. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  39726. get: function () {
  39727. return false;
  39728. },
  39729. enumerable: true,
  39730. configurable: true
  39731. });
  39732. LinesMesh.prototype.createInstance = function (name) {
  39733. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  39734. return null;
  39735. };
  39736. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  39737. // VBOs
  39738. this._geometry._bind(this._colorShader.getEffect());
  39739. // Color
  39740. if (!this.useVertexColor) {
  39741. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  39742. }
  39743. return this;
  39744. };
  39745. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  39746. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  39747. return this;
  39748. }
  39749. var engine = this.getScene().getEngine();
  39750. // Draw order
  39751. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  39752. return this;
  39753. };
  39754. LinesMesh.prototype.dispose = function (doNotRecurse) {
  39755. this._colorShader.dispose();
  39756. _super.prototype.dispose.call(this, doNotRecurse);
  39757. };
  39758. /**
  39759. * Returns a new LineMesh object cloned from the current one.
  39760. */
  39761. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39762. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  39763. };
  39764. return LinesMesh;
  39765. }(BABYLON.Mesh));
  39766. BABYLON.LinesMesh = LinesMesh;
  39767. })(BABYLON || (BABYLON = {}));
  39768. //# sourceMappingURL=babylon.linesMesh.js.map
  39769. var BABYLON;
  39770. (function (BABYLON) {
  39771. var ShaderMaterial = (function (_super) {
  39772. __extends(ShaderMaterial, _super);
  39773. function ShaderMaterial(name, scene, shaderPath, options) {
  39774. var _this = _super.call(this, name, scene) || this;
  39775. _this._textures = {};
  39776. _this._textureArrays = {};
  39777. _this._floats = {};
  39778. _this._floatsArrays = {};
  39779. _this._colors3 = {};
  39780. _this._colors4 = {};
  39781. _this._vectors2 = {};
  39782. _this._vectors3 = {};
  39783. _this._vectors4 = {};
  39784. _this._matrices = {};
  39785. _this._matrices3x3 = {};
  39786. _this._matrices2x2 = {};
  39787. _this._vectors3Arrays = {};
  39788. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39789. _this._shaderPath = shaderPath;
  39790. options.needAlphaBlending = options.needAlphaBlending || false;
  39791. options.needAlphaTesting = options.needAlphaTesting || false;
  39792. options.attributes = options.attributes || ["position", "normal", "uv"];
  39793. options.uniforms = options.uniforms || ["worldViewProjection"];
  39794. options.uniformBuffers = options.uniformBuffers || [];
  39795. options.samplers = options.samplers || [];
  39796. options.defines = options.defines || [];
  39797. _this._options = options;
  39798. return _this;
  39799. }
  39800. ShaderMaterial.prototype.getClassName = function () {
  39801. return "ShaderMaterial";
  39802. };
  39803. ShaderMaterial.prototype.needAlphaBlending = function () {
  39804. return this._options.needAlphaBlending;
  39805. };
  39806. ShaderMaterial.prototype.needAlphaTesting = function () {
  39807. return this._options.needAlphaTesting;
  39808. };
  39809. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39810. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39811. this._options.uniforms.push(uniformName);
  39812. }
  39813. };
  39814. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39815. if (this._options.samplers.indexOf(name) === -1) {
  39816. this._options.samplers.push(name);
  39817. }
  39818. this._textures[name] = texture;
  39819. return this;
  39820. };
  39821. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39822. if (this._options.samplers.indexOf(name) === -1) {
  39823. this._options.samplers.push(name);
  39824. }
  39825. this._checkUniform(name);
  39826. this._textureArrays[name] = textures;
  39827. return this;
  39828. };
  39829. ShaderMaterial.prototype.setFloat = function (name, value) {
  39830. this._checkUniform(name);
  39831. this._floats[name] = value;
  39832. return this;
  39833. };
  39834. ShaderMaterial.prototype.setFloats = function (name, value) {
  39835. this._checkUniform(name);
  39836. this._floatsArrays[name] = value;
  39837. return this;
  39838. };
  39839. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39840. this._checkUniform(name);
  39841. this._colors3[name] = value;
  39842. return this;
  39843. };
  39844. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39845. this._checkUniform(name);
  39846. this._colors4[name] = value;
  39847. return this;
  39848. };
  39849. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39850. this._checkUniform(name);
  39851. this._vectors2[name] = value;
  39852. return this;
  39853. };
  39854. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39855. this._checkUniform(name);
  39856. this._vectors3[name] = value;
  39857. return this;
  39858. };
  39859. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39860. this._checkUniform(name);
  39861. this._vectors4[name] = value;
  39862. return this;
  39863. };
  39864. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39865. this._checkUniform(name);
  39866. this._matrices[name] = value;
  39867. return this;
  39868. };
  39869. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39870. this._checkUniform(name);
  39871. this._matrices3x3[name] = value;
  39872. return this;
  39873. };
  39874. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39875. this._checkUniform(name);
  39876. this._matrices2x2[name] = value;
  39877. return this;
  39878. };
  39879. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39880. this._checkUniform(name);
  39881. this._vectors3Arrays[name] = value;
  39882. return this;
  39883. };
  39884. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39885. if (!mesh) {
  39886. return true;
  39887. }
  39888. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39889. return false;
  39890. }
  39891. return false;
  39892. };
  39893. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39894. var scene = this.getScene();
  39895. var engine = scene.getEngine();
  39896. if (!this.checkReadyOnEveryCall) {
  39897. if (this._renderId === scene.getRenderId()) {
  39898. if (this._checkCache(scene, mesh, useInstances)) {
  39899. return true;
  39900. }
  39901. }
  39902. }
  39903. // Instances
  39904. var defines = [];
  39905. var attribs = [];
  39906. var fallbacks = new BABYLON.EffectFallbacks();
  39907. if (useInstances) {
  39908. defines.push("#define INSTANCES");
  39909. }
  39910. for (var index = 0; index < this._options.defines.length; index++) {
  39911. defines.push(this._options.defines[index]);
  39912. }
  39913. for (var index = 0; index < this._options.attributes.length; index++) {
  39914. attribs.push(this._options.attributes[index]);
  39915. }
  39916. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39917. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39918. defines.push("#define VERTEXCOLOR");
  39919. }
  39920. // Bones
  39921. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39922. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39923. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39924. if (mesh.numBoneInfluencers > 4) {
  39925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39927. }
  39928. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39929. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39930. fallbacks.addCPUSkinningFallback(0, mesh);
  39931. }
  39932. else {
  39933. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39934. }
  39935. // Textures
  39936. for (var name in this._textures) {
  39937. if (!this._textures[name].isReady()) {
  39938. return false;
  39939. }
  39940. }
  39941. // Alpha test
  39942. if (engine.getAlphaTesting()) {
  39943. defines.push("#define ALPHATEST");
  39944. }
  39945. var previousEffect = this._effect;
  39946. var join = defines.join("\n");
  39947. this._effect = engine.createEffect(this._shaderPath, {
  39948. attributes: attribs,
  39949. uniformsNames: this._options.uniforms,
  39950. uniformBuffersNames: this._options.uniformBuffers,
  39951. samplers: this._options.samplers,
  39952. defines: join,
  39953. fallbacks: fallbacks,
  39954. onCompiled: this.onCompiled,
  39955. onError: this.onError
  39956. }, engine);
  39957. if (!this._effect.isReady()) {
  39958. return false;
  39959. }
  39960. if (previousEffect !== this._effect) {
  39961. scene.resetCachedMaterial();
  39962. }
  39963. this._renderId = scene.getRenderId();
  39964. return true;
  39965. };
  39966. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39967. var scene = this.getScene();
  39968. if (this._options.uniforms.indexOf("world") !== -1) {
  39969. this._effect.setMatrix("world", world);
  39970. }
  39971. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39972. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39973. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39974. }
  39975. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39976. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39977. }
  39978. };
  39979. ShaderMaterial.prototype.bind = function (world, mesh) {
  39980. // Std values
  39981. this.bindOnlyWorldMatrix(world);
  39982. if (this.getScene().getCachedMaterial() !== this) {
  39983. if (this._options.uniforms.indexOf("view") !== -1) {
  39984. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39985. }
  39986. if (this._options.uniforms.indexOf("projection") !== -1) {
  39987. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39988. }
  39989. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39990. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39991. }
  39992. // Bones
  39993. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39994. var name;
  39995. // Texture
  39996. for (name in this._textures) {
  39997. this._effect.setTexture(name, this._textures[name]);
  39998. }
  39999. // Texture arrays
  40000. for (name in this._textureArrays) {
  40001. this._effect.setTextureArray(name, this._textureArrays[name]);
  40002. }
  40003. // Float
  40004. for (name in this._floats) {
  40005. this._effect.setFloat(name, this._floats[name]);
  40006. }
  40007. // Float s
  40008. for (name in this._floatsArrays) {
  40009. this._effect.setArray(name, this._floatsArrays[name]);
  40010. }
  40011. // Color3
  40012. for (name in this._colors3) {
  40013. this._effect.setColor3(name, this._colors3[name]);
  40014. }
  40015. // Color4
  40016. for (name in this._colors4) {
  40017. var color = this._colors4[name];
  40018. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40019. }
  40020. // Vector2
  40021. for (name in this._vectors2) {
  40022. this._effect.setVector2(name, this._vectors2[name]);
  40023. }
  40024. // Vector3
  40025. for (name in this._vectors3) {
  40026. this._effect.setVector3(name, this._vectors3[name]);
  40027. }
  40028. // Vector4
  40029. for (name in this._vectors4) {
  40030. this._effect.setVector4(name, this._vectors4[name]);
  40031. }
  40032. // Matrix
  40033. for (name in this._matrices) {
  40034. this._effect.setMatrix(name, this._matrices[name]);
  40035. }
  40036. // Matrix 3x3
  40037. for (name in this._matrices3x3) {
  40038. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40039. }
  40040. // Matrix 2x2
  40041. for (name in this._matrices2x2) {
  40042. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40043. }
  40044. // Vector3Array
  40045. for (name in this._vectors3Arrays) {
  40046. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40047. }
  40048. }
  40049. this._afterBind(mesh);
  40050. };
  40051. ShaderMaterial.prototype.clone = function (name) {
  40052. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40053. return newShaderMaterial;
  40054. };
  40055. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40056. if (forceDisposeTextures) {
  40057. var name;
  40058. for (name in this._textures) {
  40059. this._textures[name].dispose();
  40060. }
  40061. for (name in this._textureArrays) {
  40062. var array = this._textureArrays[name];
  40063. for (var index = 0; index < array.length; index++) {
  40064. array[index].dispose();
  40065. }
  40066. }
  40067. }
  40068. this._textures = {};
  40069. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40070. };
  40071. ShaderMaterial.prototype.serialize = function () {
  40072. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40073. serializationObject.customType = "BABYLON.ShaderMaterial";
  40074. serializationObject.options = this._options;
  40075. serializationObject.shaderPath = this._shaderPath;
  40076. var name;
  40077. // Texture
  40078. serializationObject.textures = {};
  40079. for (name in this._textures) {
  40080. serializationObject.textures[name] = this._textures[name].serialize();
  40081. }
  40082. // Texture arrays
  40083. serializationObject.textureArrays = {};
  40084. for (name in this._textureArrays) {
  40085. serializationObject.textureArrays[name] = [];
  40086. var array = this._textureArrays[name];
  40087. for (var index = 0; index < array.length; index++) {
  40088. serializationObject.textureArrays[name].push(array[index].serialize());
  40089. }
  40090. }
  40091. // Float
  40092. serializationObject.floats = {};
  40093. for (name in this._floats) {
  40094. serializationObject.floats[name] = this._floats[name];
  40095. }
  40096. // Float s
  40097. serializationObject.floatArrays = {};
  40098. for (name in this._floatsArrays) {
  40099. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40100. }
  40101. // Color3
  40102. serializationObject.colors3 = {};
  40103. for (name in this._colors3) {
  40104. serializationObject.colors3[name] = this._colors3[name].asArray();
  40105. }
  40106. // Color4
  40107. serializationObject.colors4 = {};
  40108. for (name in this._colors4) {
  40109. serializationObject.colors4[name] = this._colors4[name].asArray();
  40110. }
  40111. // Vector2
  40112. serializationObject.vectors2 = {};
  40113. for (name in this._vectors2) {
  40114. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40115. }
  40116. // Vector3
  40117. serializationObject.vectors3 = {};
  40118. for (name in this._vectors3) {
  40119. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40120. }
  40121. // Vector4
  40122. serializationObject.vectors4 = {};
  40123. for (name in this._vectors4) {
  40124. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40125. }
  40126. // Matrix
  40127. serializationObject.matrices = {};
  40128. for (name in this._matrices) {
  40129. serializationObject.matrices[name] = this._matrices[name].asArray();
  40130. }
  40131. // Matrix 3x3
  40132. serializationObject.matrices3x3 = {};
  40133. for (name in this._matrices3x3) {
  40134. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40135. }
  40136. // Matrix 2x2
  40137. serializationObject.matrices2x2 = {};
  40138. for (name in this._matrices2x2) {
  40139. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40140. }
  40141. // Vector3Array
  40142. serializationObject.vectors3Arrays = {};
  40143. for (name in this._vectors3Arrays) {
  40144. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40145. }
  40146. return serializationObject;
  40147. };
  40148. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40149. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40150. var name;
  40151. // Texture
  40152. for (name in source.textures) {
  40153. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40154. }
  40155. // Texture arrays
  40156. for (name in source.textureArrays) {
  40157. var array = source.textureArrays[name];
  40158. var textureArray = new Array();
  40159. for (var index = 0; index < array.length; index++) {
  40160. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40161. }
  40162. material.setTextureArray(name, textureArray);
  40163. }
  40164. // Float
  40165. for (name in source.floats) {
  40166. material.setFloat(name, source.floats[name]);
  40167. }
  40168. // Float s
  40169. for (name in source.floatsArrays) {
  40170. material.setFloats(name, source.floatsArrays[name]);
  40171. }
  40172. // Color3
  40173. for (name in source.colors3) {
  40174. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40175. }
  40176. // Color4
  40177. for (name in source.colors4) {
  40178. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40179. }
  40180. // Vector2
  40181. for (name in source.vectors2) {
  40182. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40183. }
  40184. // Vector3
  40185. for (name in source.vectors3) {
  40186. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40187. }
  40188. // Vector4
  40189. for (name in source.vectors4) {
  40190. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40191. }
  40192. // Matrix
  40193. for (name in source.matrices) {
  40194. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40195. }
  40196. // Matrix 3x3
  40197. for (name in source.matrices3x3) {
  40198. material.setMatrix3x3(name, source.matrices3x3[name]);
  40199. }
  40200. // Matrix 2x2
  40201. for (name in source.matrices2x2) {
  40202. material.setMatrix2x2(name, source.matrices2x2[name]);
  40203. }
  40204. // Vector3Array
  40205. for (name in source.vectors3Arrays) {
  40206. material.setArray3(name, source.vectors3Arrays[name]);
  40207. }
  40208. return material;
  40209. };
  40210. return ShaderMaterial;
  40211. }(BABYLON.Material));
  40212. BABYLON.ShaderMaterial = ShaderMaterial;
  40213. })(BABYLON || (BABYLON = {}));
  40214. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40215. var BABYLON;
  40216. (function (BABYLON) {
  40217. var MeshBuilder = (function () {
  40218. function MeshBuilder() {
  40219. }
  40220. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  40221. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  40222. return BABYLON.Mesh.DOUBLESIDE;
  40223. }
  40224. if (orientation === undefined || orientation === null) {
  40225. return BABYLON.Mesh.FRONTSIDE;
  40226. }
  40227. return orientation;
  40228. };
  40229. /**
  40230. * Creates a box mesh.
  40231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  40232. * The parameter `size` sets the size (float) of each box side (default 1).
  40233. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  40234. * 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).
  40235. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40236. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40237. * 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).
  40238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40240. */
  40241. MeshBuilder.CreateBox = function (name, options, scene) {
  40242. var box = new BABYLON.Mesh(name, scene);
  40243. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40244. box.sideOrientation = options.sideOrientation;
  40245. var vertexData = BABYLON.VertexData.CreateBox(options);
  40246. vertexData.applyToMesh(box, options.updatable);
  40247. return box;
  40248. };
  40249. /**
  40250. * Creates a sphere mesh.
  40251. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  40252. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  40253. * 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`).
  40254. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  40255. * 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
  40256. * 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).
  40257. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40258. * 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).
  40259. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40260. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40261. */
  40262. MeshBuilder.CreateSphere = function (name, options, scene) {
  40263. var sphere = new BABYLON.Mesh(name, scene);
  40264. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40265. sphere.sideOrientation = options.sideOrientation;
  40266. var vertexData = BABYLON.VertexData.CreateSphere(options);
  40267. vertexData.applyToMesh(sphere, options.updatable);
  40268. return sphere;
  40269. };
  40270. /**
  40271. * Creates a plane polygonal mesh. By default, this is a disc.
  40272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  40273. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  40274. * 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.
  40275. * 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
  40276. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40277. * 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).
  40278. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40280. */
  40281. MeshBuilder.CreateDisc = function (name, options, scene) {
  40282. var disc = new BABYLON.Mesh(name, scene);
  40283. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40284. disc.sideOrientation = options.sideOrientation;
  40285. var vertexData = BABYLON.VertexData.CreateDisc(options);
  40286. vertexData.applyToMesh(disc, options.updatable);
  40287. return disc;
  40288. };
  40289. /**
  40290. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  40291. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  40292. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  40293. * 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`).
  40294. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  40295. * 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.
  40296. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40297. * 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).
  40298. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40300. */
  40301. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  40302. var sphere = new BABYLON.Mesh(name, scene);
  40303. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40304. sphere.sideOrientation = options.sideOrientation;
  40305. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  40306. vertexData.applyToMesh(sphere, options.updatable);
  40307. return sphere;
  40308. };
  40309. ;
  40310. /**
  40311. * Creates a ribbon mesh.
  40312. * 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.
  40313. *
  40314. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  40315. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  40316. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  40317. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  40318. * 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.
  40319. * 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.
  40320. * 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
  40321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40322. * 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).
  40323. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40324. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40325. * 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.
  40326. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  40327. * 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
  40328. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  40329. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  40330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40331. */
  40332. MeshBuilder.CreateRibbon = function (name, options, scene) {
  40333. var pathArray = options.pathArray;
  40334. var closeArray = options.closeArray;
  40335. var closePath = options.closePath;
  40336. var offset = options.offset;
  40337. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40338. var instance = options.instance;
  40339. var updatable = options.updatable;
  40340. if (instance) {
  40341. // positionFunction : ribbon case
  40342. // only pathArray and sideOrientation parameters are taken into account for positions update
  40343. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  40344. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  40345. var positionFunction = function (positions) {
  40346. var minlg = pathArray[0].length;
  40347. var i = 0;
  40348. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  40349. for (var si = 1; si <= ns; si++) {
  40350. for (var p = 0; p < pathArray.length; p++) {
  40351. var path = pathArray[p];
  40352. var l = path.length;
  40353. minlg = (minlg < l) ? minlg : l;
  40354. var j = 0;
  40355. while (j < minlg) {
  40356. positions[i] = path[j].x;
  40357. positions[i + 1] = path[j].y;
  40358. positions[i + 2] = path[j].z;
  40359. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  40360. BABYLON.Tmp.Vector3[0].x = path[j].x;
  40361. }
  40362. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  40363. BABYLON.Tmp.Vector3[1].x = path[j].x;
  40364. }
  40365. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  40366. BABYLON.Tmp.Vector3[0].y = path[j].y;
  40367. }
  40368. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  40369. BABYLON.Tmp.Vector3[1].y = path[j].y;
  40370. }
  40371. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  40372. BABYLON.Tmp.Vector3[0].z = path[j].z;
  40373. }
  40374. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  40375. BABYLON.Tmp.Vector3[1].z = path[j].z;
  40376. }
  40377. j++;
  40378. i += 3;
  40379. }
  40380. if (instance._closePath) {
  40381. positions[i] = path[0].x;
  40382. positions[i + 1] = path[0].y;
  40383. positions[i + 2] = path[0].z;
  40384. i += 3;
  40385. }
  40386. }
  40387. }
  40388. };
  40389. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40390. positionFunction(positions);
  40391. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  40392. instance._boundingInfo.update(instance._worldMatrix);
  40393. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  40394. if (options.colors) {
  40395. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40396. for (var c = 0; c < options.colors.length; c++) {
  40397. colors[c * 4] = options.colors[c].r;
  40398. colors[c * 4 + 1] = options.colors[c].g;
  40399. colors[c * 4 + 2] = options.colors[c].b;
  40400. colors[c * 4 + 3] = options.colors[c].a;
  40401. }
  40402. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  40403. }
  40404. if (options.uvs) {
  40405. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40406. for (var i = 0; i < options.uvs.length; i++) {
  40407. uvs[i * 2] = options.uvs[i].x;
  40408. uvs[i * 2 + 1] = options.uvs[i].y;
  40409. }
  40410. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  40411. }
  40412. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  40413. var indices = instance.getIndices();
  40414. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40415. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  40416. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  40417. if (instance._closePath) {
  40418. var indexFirst = 0;
  40419. var indexLast = 0;
  40420. for (var p = 0; p < pathArray.length; p++) {
  40421. indexFirst = instance._idx[p] * 3;
  40422. if (p + 1 < pathArray.length) {
  40423. indexLast = (instance._idx[p + 1] - 1) * 3;
  40424. }
  40425. else {
  40426. indexLast = normals.length - 3;
  40427. }
  40428. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  40429. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  40430. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  40431. normals[indexLast] = normals[indexFirst];
  40432. normals[indexLast + 1] = normals[indexFirst + 1];
  40433. normals[indexLast + 2] = normals[indexFirst + 2];
  40434. }
  40435. }
  40436. if (!(instance.areNormalsFrozen)) {
  40437. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  40438. }
  40439. }
  40440. return instance;
  40441. }
  40442. else {
  40443. var ribbon = new BABYLON.Mesh(name, scene);
  40444. ribbon.sideOrientation = sideOrientation;
  40445. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  40446. if (closePath) {
  40447. ribbon._idx = vertexData._idx;
  40448. }
  40449. ribbon._closePath = closePath;
  40450. ribbon._closeArray = closeArray;
  40451. vertexData.applyToMesh(ribbon, updatable);
  40452. return ribbon;
  40453. }
  40454. };
  40455. /**
  40456. * Creates a cylinder or a cone mesh.
  40457. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  40458. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  40459. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  40460. * 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.
  40461. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  40462. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  40463. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  40464. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  40465. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  40466. * 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).
  40467. * 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
  40468. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  40469. * 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
  40470. * 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.
  40471. * If `enclose` is false, a ring surface is one element.
  40472. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  40473. * 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
  40474. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40475. * 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).
  40476. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40478. */
  40479. MeshBuilder.CreateCylinder = function (name, options, scene) {
  40480. var cylinder = new BABYLON.Mesh(name, scene);
  40481. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40482. cylinder.sideOrientation = options.sideOrientation;
  40483. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  40484. vertexData.applyToMesh(cylinder, options.updatable);
  40485. return cylinder;
  40486. };
  40487. /**
  40488. * Creates a torus mesh.
  40489. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  40490. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  40491. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  40492. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  40493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40494. * 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).
  40495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40497. */
  40498. MeshBuilder.CreateTorus = function (name, options, scene) {
  40499. var torus = new BABYLON.Mesh(name, scene);
  40500. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40501. torus.sideOrientation = options.sideOrientation;
  40502. var vertexData = BABYLON.VertexData.CreateTorus(options);
  40503. vertexData.applyToMesh(torus, options.updatable);
  40504. return torus;
  40505. };
  40506. /**
  40507. * Creates a torus knot mesh.
  40508. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  40509. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  40510. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  40511. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  40512. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  40513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40514. * 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).
  40515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40517. */
  40518. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  40519. var torusKnot = new BABYLON.Mesh(name, scene);
  40520. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40521. torusKnot.sideOrientation = options.sideOrientation;
  40522. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  40523. vertexData.applyToMesh(torusKnot, options.updatable);
  40524. return torusKnot;
  40525. };
  40526. /**
  40527. * Creates a line system mesh.
  40528. * A line system is a pool of many lines gathered in a single mesh.
  40529. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  40530. * 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.
  40531. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  40532. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  40533. * 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
  40534. * 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
  40535. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  40536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40537. */
  40538. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  40539. var instance = options.instance;
  40540. var lines = options.lines;
  40541. if (instance) {
  40542. var positionFunction = function (positions) {
  40543. var i = 0;
  40544. for (var l = 0; l < lines.length; l++) {
  40545. var points = lines[l];
  40546. for (var p = 0; p < points.length; p++) {
  40547. positions[i] = points[p].x;
  40548. positions[i + 1] = points[p].y;
  40549. positions[i + 2] = points[p].z;
  40550. i += 3;
  40551. }
  40552. }
  40553. };
  40554. instance.updateMeshPositions(positionFunction, false);
  40555. return instance;
  40556. }
  40557. // line system creation
  40558. var lineSystem = new BABYLON.LinesMesh(name, scene);
  40559. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  40560. vertexData.applyToMesh(lineSystem, options.updatable);
  40561. return lineSystem;
  40562. };
  40563. /**
  40564. * Creates a line mesh.
  40565. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  40566. * 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.
  40567. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40568. * The parameter `points` is an array successive Vector3.
  40569. * 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
  40570. * When updating an instance, remember that only point positions can change, not the number of points.
  40571. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40572. */
  40573. MeshBuilder.CreateLines = function (name, options, scene) {
  40574. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  40575. return lines;
  40576. };
  40577. /**
  40578. * Creates a dashed line mesh.
  40579. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  40580. * 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.
  40581. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40582. * The parameter `points` is an array successive Vector3.
  40583. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  40584. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  40585. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  40586. * 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
  40587. * When updating an instance, remember that only point positions can change, not the number of points.
  40588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40589. */
  40590. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  40591. var points = options.points;
  40592. var instance = options.instance;
  40593. var gapSize = options.gapSize;
  40594. var dashNb = options.dashNb;
  40595. var dashSize = options.dashSize;
  40596. if (instance) {
  40597. var positionFunction = function (positions) {
  40598. var curvect = BABYLON.Vector3.Zero();
  40599. var nbSeg = positions.length / 6;
  40600. var lg = 0;
  40601. var nb = 0;
  40602. var shft = 0;
  40603. var dashshft = 0;
  40604. var curshft = 0;
  40605. var p = 0;
  40606. var i = 0;
  40607. var j = 0;
  40608. for (i = 0; i < points.length - 1; i++) {
  40609. points[i + 1].subtractToRef(points[i], curvect);
  40610. lg += curvect.length();
  40611. }
  40612. shft = lg / nbSeg;
  40613. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  40614. for (i = 0; i < points.length - 1; i++) {
  40615. points[i + 1].subtractToRef(points[i], curvect);
  40616. nb = Math.floor(curvect.length() / shft);
  40617. curvect.normalize();
  40618. j = 0;
  40619. while (j < nb && p < positions.length) {
  40620. curshft = shft * j;
  40621. positions[p] = points[i].x + curshft * curvect.x;
  40622. positions[p + 1] = points[i].y + curshft * curvect.y;
  40623. positions[p + 2] = points[i].z + curshft * curvect.z;
  40624. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  40625. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  40626. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  40627. p += 6;
  40628. j++;
  40629. }
  40630. }
  40631. while (p < positions.length) {
  40632. positions[p] = points[i].x;
  40633. positions[p + 1] = points[i].y;
  40634. positions[p + 2] = points[i].z;
  40635. p += 3;
  40636. }
  40637. };
  40638. instance.updateMeshPositions(positionFunction, false);
  40639. return instance;
  40640. }
  40641. // dashed lines creation
  40642. var dashedLines = new BABYLON.LinesMesh(name, scene);
  40643. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  40644. vertexData.applyToMesh(dashedLines, options.updatable);
  40645. dashedLines.dashSize = dashSize;
  40646. dashedLines.gapSize = gapSize;
  40647. return dashedLines;
  40648. };
  40649. /**
  40650. * Creates an extruded shape mesh.
  40651. * 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.
  40652. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40653. *
  40654. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40655. * 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
  40656. * extruded along the Z axis.
  40657. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40658. * 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.
  40659. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40660. * 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
  40661. * 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
  40662. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40664. * 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).
  40665. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40666. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40668. */
  40669. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40670. var path = options.path;
  40671. var shape = options.shape;
  40672. var scale = options.scale || 1;
  40673. var rotation = options.rotation || 0;
  40674. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40675. var updatable = options.updatable;
  40676. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40677. var instance = options.instance;
  40678. var invertUV = options.invertUV || false;
  40679. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40680. };
  40681. /**
  40682. * Creates an custom extruded shape mesh.
  40683. * 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.
  40684. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40685. *
  40686. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40687. * 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
  40688. * extruded along the Z axis.
  40689. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40690. * 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
  40691. * and the distance of this point from the begining of the path :
  40692. * ```javascript
  40693. * var rotationFunction = function(i, distance) {
  40694. * // do things
  40695. * return rotationValue; }
  40696. * ```
  40697. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40698. * 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
  40699. * and the distance of this point from the begining of the path :
  40700. * ```javascript
  40701. * var scaleFunction = function(i, distance) {
  40702. * // do things
  40703. * return scaleValue;}
  40704. * ```
  40705. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40706. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40707. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40708. * 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
  40709. * 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
  40710. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40711. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40712. * 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).
  40713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40714. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40716. */
  40717. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40718. var path = options.path;
  40719. var shape = options.shape;
  40720. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40721. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40722. var ribbonCloseArray = options.ribbonCloseArray || false;
  40723. var ribbonClosePath = options.ribbonClosePath || false;
  40724. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40725. var updatable = options.updatable;
  40726. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40727. var instance = options.instance;
  40728. var invertUV = options.invertUV || false;
  40729. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40730. };
  40731. /**
  40732. * Creates lathe mesh.
  40733. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40734. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40735. *
  40736. * 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
  40737. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40738. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40739. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40740. * 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.
  40741. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40742. * 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
  40743. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40744. * 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).
  40745. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40746. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40748. */
  40749. MeshBuilder.CreateLathe = function (name, options, scene) {
  40750. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40751. var closed = (options.closed === undefined) ? true : options.closed;
  40752. var shape = options.shape;
  40753. var radius = options.radius || 1;
  40754. var tessellation = options.tessellation || 64;
  40755. var updatable = options.updatable;
  40756. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40757. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40758. var pi2 = Math.PI * 2;
  40759. var paths = new Array();
  40760. var invertUV = options.invertUV || false;
  40761. var i = 0;
  40762. var p = 0;
  40763. var step = pi2 / tessellation * arc;
  40764. var rotated;
  40765. var path = new Array();
  40766. ;
  40767. for (i = 0; i <= tessellation; i++) {
  40768. var path = [];
  40769. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40770. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40771. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40772. }
  40773. for (p = 0; p < shape.length; p++) {
  40774. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40775. path.push(rotated);
  40776. }
  40777. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40778. 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));
  40779. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40780. }
  40781. paths.push(path);
  40782. }
  40783. // lathe ribbon
  40784. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40785. return lathe;
  40786. };
  40787. /**
  40788. * Creates a plane mesh.
  40789. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40790. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40791. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40792. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40793. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40794. * 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).
  40795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40797. */
  40798. MeshBuilder.CreatePlane = function (name, options, scene) {
  40799. var plane = new BABYLON.Mesh(name, scene);
  40800. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40801. plane.sideOrientation = options.sideOrientation;
  40802. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40803. vertexData.applyToMesh(plane, options.updatable);
  40804. if (options.sourcePlane) {
  40805. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40806. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40807. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40808. plane.rotate(vectorProduct, product);
  40809. }
  40810. return plane;
  40811. };
  40812. /**
  40813. * Creates a ground mesh.
  40814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40815. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40816. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40818. */
  40819. MeshBuilder.CreateGround = function (name, options, scene) {
  40820. var ground = new BABYLON.GroundMesh(name, scene);
  40821. ground._setReady(false);
  40822. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40823. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40824. ground._width = options.width || 1;
  40825. ground._height = options.height || 1;
  40826. ground._maxX = ground._width / 2;
  40827. ground._maxZ = ground._height / 2;
  40828. ground._minX = -ground._maxX;
  40829. ground._minZ = -ground._maxZ;
  40830. var vertexData = BABYLON.VertexData.CreateGround(options);
  40831. vertexData.applyToMesh(ground, options.updatable);
  40832. ground._setReady(true);
  40833. return ground;
  40834. };
  40835. /**
  40836. * Creates a tiled ground mesh.
  40837. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40838. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40839. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40840. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40841. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40842. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40843. * numbers of subdivisions on the ground width and height of each tile.
  40844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40845. */
  40846. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40847. var tiledGround = new BABYLON.Mesh(name, scene);
  40848. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40849. vertexData.applyToMesh(tiledGround, options.updatable);
  40850. return tiledGround;
  40851. };
  40852. /**
  40853. * Creates a ground mesh from a height map.
  40854. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40855. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40856. * The parameter `url` sets the URL of the height map image resource.
  40857. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40858. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40859. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40860. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40861. * 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.
  40862. * 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).
  40863. * This function is passed the newly built mesh :
  40864. * ```javascript
  40865. * function(mesh) { // do things
  40866. * return; }
  40867. * ```
  40868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40869. */
  40870. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40871. var width = options.width || 10.0;
  40872. var height = options.height || 10.0;
  40873. var subdivisions = options.subdivisions || 1 | 0;
  40874. var minHeight = options.minHeight || 0.0;
  40875. var maxHeight = options.maxHeight || 10.0;
  40876. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40877. var updatable = options.updatable;
  40878. var onReady = options.onReady;
  40879. var ground = new BABYLON.GroundMesh(name, scene);
  40880. ground._subdivisionsX = subdivisions;
  40881. ground._subdivisionsY = subdivisions;
  40882. ground._width = width;
  40883. ground._height = height;
  40884. ground._maxX = ground._width / 2.0;
  40885. ground._maxZ = ground._height / 2.0;
  40886. ground._minX = -ground._maxX;
  40887. ground._minZ = -ground._maxZ;
  40888. ground._setReady(false);
  40889. var onload = function (img) {
  40890. // Getting height map data
  40891. var canvas = document.createElement("canvas");
  40892. var context = canvas.getContext("2d");
  40893. var bufferWidth = img.width;
  40894. var bufferHeight = img.height;
  40895. canvas.width = bufferWidth;
  40896. canvas.height = bufferHeight;
  40897. context.drawImage(img, 0, 0);
  40898. // Create VertexData from map data
  40899. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40900. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40901. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40902. width: width, height: height,
  40903. subdivisions: subdivisions,
  40904. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40905. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40906. });
  40907. vertexData.applyToMesh(ground, updatable);
  40908. ground._setReady(true);
  40909. //execute ready callback, if set
  40910. if (onReady) {
  40911. onReady(ground);
  40912. }
  40913. };
  40914. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40915. return ground;
  40916. };
  40917. /**
  40918. * Creates a polygon mesh.
  40919. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40920. * 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.
  40921. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40923. * 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).
  40924. * Remember you can only change the shape positions, not their number when updating a polygon.
  40925. */
  40926. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40927. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40928. var shape = options.shape;
  40929. var holes = options.holes || [];
  40930. var depth = options.depth || 0;
  40931. var contours = [];
  40932. var hole = [];
  40933. for (var i = 0; i < shape.length; i++) {
  40934. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40935. }
  40936. var epsilon = 0.00000001;
  40937. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40938. contours.pop();
  40939. }
  40940. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40941. for (var hNb = 0; hNb < holes.length; hNb++) {
  40942. hole = [];
  40943. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40944. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40945. }
  40946. polygonTriangulation.addHole(hole);
  40947. }
  40948. var polygon = polygonTriangulation.build(options.updatable, depth);
  40949. polygon.sideOrientation = options.sideOrientation;
  40950. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40951. vertexData.applyToMesh(polygon, options.updatable);
  40952. return polygon;
  40953. };
  40954. ;
  40955. /**
  40956. * Creates an extruded polygon mesh, with depth in the Y direction.
  40957. * 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).
  40958. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40959. */
  40960. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40961. return MeshBuilder.CreatePolygon(name, options, scene);
  40962. };
  40963. ;
  40964. /**
  40965. * Creates a tube mesh.
  40966. * 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.
  40967. *
  40968. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40969. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40970. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40971. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40972. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40973. * 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.
  40974. * It must return a radius value (positive float) :
  40975. * ```javascript
  40976. * var radiusFunction = function(i, distance) {
  40977. * // do things
  40978. * return radius; }
  40979. * ```
  40980. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40981. * 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
  40982. * 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
  40983. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40984. * 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).
  40985. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40986. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40988. */
  40989. MeshBuilder.CreateTube = function (name, options, scene) {
  40990. var path = options.path;
  40991. var radius = options.radius || 1.0;
  40992. var tessellation = options.tessellation || 64 | 0;
  40993. var radiusFunction = options.radiusFunction;
  40994. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40995. var invertUV = options.invertUV || false;
  40996. var updatable = options.updatable;
  40997. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40998. var instance = options.instance;
  40999. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  41000. // tube geometry
  41001. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  41002. var tangents = path3D.getTangents();
  41003. var normals = path3D.getNormals();
  41004. var distances = path3D.getDistances();
  41005. var pi2 = Math.PI * 2;
  41006. var step = pi2 / tessellation * arc;
  41007. var returnRadius = function () { return radius; };
  41008. var radiusFunctionFinal = radiusFunction || returnRadius;
  41009. var circlePath;
  41010. var rad;
  41011. var normal;
  41012. var rotated;
  41013. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41014. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41015. for (var i = 0; i < path.length; i++) {
  41016. rad = radiusFunctionFinal(i, distances[i]); // current radius
  41017. circlePath = Array(); // current circle array
  41018. normal = normals[i]; // current normal
  41019. for (var t = 0; t < tessellation; t++) {
  41020. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  41021. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  41022. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  41023. rotated.scaleInPlace(rad).addInPlace(path[i]);
  41024. circlePath[t] = rotated;
  41025. }
  41026. circlePaths[index] = circlePath;
  41027. index++;
  41028. }
  41029. // cap
  41030. var capPath = function (nbPoints, pathIndex) {
  41031. var pointCap = Array();
  41032. for (var i = 0; i < nbPoints; i++) {
  41033. pointCap.push(path[pathIndex]);
  41034. }
  41035. return pointCap;
  41036. };
  41037. switch (cap) {
  41038. case BABYLON.Mesh.NO_CAP:
  41039. break;
  41040. case BABYLON.Mesh.CAP_START:
  41041. circlePaths[0] = capPath(tessellation, 0);
  41042. circlePaths[1] = circlePaths[2].slice(0);
  41043. break;
  41044. case BABYLON.Mesh.CAP_END:
  41045. circlePaths[index] = circlePaths[index - 1].slice(0);
  41046. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41047. break;
  41048. case BABYLON.Mesh.CAP_ALL:
  41049. circlePaths[0] = capPath(tessellation, 0);
  41050. circlePaths[1] = circlePaths[2].slice(0);
  41051. circlePaths[index] = circlePaths[index - 1].slice(0);
  41052. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41053. break;
  41054. default:
  41055. break;
  41056. }
  41057. return circlePaths;
  41058. };
  41059. var path3D;
  41060. var pathArray;
  41061. if (instance) {
  41062. var arc = options.arc || instance.arc;
  41063. path3D = (instance.path3D).update(path);
  41064. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  41065. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  41066. instance.path3D = path3D;
  41067. instance.pathArray = pathArray;
  41068. instance.arc = arc;
  41069. return instance;
  41070. }
  41071. // tube creation
  41072. path3D = new BABYLON.Path3D(path);
  41073. var newPathArray = new Array();
  41074. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41075. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  41076. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41077. tube.pathArray = pathArray;
  41078. tube.path3D = path3D;
  41079. tube.tessellation = tessellation;
  41080. tube.cap = cap;
  41081. tube.arc = options.arc;
  41082. return tube;
  41083. };
  41084. /**
  41085. * Creates a polyhedron mesh.
  41086. *
  41087. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  41088. * 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
  41089. * to choose the wanted type.
  41090. * The parameter `size` (positive float, default 1) sets the polygon size.
  41091. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  41092. * 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`.
  41093. * 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
  41094. * 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)`).
  41095. * 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
  41096. * 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.
  41097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41098. * 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).
  41099. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41100. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41101. */
  41102. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  41103. var polyhedron = new BABYLON.Mesh(name, scene);
  41104. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41105. polyhedron.sideOrientation = options.sideOrientation;
  41106. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  41107. vertexData.applyToMesh(polyhedron, options.updatable);
  41108. return polyhedron;
  41109. };
  41110. /**
  41111. * Creates a decal mesh.
  41112. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  41113. * 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.
  41114. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  41115. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  41116. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  41117. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  41118. */
  41119. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  41120. var indices = sourceMesh.getIndices();
  41121. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41122. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41123. var position = options.position || BABYLON.Vector3.Zero();
  41124. var normal = options.normal || BABYLON.Vector3.Up();
  41125. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  41126. var angle = options.angle || 0;
  41127. // Getting correct rotation
  41128. if (!normal) {
  41129. var target = new BABYLON.Vector3(0, 0, 1);
  41130. var camera = sourceMesh.getScene().activeCamera;
  41131. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  41132. normal = camera.globalPosition.subtract(cameraWorldTarget);
  41133. }
  41134. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  41135. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  41136. var pitch = Math.atan2(normal.y, len);
  41137. // Matrix
  41138. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  41139. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  41140. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  41141. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  41142. var vertexData = new BABYLON.VertexData();
  41143. vertexData.indices = [];
  41144. vertexData.positions = [];
  41145. vertexData.normals = [];
  41146. vertexData.uvs = [];
  41147. var currentVertexDataIndex = 0;
  41148. var extractDecalVector3 = function (indexId) {
  41149. var vertexId = indices[indexId];
  41150. var result = new BABYLON.PositionNormalVertex();
  41151. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  41152. // Send vector to decal local world
  41153. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  41154. // Get normal
  41155. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  41156. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  41157. return result;
  41158. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  41159. var clip = function (vertices, axis) {
  41160. if (vertices.length === 0) {
  41161. return vertices;
  41162. }
  41163. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  41164. var clipVertices = function (v0, v1) {
  41165. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  41166. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  41167. };
  41168. var result = new Array();
  41169. for (var index = 0; index < vertices.length; index += 3) {
  41170. var v1Out;
  41171. var v2Out;
  41172. var v3Out;
  41173. var total = 0;
  41174. var nV1, nV2, nV3, nV4;
  41175. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  41176. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  41177. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  41178. v1Out = d1 > 0;
  41179. v2Out = d2 > 0;
  41180. v3Out = d3 > 0;
  41181. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  41182. switch (total) {
  41183. case 0:
  41184. result.push(vertices[index]);
  41185. result.push(vertices[index + 1]);
  41186. result.push(vertices[index + 2]);
  41187. break;
  41188. case 1:
  41189. if (v1Out) {
  41190. nV1 = vertices[index + 1];
  41191. nV2 = vertices[index + 2];
  41192. nV3 = clipVertices(vertices[index], nV1);
  41193. nV4 = clipVertices(vertices[index], nV2);
  41194. }
  41195. if (v2Out) {
  41196. nV1 = vertices[index];
  41197. nV2 = vertices[index + 2];
  41198. nV3 = clipVertices(vertices[index + 1], nV1);
  41199. nV4 = clipVertices(vertices[index + 1], nV2);
  41200. result.push(nV3);
  41201. result.push(nV2.clone());
  41202. result.push(nV1.clone());
  41203. result.push(nV2.clone());
  41204. result.push(nV3.clone());
  41205. result.push(nV4);
  41206. break;
  41207. }
  41208. if (v3Out) {
  41209. nV1 = vertices[index];
  41210. nV2 = vertices[index + 1];
  41211. nV3 = clipVertices(vertices[index + 2], nV1);
  41212. nV4 = clipVertices(vertices[index + 2], nV2);
  41213. }
  41214. result.push(nV1.clone());
  41215. result.push(nV2.clone());
  41216. result.push(nV3);
  41217. result.push(nV4);
  41218. result.push(nV3.clone());
  41219. result.push(nV2.clone());
  41220. break;
  41221. case 2:
  41222. if (!v1Out) {
  41223. nV1 = vertices[index].clone();
  41224. nV2 = clipVertices(nV1, vertices[index + 1]);
  41225. nV3 = clipVertices(nV1, vertices[index + 2]);
  41226. result.push(nV1);
  41227. result.push(nV2);
  41228. result.push(nV3);
  41229. }
  41230. if (!v2Out) {
  41231. nV1 = vertices[index + 1].clone();
  41232. nV2 = clipVertices(nV1, vertices[index + 2]);
  41233. nV3 = clipVertices(nV1, vertices[index]);
  41234. result.push(nV1);
  41235. result.push(nV2);
  41236. result.push(nV3);
  41237. }
  41238. if (!v3Out) {
  41239. nV1 = vertices[index + 2].clone();
  41240. nV2 = clipVertices(nV1, vertices[index]);
  41241. nV3 = clipVertices(nV1, vertices[index + 1]);
  41242. result.push(nV1);
  41243. result.push(nV2);
  41244. result.push(nV3);
  41245. }
  41246. break;
  41247. case 3:
  41248. break;
  41249. }
  41250. }
  41251. return result;
  41252. };
  41253. for (var index = 0; index < indices.length; index += 3) {
  41254. var faceVertices = new Array();
  41255. faceVertices.push(extractDecalVector3(index));
  41256. faceVertices.push(extractDecalVector3(index + 1));
  41257. faceVertices.push(extractDecalVector3(index + 2));
  41258. // Clip
  41259. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  41260. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  41261. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  41262. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  41263. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  41264. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  41265. if (faceVertices.length === 0) {
  41266. continue;
  41267. }
  41268. // Add UVs and get back to world
  41269. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  41270. var vertex = faceVertices[vIndex];
  41271. //TODO check for Int32Array | Uint32Array | Uint16Array
  41272. vertexData.indices.push(currentVertexDataIndex);
  41273. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  41274. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  41275. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  41276. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  41277. currentVertexDataIndex++;
  41278. }
  41279. }
  41280. // Return mesh
  41281. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  41282. vertexData.applyToMesh(decal);
  41283. decal.position = position.clone();
  41284. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  41285. return decal;
  41286. };
  41287. // Privates
  41288. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  41289. // extrusion geometry
  41290. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  41291. var tangents = path3D.getTangents();
  41292. var normals = path3D.getNormals();
  41293. var binormals = path3D.getBinormals();
  41294. var distances = path3D.getDistances();
  41295. var angle = 0;
  41296. var returnScale = function () { return scale; };
  41297. var returnRotation = function () { return rotation; };
  41298. var rotate = custom ? rotateFunction : returnRotation;
  41299. var scl = custom ? scaleFunction : returnScale;
  41300. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41301. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41302. for (var i = 0; i < curve.length; i++) {
  41303. var shapePath = new Array();
  41304. var angleStep = rotate(i, distances[i]);
  41305. var scaleRatio = scl(i, distances[i]);
  41306. for (var p = 0; p < shape.length; p++) {
  41307. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  41308. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  41309. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  41310. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  41311. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  41312. shapePath[p] = rotated;
  41313. }
  41314. shapePaths[index] = shapePath;
  41315. angle += angleStep;
  41316. index++;
  41317. }
  41318. // cap
  41319. var capPath = function (shapePath) {
  41320. var pointCap = Array();
  41321. var barycenter = BABYLON.Vector3.Zero();
  41322. var i;
  41323. for (i = 0; i < shapePath.length; i++) {
  41324. barycenter.addInPlace(shapePath[i]);
  41325. }
  41326. barycenter.scaleInPlace(1.0 / shapePath.length);
  41327. for (i = 0; i < shapePath.length; i++) {
  41328. pointCap.push(barycenter);
  41329. }
  41330. return pointCap;
  41331. };
  41332. switch (cap) {
  41333. case BABYLON.Mesh.NO_CAP:
  41334. break;
  41335. case BABYLON.Mesh.CAP_START:
  41336. shapePaths[0] = capPath(shapePaths[2]);
  41337. shapePaths[1] = shapePaths[2];
  41338. break;
  41339. case BABYLON.Mesh.CAP_END:
  41340. shapePaths[index] = shapePaths[index - 1];
  41341. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41342. break;
  41343. case BABYLON.Mesh.CAP_ALL:
  41344. shapePaths[0] = capPath(shapePaths[2]);
  41345. shapePaths[1] = shapePaths[2];
  41346. shapePaths[index] = shapePaths[index - 1];
  41347. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41348. break;
  41349. default:
  41350. break;
  41351. }
  41352. return shapePaths;
  41353. };
  41354. var path3D;
  41355. var pathArray;
  41356. if (instance) {
  41357. path3D = (instance.path3D).update(curve);
  41358. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  41359. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  41360. return instance;
  41361. }
  41362. // extruded shape creation
  41363. path3D = new BABYLON.Path3D(curve);
  41364. var newShapePaths = new Array();
  41365. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41366. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  41367. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  41368. extrudedGeneric.pathArray = pathArray;
  41369. extrudedGeneric.path3D = path3D;
  41370. extrudedGeneric.cap = cap;
  41371. return extrudedGeneric;
  41372. };
  41373. return MeshBuilder;
  41374. }());
  41375. BABYLON.MeshBuilder = MeshBuilder;
  41376. })(BABYLON || (BABYLON = {}));
  41377. //# sourceMappingURL=babylon.meshBuilder.js.map
  41378. var BABYLON;
  41379. (function (BABYLON) {
  41380. var AudioEngine = (function () {
  41381. function AudioEngine() {
  41382. this._audioContext = null;
  41383. this._audioContextInitialized = false;
  41384. this.canUseWebAudio = false;
  41385. this.WarnedWebAudioUnsupported = false;
  41386. this.unlocked = false;
  41387. this.isMP3supported = false;
  41388. this.isOGGsupported = false;
  41389. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41390. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41391. this.canUseWebAudio = true;
  41392. }
  41393. var audioElem = document.createElement('audio');
  41394. try {
  41395. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41396. this.isMP3supported = true;
  41397. }
  41398. }
  41399. catch (e) {
  41400. // protect error during capability check.
  41401. }
  41402. try {
  41403. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41404. this.isOGGsupported = true;
  41405. }
  41406. }
  41407. catch (e) {
  41408. // protect error during capability check.
  41409. }
  41410. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41411. this._unlockiOSaudio();
  41412. }
  41413. else {
  41414. this.unlocked = true;
  41415. }
  41416. }
  41417. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41418. get: function () {
  41419. if (!this._audioContextInitialized) {
  41420. this._initializeAudioContext();
  41421. }
  41422. return this._audioContext;
  41423. },
  41424. enumerable: true,
  41425. configurable: true
  41426. });
  41427. AudioEngine.prototype._unlockiOSaudio = function () {
  41428. var _this = this;
  41429. var unlockaudio = function () {
  41430. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41431. var source = _this.audioContext.createBufferSource();
  41432. source.buffer = buffer;
  41433. source.connect(_this.audioContext.destination);
  41434. source.start(0);
  41435. setTimeout(function () {
  41436. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41437. _this.unlocked = true;
  41438. window.removeEventListener('touchend', unlockaudio, false);
  41439. if (_this.onAudioUnlocked) {
  41440. _this.onAudioUnlocked();
  41441. }
  41442. }
  41443. }, 0);
  41444. };
  41445. window.addEventListener('touchend', unlockaudio, false);
  41446. };
  41447. AudioEngine.prototype._initializeAudioContext = function () {
  41448. try {
  41449. if (this.canUseWebAudio) {
  41450. this._audioContext = new AudioContext();
  41451. // create a global volume gain node
  41452. this.masterGain = this._audioContext.createGain();
  41453. this.masterGain.gain.value = 1;
  41454. this.masterGain.connect(this._audioContext.destination);
  41455. this._audioContextInitialized = true;
  41456. }
  41457. }
  41458. catch (e) {
  41459. this.canUseWebAudio = false;
  41460. BABYLON.Tools.Error("Web Audio: " + e.message);
  41461. }
  41462. };
  41463. AudioEngine.prototype.dispose = function () {
  41464. if (this.canUseWebAudio && this._audioContextInitialized) {
  41465. if (this._connectedAnalyser) {
  41466. this._connectedAnalyser.stopDebugCanvas();
  41467. this._connectedAnalyser.dispose();
  41468. this.masterGain.disconnect();
  41469. this.masterGain.connect(this._audioContext.destination);
  41470. this._connectedAnalyser = null;
  41471. }
  41472. this.masterGain.gain.value = 1;
  41473. }
  41474. this.WarnedWebAudioUnsupported = false;
  41475. };
  41476. AudioEngine.prototype.getGlobalVolume = function () {
  41477. if (this.canUseWebAudio && this._audioContextInitialized) {
  41478. return this.masterGain.gain.value;
  41479. }
  41480. else {
  41481. return -1;
  41482. }
  41483. };
  41484. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41485. if (this.canUseWebAudio && this._audioContextInitialized) {
  41486. this.masterGain.gain.value = newVolume;
  41487. }
  41488. };
  41489. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41490. if (this._connectedAnalyser) {
  41491. this._connectedAnalyser.stopDebugCanvas();
  41492. }
  41493. if (this.canUseWebAudio && this._audioContextInitialized) {
  41494. this._connectedAnalyser = analyser;
  41495. this.masterGain.disconnect();
  41496. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41497. }
  41498. };
  41499. return AudioEngine;
  41500. }());
  41501. BABYLON.AudioEngine = AudioEngine;
  41502. })(BABYLON || (BABYLON = {}));
  41503. //# sourceMappingURL=babylon.audioEngine.js.map
  41504. var BABYLON;
  41505. (function (BABYLON) {
  41506. var Sound = (function () {
  41507. /**
  41508. * Create a sound and attach it to a scene
  41509. * @param name Name of your sound
  41510. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41511. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41512. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41513. */
  41514. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41515. var _this = this;
  41516. this.autoplay = false;
  41517. this.loop = false;
  41518. this.useCustomAttenuation = false;
  41519. this.spatialSound = false;
  41520. this.refDistance = 1;
  41521. this.rolloffFactor = 1;
  41522. this.maxDistance = 100;
  41523. this.distanceModel = "linear";
  41524. this._panningModel = "equalpower";
  41525. this._playbackRate = 1;
  41526. this._streaming = false;
  41527. this._startTime = 0;
  41528. this._startOffset = 0;
  41529. this._position = BABYLON.Vector3.Zero();
  41530. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41531. this._volume = 1;
  41532. this._isLoaded = false;
  41533. this._isReadyToPlay = false;
  41534. this.isPlaying = false;
  41535. this.isPaused = false;
  41536. this._isDirectional = false;
  41537. // Used if you'd like to create a directional sound.
  41538. // If not set, the sound will be omnidirectional
  41539. this._coneInnerAngle = 360;
  41540. this._coneOuterAngle = 360;
  41541. this._coneOuterGain = 0;
  41542. this._isOutputConnected = false;
  41543. this._urlType = "Unknown";
  41544. this.name = name;
  41545. this._scene = scene;
  41546. this._readyToPlayCallback = readyToPlayCallback;
  41547. // Default custom attenuation function is a linear attenuation
  41548. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41549. if (currentDistance < maxDistance) {
  41550. return currentVolume * (1 - currentDistance / maxDistance);
  41551. }
  41552. else {
  41553. return 0;
  41554. }
  41555. };
  41556. if (options) {
  41557. this.autoplay = options.autoplay || false;
  41558. this.loop = options.loop || false;
  41559. // if volume === 0, we need another way to check this option
  41560. if (options.volume !== undefined) {
  41561. this._volume = options.volume;
  41562. }
  41563. this.spatialSound = options.spatialSound || false;
  41564. this.maxDistance = options.maxDistance || 100;
  41565. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41566. this.rolloffFactor = options.rolloffFactor || 1;
  41567. this.refDistance = options.refDistance || 1;
  41568. this.distanceModel = options.distanceModel || "linear";
  41569. this._playbackRate = options.playbackRate || 1;
  41570. this._streaming = options.streaming || false;
  41571. }
  41572. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41573. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41574. this._soundGain.gain.value = this._volume;
  41575. this._inputAudioNode = this._soundGain;
  41576. this._ouputAudioNode = this._soundGain;
  41577. if (this.spatialSound) {
  41578. this._createSpatialParameters();
  41579. }
  41580. this._scene.mainSoundTrack.AddSound(this);
  41581. var validParameter = true;
  41582. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41583. if (urlOrArrayBuffer) {
  41584. if (typeof (urlOrArrayBuffer) === "string")
  41585. this._urlType = "String";
  41586. if (Array.isArray(urlOrArrayBuffer))
  41587. this._urlType = "Array";
  41588. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41589. this._urlType = "ArrayBuffer";
  41590. var urls = [];
  41591. var codecSupportedFound = false;
  41592. switch (this._urlType) {
  41593. case "ArrayBuffer":
  41594. if (urlOrArrayBuffer.byteLength > 0) {
  41595. codecSupportedFound = true;
  41596. this._soundLoaded(urlOrArrayBuffer);
  41597. }
  41598. break;
  41599. case "String":
  41600. urls.push(urlOrArrayBuffer);
  41601. case "Array":
  41602. if (urls.length === 0)
  41603. urls = urlOrArrayBuffer;
  41604. // If we found a supported format, we load it immediately and stop the loop
  41605. for (var i = 0; i < urls.length; i++) {
  41606. var url = urls[i];
  41607. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41608. codecSupportedFound = true;
  41609. }
  41610. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41611. codecSupportedFound = true;
  41612. }
  41613. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41614. codecSupportedFound = true;
  41615. }
  41616. if (codecSupportedFound) {
  41617. // Loading sound using XHR2
  41618. if (!this._streaming) {
  41619. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41620. }
  41621. else {
  41622. this._htmlAudioElement = new Audio(url);
  41623. this._htmlAudioElement.controls = false;
  41624. this._htmlAudioElement.loop = this.loop;
  41625. this._htmlAudioElement.crossOrigin = "anonymous";
  41626. this._htmlAudioElement.preload = "auto";
  41627. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41628. _this._isReadyToPlay = true;
  41629. if (_this.autoplay) {
  41630. _this.play();
  41631. }
  41632. if (_this._readyToPlayCallback) {
  41633. _this._readyToPlayCallback();
  41634. }
  41635. });
  41636. document.body.appendChild(this._htmlAudioElement);
  41637. }
  41638. break;
  41639. }
  41640. }
  41641. break;
  41642. default:
  41643. validParameter = false;
  41644. break;
  41645. }
  41646. if (!validParameter) {
  41647. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41648. }
  41649. else {
  41650. if (!codecSupportedFound) {
  41651. this._isReadyToPlay = true;
  41652. // Simulating a ready to play event to avoid breaking code path
  41653. if (this._readyToPlayCallback) {
  41654. window.setTimeout(function () {
  41655. _this._readyToPlayCallback();
  41656. }, 1000);
  41657. }
  41658. }
  41659. }
  41660. }
  41661. }
  41662. else {
  41663. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  41664. this._scene.mainSoundTrack.AddSound(this);
  41665. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  41666. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  41667. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  41668. }
  41669. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  41670. if (this._readyToPlayCallback) {
  41671. window.setTimeout(function () {
  41672. _this._readyToPlayCallback();
  41673. }, 1000);
  41674. }
  41675. }
  41676. }
  41677. Sound.prototype.dispose = function () {
  41678. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  41679. if (this.isPlaying) {
  41680. this.stop();
  41681. }
  41682. this._isReadyToPlay = false;
  41683. if (this.soundTrackId === -1) {
  41684. this._scene.mainSoundTrack.RemoveSound(this);
  41685. }
  41686. else {
  41687. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  41688. }
  41689. if (this._soundGain) {
  41690. this._soundGain.disconnect();
  41691. this._soundGain = null;
  41692. }
  41693. if (this._soundPanner) {
  41694. this._soundPanner.disconnect();
  41695. this._soundPanner = null;
  41696. }
  41697. if (this._soundSource) {
  41698. this._soundSource.disconnect();
  41699. this._soundSource = null;
  41700. }
  41701. this._audioBuffer = null;
  41702. if (this._htmlAudioElement) {
  41703. this._htmlAudioElement.pause();
  41704. this._htmlAudioElement.src = "";
  41705. document.body.removeChild(this._htmlAudioElement);
  41706. }
  41707. if (this._connectedMesh) {
  41708. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41709. this._connectedMesh = null;
  41710. }
  41711. }
  41712. };
  41713. Sound.prototype.isReady = function () {
  41714. return this._isReadyToPlay;
  41715. };
  41716. Sound.prototype._soundLoaded = function (audioData) {
  41717. var _this = this;
  41718. this._isLoaded = true;
  41719. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  41720. _this._audioBuffer = buffer;
  41721. _this._isReadyToPlay = true;
  41722. if (_this.autoplay) {
  41723. _this.play();
  41724. }
  41725. if (_this._readyToPlayCallback) {
  41726. _this._readyToPlayCallback();
  41727. }
  41728. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  41729. };
  41730. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  41731. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41732. this._audioBuffer = audioBuffer;
  41733. this._isReadyToPlay = true;
  41734. }
  41735. };
  41736. Sound.prototype.updateOptions = function (options) {
  41737. if (options) {
  41738. this.loop = options.loop || this.loop;
  41739. this.maxDistance = options.maxDistance || this.maxDistance;
  41740. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  41741. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  41742. this.refDistance = options.refDistance || this.refDistance;
  41743. this.distanceModel = options.distanceModel || this.distanceModel;
  41744. this._playbackRate = options.playbackRate || this._playbackRate;
  41745. this._updateSpatialParameters();
  41746. if (this.isPlaying) {
  41747. if (this._streaming) {
  41748. this._htmlAudioElement.playbackRate = this._playbackRate;
  41749. }
  41750. else {
  41751. this._soundSource.playbackRate.value = this._playbackRate;
  41752. }
  41753. }
  41754. }
  41755. };
  41756. Sound.prototype._createSpatialParameters = function () {
  41757. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41758. if (this._scene.headphone) {
  41759. this._panningModel = "HRTF";
  41760. }
  41761. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  41762. this._updateSpatialParameters();
  41763. this._soundPanner.connect(this._ouputAudioNode);
  41764. this._inputAudioNode = this._soundPanner;
  41765. }
  41766. };
  41767. Sound.prototype._updateSpatialParameters = function () {
  41768. if (this.spatialSound) {
  41769. if (this.useCustomAttenuation) {
  41770. // Tricks to disable in a way embedded Web Audio attenuation
  41771. this._soundPanner.distanceModel = "linear";
  41772. this._soundPanner.maxDistance = Number.MAX_VALUE;
  41773. this._soundPanner.refDistance = 1;
  41774. this._soundPanner.rolloffFactor = 1;
  41775. this._soundPanner.panningModel = this._panningModel;
  41776. }
  41777. else {
  41778. this._soundPanner.distanceModel = this.distanceModel;
  41779. this._soundPanner.maxDistance = this.maxDistance;
  41780. this._soundPanner.refDistance = this.refDistance;
  41781. this._soundPanner.rolloffFactor = this.rolloffFactor;
  41782. this._soundPanner.panningModel = this._panningModel;
  41783. }
  41784. }
  41785. };
  41786. Sound.prototype.switchPanningModelToHRTF = function () {
  41787. this._panningModel = "HRTF";
  41788. this._switchPanningModel();
  41789. };
  41790. Sound.prototype.switchPanningModelToEqualPower = function () {
  41791. this._panningModel = "equalpower";
  41792. this._switchPanningModel();
  41793. };
  41794. Sound.prototype._switchPanningModel = function () {
  41795. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41796. this._soundPanner.panningModel = this._panningModel;
  41797. }
  41798. };
  41799. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  41800. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41801. if (this._isOutputConnected) {
  41802. this._ouputAudioNode.disconnect();
  41803. }
  41804. this._ouputAudioNode.connect(soundTrackAudioNode);
  41805. this._isOutputConnected = true;
  41806. }
  41807. };
  41808. /**
  41809. * Transform this sound into a directional source
  41810. * @param coneInnerAngle Size of the inner cone in degree
  41811. * @param coneOuterAngle Size of the outer cone in degree
  41812. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  41813. */
  41814. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  41815. if (coneOuterAngle < coneInnerAngle) {
  41816. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  41817. return;
  41818. }
  41819. this._coneInnerAngle = coneInnerAngle;
  41820. this._coneOuterAngle = coneOuterAngle;
  41821. this._coneOuterGain = coneOuterGain;
  41822. this._isDirectional = true;
  41823. if (this.isPlaying && this.loop) {
  41824. this.stop();
  41825. this.play();
  41826. }
  41827. };
  41828. Sound.prototype.setPosition = function (newPosition) {
  41829. this._position = newPosition;
  41830. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41831. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41832. }
  41833. };
  41834. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  41835. this._localDirection = newLocalDirection;
  41836. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  41837. this._updateDirection();
  41838. }
  41839. };
  41840. Sound.prototype._updateDirection = function () {
  41841. var mat = this._connectedMesh.getWorldMatrix();
  41842. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  41843. direction.normalize();
  41844. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  41845. };
  41846. Sound.prototype.updateDistanceFromListener = function () {
  41847. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  41848. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  41849. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  41850. }
  41851. };
  41852. Sound.prototype.setAttenuationFunction = function (callback) {
  41853. this._customAttenuationFunction = callback;
  41854. };
  41855. /**
  41856. * Play the sound
  41857. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  41858. * @param offset (optional) Start the sound setting it at a specific time
  41859. */
  41860. Sound.prototype.play = function (time, offset) {
  41861. var _this = this;
  41862. if (this._isReadyToPlay && this._scene.audioEnabled) {
  41863. try {
  41864. if (this._startOffset < 0) {
  41865. time = -this._startOffset;
  41866. this._startOffset = 0;
  41867. }
  41868. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41869. if (!this._soundSource || !this._streamingSource) {
  41870. if (this.spatialSound) {
  41871. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41872. if (this._isDirectional) {
  41873. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  41874. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  41875. this._soundPanner.coneOuterGain = this._coneOuterGain;
  41876. if (this._connectedMesh) {
  41877. this._updateDirection();
  41878. }
  41879. else {
  41880. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  41881. }
  41882. }
  41883. }
  41884. }
  41885. if (this._streaming) {
  41886. if (!this._streamingSource) {
  41887. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  41888. this._htmlAudioElement.onended = function () { _this._onended(); };
  41889. this._htmlAudioElement.playbackRate = this._playbackRate;
  41890. }
  41891. this._streamingSource.disconnect();
  41892. this._streamingSource.connect(this._inputAudioNode);
  41893. this._htmlAudioElement.play();
  41894. }
  41895. else {
  41896. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  41897. this._soundSource.buffer = this._audioBuffer;
  41898. this._soundSource.connect(this._inputAudioNode);
  41899. this._soundSource.loop = this.loop;
  41900. this._soundSource.playbackRate.value = this._playbackRate;
  41901. this._soundSource.onended = function () { _this._onended(); };
  41902. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  41903. }
  41904. this._startTime = startTime;
  41905. this.isPlaying = true;
  41906. this.isPaused = false;
  41907. }
  41908. catch (ex) {
  41909. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  41910. }
  41911. }
  41912. };
  41913. Sound.prototype._onended = function () {
  41914. this.isPlaying = false;
  41915. if (this.onended) {
  41916. this.onended();
  41917. }
  41918. };
  41919. /**
  41920. * Stop the sound
  41921. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  41922. */
  41923. Sound.prototype.stop = function (time) {
  41924. if (this.isPlaying) {
  41925. if (this._streaming) {
  41926. this._htmlAudioElement.pause();
  41927. // Test needed for Firefox or it will generate an Invalid State Error
  41928. if (this._htmlAudioElement.currentTime > 0) {
  41929. this._htmlAudioElement.currentTime = 0;
  41930. }
  41931. }
  41932. else {
  41933. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41934. this._soundSource.stop(stopTime);
  41935. this._soundSource.onended = null;
  41936. if (!this.isPaused) {
  41937. this._startOffset = 0;
  41938. }
  41939. }
  41940. this.isPlaying = false;
  41941. }
  41942. };
  41943. Sound.prototype.pause = function () {
  41944. if (this.isPlaying) {
  41945. this.isPaused = true;
  41946. if (this._streaming) {
  41947. this._htmlAudioElement.pause();
  41948. }
  41949. else {
  41950. this.stop(0);
  41951. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  41952. }
  41953. }
  41954. };
  41955. Sound.prototype.setVolume = function (newVolume, time) {
  41956. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41957. if (time) {
  41958. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  41959. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  41960. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  41961. }
  41962. else {
  41963. this._soundGain.gain.value = newVolume;
  41964. }
  41965. }
  41966. this._volume = newVolume;
  41967. };
  41968. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  41969. this._playbackRate = newPlaybackRate;
  41970. if (this.isPlaying) {
  41971. if (this._streaming) {
  41972. this._htmlAudioElement.playbackRate = this._playbackRate;
  41973. }
  41974. else {
  41975. this._soundSource.playbackRate.value = this._playbackRate;
  41976. }
  41977. }
  41978. };
  41979. Sound.prototype.getVolume = function () {
  41980. return this._volume;
  41981. };
  41982. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  41983. var _this = this;
  41984. if (this._connectedMesh) {
  41985. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41986. this._registerFunc = null;
  41987. }
  41988. this._connectedMesh = meshToConnectTo;
  41989. if (!this.spatialSound) {
  41990. this.spatialSound = true;
  41991. this._createSpatialParameters();
  41992. if (this.isPlaying && this.loop) {
  41993. this.stop();
  41994. this.play();
  41995. }
  41996. }
  41997. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  41998. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  41999. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42000. };
  42001. Sound.prototype.detachFromMesh = function () {
  42002. if (this._connectedMesh) {
  42003. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42004. this._registerFunc = null;
  42005. this._connectedMesh = null;
  42006. }
  42007. };
  42008. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42009. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42010. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42011. this._updateDirection();
  42012. }
  42013. };
  42014. Sound.prototype.clone = function () {
  42015. var _this = this;
  42016. if (!this._streaming) {
  42017. var setBufferAndRun = function () {
  42018. if (_this._isReadyToPlay) {
  42019. clonedSound._audioBuffer = _this.getAudioBuffer();
  42020. clonedSound._isReadyToPlay = true;
  42021. if (clonedSound.autoplay) {
  42022. clonedSound.play();
  42023. }
  42024. }
  42025. else {
  42026. window.setTimeout(setBufferAndRun, 300);
  42027. }
  42028. };
  42029. var currentOptions = {
  42030. autoplay: this.autoplay, loop: this.loop,
  42031. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  42032. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  42033. refDistance: this.refDistance, distanceModel: this.distanceModel
  42034. };
  42035. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  42036. if (this.useCustomAttenuation) {
  42037. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  42038. }
  42039. clonedSound.setPosition(this._position);
  42040. clonedSound.setPlaybackRate(this._playbackRate);
  42041. setBufferAndRun();
  42042. return clonedSound;
  42043. }
  42044. else {
  42045. return null;
  42046. }
  42047. };
  42048. Sound.prototype.getAudioBuffer = function () {
  42049. return this._audioBuffer;
  42050. };
  42051. Sound.prototype.serialize = function () {
  42052. var serializationObject = {
  42053. name: this.name,
  42054. url: this.name,
  42055. autoplay: this.autoplay,
  42056. loop: this.loop,
  42057. volume: this._volume,
  42058. spatialSound: this.spatialSound,
  42059. maxDistance: this.maxDistance,
  42060. rolloffFactor: this.rolloffFactor,
  42061. refDistance: this.refDistance,
  42062. distanceModel: this.distanceModel,
  42063. playbackRate: this._playbackRate,
  42064. panningModel: this._panningModel,
  42065. soundTrackId: this.soundTrackId
  42066. };
  42067. if (this.spatialSound) {
  42068. if (this._connectedMesh)
  42069. serializationObject.connectedMeshId = this._connectedMesh.id;
  42070. serializationObject.position = this._position.asArray();
  42071. serializationObject.refDistance = this.refDistance;
  42072. serializationObject.distanceModel = this.distanceModel;
  42073. serializationObject.isDirectional = this._isDirectional;
  42074. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  42075. serializationObject.coneInnerAngle = this._coneInnerAngle;
  42076. serializationObject.coneOuterAngle = this._coneOuterAngle;
  42077. serializationObject.coneOuterGain = this._coneOuterGain;
  42078. }
  42079. return serializationObject;
  42080. };
  42081. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  42082. var soundName = parsedSound.name;
  42083. var soundUrl;
  42084. if (parsedSound.url) {
  42085. soundUrl = rootUrl + parsedSound.url;
  42086. }
  42087. else {
  42088. soundUrl = rootUrl + soundName;
  42089. }
  42090. var options = {
  42091. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  42092. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  42093. rolloffFactor: parsedSound.rolloffFactor,
  42094. refDistance: parsedSound.refDistance,
  42095. distanceModel: parsedSound.distanceModel,
  42096. playbackRate: parsedSound.playbackRate
  42097. };
  42098. var newSound;
  42099. if (!sourceSound) {
  42100. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  42101. scene._addPendingData(newSound);
  42102. }
  42103. else {
  42104. var setBufferAndRun = function () {
  42105. if (sourceSound._isReadyToPlay) {
  42106. newSound._audioBuffer = sourceSound.getAudioBuffer();
  42107. newSound._isReadyToPlay = true;
  42108. if (newSound.autoplay) {
  42109. newSound.play();
  42110. }
  42111. }
  42112. else {
  42113. window.setTimeout(setBufferAndRun, 300);
  42114. }
  42115. };
  42116. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42117. setBufferAndRun();
  42118. }
  42119. if (parsedSound.position) {
  42120. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42121. newSound.setPosition(soundPosition);
  42122. }
  42123. if (parsedSound.isDirectional) {
  42124. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42125. if (parsedSound.localDirectionToMesh) {
  42126. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42127. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42128. }
  42129. }
  42130. if (parsedSound.connectedMeshId) {
  42131. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42132. if (connectedMesh) {
  42133. newSound.attachToMesh(connectedMesh);
  42134. }
  42135. }
  42136. return newSound;
  42137. };
  42138. return Sound;
  42139. }());
  42140. BABYLON.Sound = Sound;
  42141. })(BABYLON || (BABYLON = {}));
  42142. //# sourceMappingURL=babylon.sound.js.map
  42143. var BABYLON;
  42144. (function (BABYLON) {
  42145. var SoundTrack = (function () {
  42146. function SoundTrack(scene, options) {
  42147. this.id = -1;
  42148. this._isMainTrack = false;
  42149. this._isInitialized = false;
  42150. this._scene = scene;
  42151. this.soundCollection = new Array();
  42152. this._options = options;
  42153. if (!this._isMainTrack) {
  42154. this._scene.soundTracks.push(this);
  42155. this.id = this._scene.soundTracks.length - 1;
  42156. }
  42157. }
  42158. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42159. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42160. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42161. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42162. if (this._options) {
  42163. if (this._options.volume) {
  42164. this._outputAudioNode.gain.value = this._options.volume;
  42165. }
  42166. if (this._options.mainTrack) {
  42167. this._isMainTrack = this._options.mainTrack;
  42168. }
  42169. }
  42170. this._isInitialized = true;
  42171. }
  42172. };
  42173. SoundTrack.prototype.dispose = function () {
  42174. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42175. if (this._connectedAnalyser) {
  42176. this._connectedAnalyser.stopDebugCanvas();
  42177. }
  42178. while (this.soundCollection.length) {
  42179. this.soundCollection[0].dispose();
  42180. }
  42181. if (this._outputAudioNode) {
  42182. this._outputAudioNode.disconnect();
  42183. }
  42184. this._outputAudioNode = null;
  42185. }
  42186. };
  42187. SoundTrack.prototype.AddSound = function (sound) {
  42188. if (!this._isInitialized) {
  42189. this._initializeSoundTrackAudioGraph();
  42190. }
  42191. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42192. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42193. }
  42194. if (sound.soundTrackId) {
  42195. if (sound.soundTrackId === -1) {
  42196. this._scene.mainSoundTrack.RemoveSound(sound);
  42197. }
  42198. else {
  42199. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42200. }
  42201. }
  42202. this.soundCollection.push(sound);
  42203. sound.soundTrackId = this.id;
  42204. };
  42205. SoundTrack.prototype.RemoveSound = function (sound) {
  42206. var index = this.soundCollection.indexOf(sound);
  42207. if (index !== -1) {
  42208. this.soundCollection.splice(index, 1);
  42209. }
  42210. };
  42211. SoundTrack.prototype.setVolume = function (newVolume) {
  42212. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42213. this._outputAudioNode.gain.value = newVolume;
  42214. }
  42215. };
  42216. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42217. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42218. for (var i = 0; i < this.soundCollection.length; i++) {
  42219. this.soundCollection[i].switchPanningModelToHRTF();
  42220. }
  42221. }
  42222. };
  42223. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42224. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42225. for (var i = 0; i < this.soundCollection.length; i++) {
  42226. this.soundCollection[i].switchPanningModelToEqualPower();
  42227. }
  42228. }
  42229. };
  42230. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42231. if (this._connectedAnalyser) {
  42232. this._connectedAnalyser.stopDebugCanvas();
  42233. }
  42234. this._connectedAnalyser = analyser;
  42235. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42236. this._outputAudioNode.disconnect();
  42237. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42238. }
  42239. };
  42240. return SoundTrack;
  42241. }());
  42242. BABYLON.SoundTrack = SoundTrack;
  42243. })(BABYLON || (BABYLON = {}));
  42244. //# sourceMappingURL=babylon.soundtrack.js.map
  42245. var BABYLON;
  42246. (function (BABYLON) {
  42247. var Analyser = (function () {
  42248. function Analyser(scene) {
  42249. this.SMOOTHING = 0.75;
  42250. this.FFT_SIZE = 512;
  42251. this.BARGRAPHAMPLITUDE = 256;
  42252. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  42253. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  42254. this._scene = scene;
  42255. this._audioEngine = BABYLON.Engine.audioEngine;
  42256. if (this._audioEngine.canUseWebAudio) {
  42257. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  42258. this._webAudioAnalyser.minDecibels = -140;
  42259. this._webAudioAnalyser.maxDecibels = 0;
  42260. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42261. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42262. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  42263. }
  42264. }
  42265. Analyser.prototype.getFrequencyBinCount = function () {
  42266. if (this._audioEngine.canUseWebAudio) {
  42267. return this._webAudioAnalyser.frequencyBinCount;
  42268. }
  42269. else {
  42270. return 0;
  42271. }
  42272. };
  42273. Analyser.prototype.getByteFrequencyData = function () {
  42274. if (this._audioEngine.canUseWebAudio) {
  42275. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42276. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42277. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  42278. }
  42279. return this._byteFreqs;
  42280. };
  42281. Analyser.prototype.getByteTimeDomainData = function () {
  42282. if (this._audioEngine.canUseWebAudio) {
  42283. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42284. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42285. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  42286. }
  42287. return this._byteTime;
  42288. };
  42289. Analyser.prototype.getFloatFrequencyData = function () {
  42290. if (this._audioEngine.canUseWebAudio) {
  42291. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42292. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42293. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  42294. }
  42295. return this._floatFreqs;
  42296. };
  42297. Analyser.prototype.drawDebugCanvas = function () {
  42298. var _this = this;
  42299. if (this._audioEngine.canUseWebAudio) {
  42300. if (!this._debugCanvas) {
  42301. this._debugCanvas = document.createElement("canvas");
  42302. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  42303. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  42304. this._debugCanvas.style.position = "absolute";
  42305. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  42306. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  42307. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  42308. document.body.appendChild(this._debugCanvas);
  42309. this._registerFunc = function () {
  42310. _this.drawDebugCanvas();
  42311. };
  42312. this._scene.registerBeforeRender(this._registerFunc);
  42313. }
  42314. if (this._registerFunc) {
  42315. var workingArray = this.getByteFrequencyData();
  42316. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  42317. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  42318. // Draw the frequency domain chart.
  42319. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  42320. var value = workingArray[i];
  42321. var percent = value / this.BARGRAPHAMPLITUDE;
  42322. var height = this.DEBUGCANVASSIZE.height * percent;
  42323. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  42324. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  42325. var hue = i / this.getFrequencyBinCount() * 360;
  42326. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  42327. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  42328. }
  42329. }
  42330. }
  42331. };
  42332. Analyser.prototype.stopDebugCanvas = function () {
  42333. if (this._debugCanvas) {
  42334. this._scene.unregisterBeforeRender(this._registerFunc);
  42335. this._registerFunc = null;
  42336. document.body.removeChild(this._debugCanvas);
  42337. this._debugCanvas = null;
  42338. this._debugCanvasContext = null;
  42339. }
  42340. };
  42341. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  42342. if (this._audioEngine.canUseWebAudio) {
  42343. inputAudioNode.connect(this._webAudioAnalyser);
  42344. this._webAudioAnalyser.connect(outputAudioNode);
  42345. }
  42346. };
  42347. Analyser.prototype.dispose = function () {
  42348. if (this._audioEngine.canUseWebAudio) {
  42349. this._webAudioAnalyser.disconnect();
  42350. }
  42351. };
  42352. return Analyser;
  42353. }());
  42354. BABYLON.Analyser = Analyser;
  42355. })(BABYLON || (BABYLON = {}));
  42356. //# sourceMappingURL=babylon.analyser.js.map
  42357. var BABYLON;
  42358. (function (BABYLON) {
  42359. var CubeTexture = (function (_super) {
  42360. __extends(CubeTexture, _super);
  42361. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  42362. if (onLoad === void 0) { onLoad = null; }
  42363. if (onError === void 0) { onError = null; }
  42364. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42365. var _this = _super.call(this, scene) || this;
  42366. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42367. _this.name = rootUrl;
  42368. _this.url = rootUrl;
  42369. _this._noMipmap = noMipmap;
  42370. _this.hasAlpha = false;
  42371. _this._format = format;
  42372. if (!rootUrl && !files) {
  42373. return _this;
  42374. }
  42375. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  42376. if (!files) {
  42377. if (!extensions) {
  42378. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  42379. }
  42380. files = [];
  42381. for (var index = 0; index < extensions.length; index++) {
  42382. files.push(rootUrl + extensions[index]);
  42383. }
  42384. _this._extensions = extensions;
  42385. }
  42386. _this._files = files;
  42387. if (!_this._texture) {
  42388. if (!scene.useDelayedTextureLoading) {
  42389. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  42390. }
  42391. else {
  42392. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42393. }
  42394. }
  42395. else if (onLoad) {
  42396. if (_this._texture.isReady) {
  42397. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  42398. }
  42399. else {
  42400. _this._texture.onLoadedCallbacks.push(onLoad);
  42401. }
  42402. }
  42403. _this.isCube = true;
  42404. _this._textureMatrix = BABYLON.Matrix.Identity();
  42405. return _this;
  42406. }
  42407. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  42408. return new CubeTexture("", scene, null, noMipmap, files);
  42409. };
  42410. // Methods
  42411. CubeTexture.prototype.delayLoad = function () {
  42412. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42413. return;
  42414. }
  42415. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42416. this._texture = this._getFromCache(this.url, this._noMipmap);
  42417. if (!this._texture) {
  42418. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  42419. }
  42420. };
  42421. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  42422. return this._textureMatrix;
  42423. };
  42424. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42425. var texture = BABYLON.SerializationHelper.Parse(function () {
  42426. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  42427. }, parsedTexture, scene);
  42428. // Animations
  42429. if (parsedTexture.animations) {
  42430. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  42431. var parsedAnimation = parsedTexture.animations[animationIndex];
  42432. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  42433. }
  42434. }
  42435. return texture;
  42436. };
  42437. CubeTexture.prototype.clone = function () {
  42438. var _this = this;
  42439. return BABYLON.SerializationHelper.Clone(function () {
  42440. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  42441. }, this);
  42442. };
  42443. return CubeTexture;
  42444. }(BABYLON.BaseTexture));
  42445. BABYLON.CubeTexture = CubeTexture;
  42446. })(BABYLON || (BABYLON = {}));
  42447. //# sourceMappingURL=babylon.cubeTexture.js.map
  42448. var BABYLON;
  42449. (function (BABYLON) {
  42450. var RenderTargetTexture = (function (_super) {
  42451. __extends(RenderTargetTexture, _super);
  42452. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  42453. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  42454. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42455. if (isCube === void 0) { isCube = false; }
  42456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42457. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  42458. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  42459. if (isMulti === void 0) { isMulti = false; }
  42460. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  42461. _this.isCube = isCube;
  42462. /**
  42463. * Use this list to define the list of mesh you want to render.
  42464. */
  42465. _this.renderList = new Array();
  42466. _this.renderParticles = true;
  42467. _this.renderSprites = false;
  42468. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  42469. // Events
  42470. /**
  42471. * An event triggered when the texture is unbind.
  42472. * @type {BABYLON.Observable}
  42473. */
  42474. _this.onAfterUnbindObservable = new BABYLON.Observable();
  42475. /**
  42476. * An event triggered before rendering the texture
  42477. * @type {BABYLON.Observable}
  42478. */
  42479. _this.onBeforeRenderObservable = new BABYLON.Observable();
  42480. /**
  42481. * An event triggered after rendering the texture
  42482. * @type {BABYLON.Observable}
  42483. */
  42484. _this.onAfterRenderObservable = new BABYLON.Observable();
  42485. /**
  42486. * An event triggered after the texture clear
  42487. * @type {BABYLON.Observable}
  42488. */
  42489. _this.onClearObservable = new BABYLON.Observable();
  42490. _this._currentRefreshId = -1;
  42491. _this._refreshRate = 1;
  42492. _this._samples = 1;
  42493. _this.name = name;
  42494. _this.isRenderTarget = true;
  42495. _this._size = size;
  42496. _this._generateMipMaps = generateMipMaps;
  42497. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  42498. // Rendering groups
  42499. _this._renderingManager = new BABYLON.RenderingManager(scene);
  42500. if (isMulti) {
  42501. return _this;
  42502. }
  42503. _this._renderTargetOptions = {
  42504. generateMipMaps: generateMipMaps,
  42505. type: type,
  42506. samplingMode: samplingMode,
  42507. generateDepthBuffer: generateDepthBuffer,
  42508. generateStencilBuffer: generateStencilBuffer
  42509. };
  42510. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  42511. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42512. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42513. }
  42514. if (isCube) {
  42515. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  42516. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  42517. _this._textureMatrix = BABYLON.Matrix.Identity();
  42518. }
  42519. else {
  42520. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  42521. }
  42522. return _this;
  42523. }
  42524. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  42525. get: function () {
  42526. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  42527. },
  42528. enumerable: true,
  42529. configurable: true
  42530. });
  42531. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  42532. get: function () {
  42533. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  42534. },
  42535. enumerable: true,
  42536. configurable: true
  42537. });
  42538. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  42539. get: function () {
  42540. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  42541. },
  42542. enumerable: true,
  42543. configurable: true
  42544. });
  42545. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  42546. set: function (callback) {
  42547. if (this._onAfterUnbindObserver) {
  42548. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  42549. }
  42550. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  42551. },
  42552. enumerable: true,
  42553. configurable: true
  42554. });
  42555. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  42556. set: function (callback) {
  42557. if (this._onBeforeRenderObserver) {
  42558. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  42559. }
  42560. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  42561. },
  42562. enumerable: true,
  42563. configurable: true
  42564. });
  42565. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  42566. set: function (callback) {
  42567. if (this._onAfterRenderObserver) {
  42568. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  42569. }
  42570. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  42571. },
  42572. enumerable: true,
  42573. configurable: true
  42574. });
  42575. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  42576. set: function (callback) {
  42577. if (this._onClearObserver) {
  42578. this.onClearObservable.remove(this._onClearObserver);
  42579. }
  42580. this._onClearObserver = this.onClearObservable.add(callback);
  42581. },
  42582. enumerable: true,
  42583. configurable: true
  42584. });
  42585. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  42586. get: function () {
  42587. return this._renderTargetOptions;
  42588. },
  42589. enumerable: true,
  42590. configurable: true
  42591. });
  42592. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  42593. get: function () {
  42594. return this._samples;
  42595. },
  42596. set: function (value) {
  42597. if (this._samples === value) {
  42598. return;
  42599. }
  42600. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  42601. },
  42602. enumerable: true,
  42603. configurable: true
  42604. });
  42605. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  42606. this._currentRefreshId = -1;
  42607. };
  42608. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  42609. get: function () {
  42610. return this._refreshRate;
  42611. },
  42612. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  42613. set: function (value) {
  42614. this._refreshRate = value;
  42615. this.resetRefreshCounter();
  42616. },
  42617. enumerable: true,
  42618. configurable: true
  42619. });
  42620. RenderTargetTexture.prototype._shouldRender = function () {
  42621. if (this._currentRefreshId === -1) {
  42622. this._currentRefreshId = 1;
  42623. return true;
  42624. }
  42625. if (this.refreshRate === this._currentRefreshId) {
  42626. this._currentRefreshId = 1;
  42627. return true;
  42628. }
  42629. this._currentRefreshId++;
  42630. return false;
  42631. };
  42632. RenderTargetTexture.prototype.isReady = function () {
  42633. if (!this.getScene().renderTargetsEnabled) {
  42634. return false;
  42635. }
  42636. return _super.prototype.isReady.call(this);
  42637. };
  42638. RenderTargetTexture.prototype.getRenderSize = function () {
  42639. return this._size;
  42640. };
  42641. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  42642. get: function () {
  42643. return true;
  42644. },
  42645. enumerable: true,
  42646. configurable: true
  42647. });
  42648. RenderTargetTexture.prototype.scale = function (ratio) {
  42649. var newSize = this._size * ratio;
  42650. this.resize(newSize);
  42651. };
  42652. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  42653. if (this.isCube) {
  42654. return this._textureMatrix;
  42655. }
  42656. return _super.prototype.getReflectionTextureMatrix.call(this);
  42657. };
  42658. RenderTargetTexture.prototype.resize = function (size) {
  42659. this.releaseInternalTexture();
  42660. if (this.isCube) {
  42661. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  42662. }
  42663. else {
  42664. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  42665. }
  42666. };
  42667. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  42668. var scene = this.getScene();
  42669. var engine = scene.getEngine();
  42670. if (this.useCameraPostProcesses !== undefined) {
  42671. useCameraPostProcess = this.useCameraPostProcesses;
  42672. }
  42673. if (this._waitingRenderList) {
  42674. this.renderList = [];
  42675. for (var index = 0; index < this._waitingRenderList.length; index++) {
  42676. var id = this._waitingRenderList[index];
  42677. this.renderList.push(scene.getMeshByID(id));
  42678. }
  42679. delete this._waitingRenderList;
  42680. }
  42681. // Is predicate defined?
  42682. if (this.renderListPredicate) {
  42683. this.renderList.splice(0); // Clear previous renderList
  42684. var sceneMeshes = this.getScene().meshes;
  42685. for (var index = 0; index < sceneMeshes.length; index++) {
  42686. var mesh = sceneMeshes[index];
  42687. if (this.renderListPredicate(mesh)) {
  42688. this.renderList.push(mesh);
  42689. }
  42690. }
  42691. }
  42692. if (this.renderList && this.renderList.length === 0) {
  42693. return;
  42694. }
  42695. // Set custom projection.
  42696. // Needs to be before binding to prevent changing the aspect ratio.
  42697. if (this.activeCamera) {
  42698. engine.setViewport(this.activeCamera.viewport);
  42699. if (this.activeCamera !== scene.activeCamera) {
  42700. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  42701. }
  42702. }
  42703. else {
  42704. engine.setViewport(scene.activeCamera.viewport);
  42705. }
  42706. // Prepare renderingManager
  42707. this._renderingManager.reset();
  42708. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  42709. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  42710. var sceneRenderId = scene.getRenderId();
  42711. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  42712. var mesh = currentRenderList[meshIndex];
  42713. if (mesh) {
  42714. if (!mesh.isReady()) {
  42715. // Reset _currentRefreshId
  42716. this.resetRefreshCounter();
  42717. continue;
  42718. }
  42719. mesh._preActivateForIntermediateRendering(sceneRenderId);
  42720. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  42721. mesh._activate(sceneRenderId);
  42722. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42723. var subMesh = mesh.subMeshes[subIndex];
  42724. scene._activeIndices.addCount(subMesh.indexCount, false);
  42725. this._renderingManager.dispatch(subMesh);
  42726. }
  42727. }
  42728. }
  42729. }
  42730. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  42731. var particleSystem = scene.particleSystems[particleIndex];
  42732. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  42733. continue;
  42734. }
  42735. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  42736. this._renderingManager.dispatchParticles(particleSystem);
  42737. }
  42738. }
  42739. if (this.isCube) {
  42740. for (var face = 0; face < 6; face++) {
  42741. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42742. scene.incrementRenderId();
  42743. scene.resetCachedMaterial();
  42744. }
  42745. }
  42746. else {
  42747. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42748. }
  42749. this.onAfterUnbindObservable.notifyObservers(this);
  42750. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  42751. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  42752. }
  42753. engine.setViewport(scene.activeCamera.viewport);
  42754. scene.resetCachedMaterial();
  42755. };
  42756. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  42757. var _this = this;
  42758. var scene = this.getScene();
  42759. var engine = scene.getEngine();
  42760. // Bind
  42761. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  42762. if (this.isCube) {
  42763. engine.bindFramebuffer(this._texture, faceIndex);
  42764. }
  42765. else {
  42766. engine.bindFramebuffer(this._texture);
  42767. }
  42768. }
  42769. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  42770. // Clear
  42771. if (this.onClearObservable.hasObservers()) {
  42772. this.onClearObservable.notifyObservers(engine);
  42773. }
  42774. else {
  42775. engine.clear(scene.clearColor, true, true, true);
  42776. }
  42777. if (!this._doNotChangeAspectRatio) {
  42778. scene.updateTransformMatrix(true);
  42779. }
  42780. // Render
  42781. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  42782. if (useCameraPostProcess) {
  42783. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  42784. }
  42785. if (!this._doNotChangeAspectRatio) {
  42786. scene.updateTransformMatrix(true);
  42787. }
  42788. // Dump ?
  42789. if (dumpForDebug) {
  42790. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  42791. }
  42792. // Unbind
  42793. if (!this.isCube || faceIndex === 5) {
  42794. if (this.isCube) {
  42795. if (faceIndex === 5) {
  42796. engine.generateMipMapsForCubemap(this._texture);
  42797. }
  42798. }
  42799. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  42800. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  42801. });
  42802. }
  42803. else {
  42804. this.onAfterRenderObservable.notifyObservers(faceIndex);
  42805. }
  42806. };
  42807. /**
  42808. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  42809. * This allowed control for front to back rendering or reversly depending of the special needs.
  42810. *
  42811. * @param renderingGroupId The rendering group id corresponding to its index
  42812. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  42813. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  42814. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  42815. */
  42816. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  42817. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  42818. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  42819. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  42820. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  42821. };
  42822. /**
  42823. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  42824. *
  42825. * @param renderingGroupId The rendering group id corresponding to its index
  42826. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  42827. */
  42828. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  42829. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  42830. };
  42831. RenderTargetTexture.prototype.clone = function () {
  42832. var textureSize = this.getSize();
  42833. 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);
  42834. // Base texture
  42835. newTexture.hasAlpha = this.hasAlpha;
  42836. newTexture.level = this.level;
  42837. // RenderTarget Texture
  42838. newTexture.coordinatesMode = this.coordinatesMode;
  42839. newTexture.renderList = this.renderList.slice(0);
  42840. return newTexture;
  42841. };
  42842. RenderTargetTexture.prototype.serialize = function () {
  42843. if (!this.name) {
  42844. return null;
  42845. }
  42846. var serializationObject = _super.prototype.serialize.call(this);
  42847. serializationObject.renderTargetSize = this.getRenderSize();
  42848. serializationObject.renderList = [];
  42849. for (var index = 0; index < this.renderList.length; index++) {
  42850. serializationObject.renderList.push(this.renderList[index].id);
  42851. }
  42852. return serializationObject;
  42853. };
  42854. RenderTargetTexture.prototype.dispose = function () {
  42855. _super.prototype.dispose.call(this);
  42856. };
  42857. return RenderTargetTexture;
  42858. }(BABYLON.Texture));
  42859. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  42860. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  42861. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  42862. BABYLON.RenderTargetTexture = RenderTargetTexture;
  42863. })(BABYLON || (BABYLON = {}));
  42864. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  42865. var BABYLON;
  42866. (function (BABYLON) {
  42867. ;
  42868. var MultiRenderTarget = (function (_super) {
  42869. __extends(MultiRenderTarget, _super);
  42870. function MultiRenderTarget(name, size, count, scene, options) {
  42871. var _this = this;
  42872. options = options || {};
  42873. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  42874. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  42875. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  42876. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  42877. if (!_this.isSupported) {
  42878. _this.dispose();
  42879. return;
  42880. }
  42881. var types = [];
  42882. var samplingModes = [];
  42883. for (var i = 0; i < count; i++) {
  42884. if (options.types && options.types[i]) {
  42885. types.push(options.types[i]);
  42886. }
  42887. else {
  42888. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  42889. }
  42890. if (options.samplingModes && options.samplingModes[i]) {
  42891. samplingModes.push(options.samplingModes[i]);
  42892. }
  42893. else {
  42894. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42895. }
  42896. }
  42897. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  42898. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  42899. _this._count = count;
  42900. _this._size = size;
  42901. _this._multiRenderTargetOptions = {
  42902. samplingModes: samplingModes,
  42903. generateMipMaps: generateMipMaps,
  42904. generateDepthBuffer: generateDepthBuffer,
  42905. generateStencilBuffer: generateStencilBuffer,
  42906. generateDepthTexture: generateDepthTexture,
  42907. types: types,
  42908. textureCount: count
  42909. };
  42910. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  42911. _this._createInternalTextures();
  42912. return _this;
  42913. }
  42914. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  42915. get: function () {
  42916. var engine = this.getScene().getEngine();
  42917. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  42918. },
  42919. enumerable: true,
  42920. configurable: true
  42921. });
  42922. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  42923. get: function () {
  42924. return this._textures;
  42925. },
  42926. enumerable: true,
  42927. configurable: true
  42928. });
  42929. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  42930. get: function () {
  42931. return this._textures[this._textures.length - 1];
  42932. },
  42933. enumerable: true,
  42934. configurable: true
  42935. });
  42936. MultiRenderTarget.prototype._createInternalTextures = function () {
  42937. this._textures = [];
  42938. for (var i = 0; i < this._webGLTextures.length; i++) {
  42939. var texture = new BABYLON.Texture(null, this.getScene());
  42940. texture._texture = this._webGLTextures[i];
  42941. this._textures.push(texture);
  42942. }
  42943. // Keeps references to frame buffer and stencil/depth buffer
  42944. this._texture = this._webGLTextures[0];
  42945. };
  42946. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  42947. get: function () {
  42948. return this._samples;
  42949. },
  42950. set: function (value) {
  42951. if (this._samples === value) {
  42952. return;
  42953. }
  42954. for (var i = 0; i < this._webGLTextures.length; i++) {
  42955. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  42956. }
  42957. },
  42958. enumerable: true,
  42959. configurable: true
  42960. });
  42961. MultiRenderTarget.prototype.resize = function (size) {
  42962. this.releaseInternalTextures();
  42963. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  42964. this._createInternalTextures();
  42965. };
  42966. MultiRenderTarget.prototype.dispose = function () {
  42967. this.releaseInternalTextures();
  42968. _super.prototype.dispose.call(this);
  42969. };
  42970. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  42971. if (!this._webGLTextures) {
  42972. return;
  42973. }
  42974. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  42975. if (this._webGLTextures[i] !== undefined) {
  42976. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  42977. this._webGLTextures.splice(i, 1);
  42978. }
  42979. }
  42980. };
  42981. return MultiRenderTarget;
  42982. }(BABYLON.RenderTargetTexture));
  42983. BABYLON.MultiRenderTarget = MultiRenderTarget;
  42984. })(BABYLON || (BABYLON = {}));
  42985. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  42986. /// <reference path="babylon.renderTargetTexture.ts" />
  42987. var BABYLON;
  42988. (function (BABYLON) {
  42989. var MirrorTexture = (function (_super) {
  42990. __extends(MirrorTexture, _super);
  42991. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  42992. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  42994. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  42995. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  42996. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  42997. _this._transformMatrix = BABYLON.Matrix.Zero();
  42998. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  42999. _this.onBeforeRenderObservable.add(function () {
  43000. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  43001. _this._savedViewMatrix = scene.getViewMatrix();
  43002. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  43003. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  43004. scene.clipPlane = _this.mirrorPlane;
  43005. scene.getEngine().cullBackFaces = false;
  43006. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  43007. });
  43008. _this.onAfterRenderObservable.add(function () {
  43009. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  43010. scene.getEngine().cullBackFaces = true;
  43011. scene._mirroredCameraPosition = null;
  43012. delete scene.clipPlane;
  43013. });
  43014. return _this;
  43015. }
  43016. MirrorTexture.prototype.clone = function () {
  43017. var textureSize = this.getSize();
  43018. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  43019. // Base texture
  43020. newTexture.hasAlpha = this.hasAlpha;
  43021. newTexture.level = this.level;
  43022. // Mirror Texture
  43023. newTexture.mirrorPlane = this.mirrorPlane.clone();
  43024. newTexture.renderList = this.renderList.slice(0);
  43025. return newTexture;
  43026. };
  43027. MirrorTexture.prototype.serialize = function () {
  43028. if (!this.name) {
  43029. return null;
  43030. }
  43031. var serializationObject = _super.prototype.serialize.call(this);
  43032. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  43033. return serializationObject;
  43034. };
  43035. return MirrorTexture;
  43036. }(BABYLON.RenderTargetTexture));
  43037. BABYLON.MirrorTexture = MirrorTexture;
  43038. })(BABYLON || (BABYLON = {}));
  43039. //# sourceMappingURL=babylon.mirrorTexture.js.map
  43040. /// <reference path="babylon.renderTargetTexture.ts" />
  43041. var BABYLON;
  43042. (function (BABYLON) {
  43043. /**
  43044. * Creates a refraction texture used by refraction channel of the standard material.
  43045. * @param name the texture name
  43046. * @param size size of the underlying texture
  43047. * @param scene root scene
  43048. */
  43049. var RefractionTexture = (function (_super) {
  43050. __extends(RefractionTexture, _super);
  43051. function RefractionTexture(name, size, scene, generateMipMaps) {
  43052. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  43053. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  43054. _this.depth = 2.0;
  43055. _this.onBeforeRenderObservable.add(function () {
  43056. scene.clipPlane = _this.refractionPlane;
  43057. });
  43058. _this.onAfterRenderObservable.add(function () {
  43059. delete scene.clipPlane;
  43060. });
  43061. return _this;
  43062. }
  43063. RefractionTexture.prototype.clone = function () {
  43064. var textureSize = this.getSize();
  43065. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  43066. // Base texture
  43067. newTexture.hasAlpha = this.hasAlpha;
  43068. newTexture.level = this.level;
  43069. // Refraction Texture
  43070. newTexture.refractionPlane = this.refractionPlane.clone();
  43071. newTexture.renderList = this.renderList.slice(0);
  43072. newTexture.depth = this.depth;
  43073. return newTexture;
  43074. };
  43075. RefractionTexture.prototype.serialize = function () {
  43076. if (!this.name) {
  43077. return null;
  43078. }
  43079. var serializationObject = _super.prototype.serialize.call(this);
  43080. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  43081. serializationObject.depth = this.depth;
  43082. return serializationObject;
  43083. };
  43084. return RefractionTexture;
  43085. }(BABYLON.RenderTargetTexture));
  43086. BABYLON.RefractionTexture = RefractionTexture;
  43087. })(BABYLON || (BABYLON = {}));
  43088. //# sourceMappingURL=babylon.refractionTexture.js.map
  43089. /// <reference path="babylon.texture.ts" />
  43090. var BABYLON;
  43091. (function (BABYLON) {
  43092. var DynamicTexture = (function (_super) {
  43093. __extends(DynamicTexture, _super);
  43094. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  43095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43096. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  43097. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  43098. _this.name = name;
  43099. var engine = _this.getScene().getEngine();
  43100. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43101. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43102. _this._generateMipMaps = generateMipMaps;
  43103. if (options.getContext) {
  43104. _this._canvas = options;
  43105. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43106. }
  43107. else {
  43108. _this._canvas = document.createElement("canvas");
  43109. if (options.width) {
  43110. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43111. }
  43112. else {
  43113. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  43114. }
  43115. }
  43116. var textureSize = _this.getSize();
  43117. _this._canvas.width = textureSize.width;
  43118. _this._canvas.height = textureSize.height;
  43119. _this._context = _this._canvas.getContext("2d");
  43120. return _this;
  43121. }
  43122. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  43123. get: function () {
  43124. return true;
  43125. },
  43126. enumerable: true,
  43127. configurable: true
  43128. });
  43129. DynamicTexture.prototype._recreate = function (textureSize) {
  43130. this._canvas.width = textureSize.width;
  43131. this._canvas.height = textureSize.height;
  43132. this.releaseInternalTexture();
  43133. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  43134. };
  43135. DynamicTexture.prototype.scale = function (ratio) {
  43136. var textureSize = this.getSize();
  43137. textureSize.width *= ratio;
  43138. textureSize.height *= ratio;
  43139. this._recreate(textureSize);
  43140. };
  43141. DynamicTexture.prototype.scaleTo = function (width, height) {
  43142. var textureSize = this.getSize();
  43143. textureSize.width = width;
  43144. textureSize.height = height;
  43145. this._recreate(textureSize);
  43146. };
  43147. DynamicTexture.prototype.getContext = function () {
  43148. return this._context;
  43149. };
  43150. DynamicTexture.prototype.clear = function () {
  43151. var size = this.getSize();
  43152. this._context.fillRect(0, 0, size.width, size.height);
  43153. };
  43154. DynamicTexture.prototype.update = function (invertY) {
  43155. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  43156. };
  43157. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  43158. if (update === void 0) { update = true; }
  43159. var size = this.getSize();
  43160. if (clearColor) {
  43161. this._context.fillStyle = clearColor;
  43162. this._context.fillRect(0, 0, size.width, size.height);
  43163. }
  43164. this._context.font = font;
  43165. if (x === null || x === undefined) {
  43166. var textSize = this._context.measureText(text);
  43167. x = (size.width - textSize.width) / 2;
  43168. }
  43169. if (y === null || y === undefined) {
  43170. var fontSize = parseInt((font.replace(/\D/g, '')));
  43171. ;
  43172. y = (size.height / 2) + (fontSize / 3.65);
  43173. }
  43174. this._context.fillStyle = color;
  43175. this._context.fillText(text, x, y);
  43176. if (update) {
  43177. this.update(invertY);
  43178. }
  43179. };
  43180. DynamicTexture.prototype.clone = function () {
  43181. var textureSize = this.getSize();
  43182. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  43183. // Base texture
  43184. newTexture.hasAlpha = this.hasAlpha;
  43185. newTexture.level = this.level;
  43186. // Dynamic Texture
  43187. newTexture.wrapU = this.wrapU;
  43188. newTexture.wrapV = this.wrapV;
  43189. return newTexture;
  43190. };
  43191. return DynamicTexture;
  43192. }(BABYLON.Texture));
  43193. BABYLON.DynamicTexture = DynamicTexture;
  43194. })(BABYLON || (BABYLON = {}));
  43195. //# sourceMappingURL=babylon.dynamicTexture.js.map
  43196. var BABYLON;
  43197. (function (BABYLON) {
  43198. var VideoTexture = (function (_super) {
  43199. __extends(VideoTexture, _super);
  43200. /**
  43201. * Creates a video texture.
  43202. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  43203. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  43204. * @param {BABYLON.Scene} scene is obviously the current scene.
  43205. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  43206. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  43207. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  43208. */
  43209. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  43210. if (generateMipMaps === void 0) { generateMipMaps = false; }
  43211. if (invertY === void 0) { invertY = false; }
  43212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43213. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43214. _this._autoLaunch = true;
  43215. var urls;
  43216. _this.name = name;
  43217. if (urlsOrVideo instanceof HTMLVideoElement) {
  43218. _this.video = urlsOrVideo;
  43219. }
  43220. else {
  43221. urls = urlsOrVideo;
  43222. _this.video = document.createElement("video");
  43223. _this.video.autoplay = false;
  43224. _this.video.loop = true;
  43225. }
  43226. _this._generateMipMaps = generateMipMaps;
  43227. _this._samplingMode = samplingMode;
  43228. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  43229. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  43230. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  43231. }
  43232. else {
  43233. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43234. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43235. _this._generateMipMaps = false;
  43236. }
  43237. if (urls) {
  43238. _this.video.addEventListener("canplay", function () {
  43239. _this._createTexture();
  43240. });
  43241. urls.forEach(function (url) {
  43242. var source = document.createElement("source");
  43243. source.src = url;
  43244. _this.video.appendChild(source);
  43245. });
  43246. }
  43247. else {
  43248. _this._createTexture();
  43249. }
  43250. _this._lastUpdate = BABYLON.Tools.Now;
  43251. return _this;
  43252. }
  43253. VideoTexture.prototype.__setTextureReady = function () {
  43254. this._texture.isReady = true;
  43255. };
  43256. VideoTexture.prototype._createTexture = function () {
  43257. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  43258. if (this._autoLaunch) {
  43259. this._autoLaunch = false;
  43260. this.video.play();
  43261. }
  43262. this._setTextureReady = this.__setTextureReady.bind(this);
  43263. this.video.addEventListener("playing", this._setTextureReady);
  43264. };
  43265. VideoTexture.prototype.update = function () {
  43266. var now = BABYLON.Tools.Now;
  43267. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  43268. return false;
  43269. }
  43270. this._lastUpdate = now;
  43271. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  43272. return true;
  43273. };
  43274. VideoTexture.prototype.dispose = function () {
  43275. _super.prototype.dispose.call(this);
  43276. this.video.removeEventListener("playing", this._setTextureReady);
  43277. };
  43278. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  43279. var video = document.createElement("video");
  43280. var constraintsDeviceId;
  43281. if (constraints && constraints.deviceId) {
  43282. constraintsDeviceId = {
  43283. exact: constraints.deviceId
  43284. };
  43285. }
  43286. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  43287. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  43288. if (navigator.getUserMedia) {
  43289. navigator.getUserMedia({
  43290. video: {
  43291. deviceId: constraintsDeviceId,
  43292. width: {
  43293. min: (constraints && constraints.minWidth) || 256,
  43294. max: (constraints && constraints.maxWidth) || 640
  43295. },
  43296. height: {
  43297. min: (constraints && constraints.minHeight) || 256,
  43298. max: (constraints && constraints.maxHeight) || 480
  43299. }
  43300. }
  43301. }, function (stream) {
  43302. if (video.mozSrcObject !== undefined) {
  43303. video.mozSrcObject = stream;
  43304. }
  43305. else {
  43306. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  43307. }
  43308. video.play();
  43309. if (onReady) {
  43310. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  43311. }
  43312. }, function (e) {
  43313. BABYLON.Tools.Error(e.name);
  43314. });
  43315. }
  43316. };
  43317. return VideoTexture;
  43318. }(BABYLON.Texture));
  43319. BABYLON.VideoTexture = VideoTexture;
  43320. })(BABYLON || (BABYLON = {}));
  43321. //# sourceMappingURL=babylon.videoTexture.js.map
  43322. var BABYLON;
  43323. (function (BABYLON) {
  43324. var RawTexture = (function (_super) {
  43325. __extends(RawTexture, _super);
  43326. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43327. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43328. if (invertY === void 0) { invertY = false; }
  43329. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43330. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43331. _this.format = format;
  43332. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43333. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43334. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43335. return _this;
  43336. }
  43337. RawTexture.prototype.update = function (data) {
  43338. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43339. };
  43340. // Statics
  43341. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43342. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43343. if (invertY === void 0) { invertY = false; }
  43344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43345. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43346. };
  43347. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43348. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43349. if (invertY === void 0) { invertY = false; }
  43350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43351. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43352. };
  43353. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43354. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43355. if (invertY === void 0) { invertY = false; }
  43356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43357. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43358. };
  43359. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43360. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43361. if (invertY === void 0) { invertY = false; }
  43362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43363. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43364. };
  43365. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43367. if (invertY === void 0) { invertY = false; }
  43368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43369. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43370. };
  43371. return RawTexture;
  43372. }(BABYLON.Texture));
  43373. BABYLON.RawTexture = RawTexture;
  43374. })(BABYLON || (BABYLON = {}));
  43375. //# sourceMappingURL=babylon.rawTexture.js.map
  43376. var BABYLON;
  43377. (function (BABYLON) {
  43378. var PostProcess = (function () {
  43379. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  43380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  43381. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43382. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  43383. if (blockCompilation === void 0) { blockCompilation = false; }
  43384. this.name = name;
  43385. this.width = -1;
  43386. this.height = -1;
  43387. this.autoClear = true;
  43388. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  43389. /*
  43390. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  43391. Can only be used on a single postprocess or on the last one of a chain.
  43392. */
  43393. this.enablePixelPerfectMode = false;
  43394. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  43395. this.alwaysForcePOT = false;
  43396. this.samples = 1;
  43397. this._reusable = false;
  43398. this._textures = new BABYLON.SmartArray(2);
  43399. this._currentRenderTextureInd = 0;
  43400. this._scaleRatio = new BABYLON.Vector2(1, 1);
  43401. this._texelSize = BABYLON.Vector2.Zero();
  43402. // Events
  43403. /**
  43404. * An event triggered when the postprocess is activated.
  43405. * @type {BABYLON.Observable}
  43406. */
  43407. this.onActivateObservable = new BABYLON.Observable();
  43408. /**
  43409. * An event triggered when the postprocess changes its size.
  43410. * @type {BABYLON.Observable}
  43411. */
  43412. this.onSizeChangedObservable = new BABYLON.Observable();
  43413. /**
  43414. * An event triggered when the postprocess applies its effect.
  43415. * @type {BABYLON.Observable}
  43416. */
  43417. this.onApplyObservable = new BABYLON.Observable();
  43418. /**
  43419. * An event triggered before rendering the postprocess
  43420. * @type {BABYLON.Observable}
  43421. */
  43422. this.onBeforeRenderObservable = new BABYLON.Observable();
  43423. /**
  43424. * An event triggered after rendering the postprocess
  43425. * @type {BABYLON.Observable}
  43426. */
  43427. this.onAfterRenderObservable = new BABYLON.Observable();
  43428. if (camera != null) {
  43429. this._camera = camera;
  43430. this._scene = camera.getScene();
  43431. camera.attachPostProcess(this);
  43432. this._engine = this._scene.getEngine();
  43433. }
  43434. else {
  43435. this._engine = engine;
  43436. }
  43437. this._options = options;
  43438. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  43439. this._reusable = reusable || false;
  43440. this._textureType = textureType;
  43441. this._samplers = samplers || [];
  43442. this._samplers.push("textureSampler");
  43443. this._fragmentUrl = fragmentUrl;
  43444. this._vertexUrl = vertexUrl;
  43445. this._parameters = parameters || [];
  43446. this._parameters.push("scale");
  43447. this._indexParameters = indexParameters;
  43448. if (!blockCompilation) {
  43449. this.updateEffect(defines);
  43450. }
  43451. }
  43452. Object.defineProperty(PostProcess.prototype, "onActivate", {
  43453. set: function (callback) {
  43454. if (this._onActivateObserver) {
  43455. this.onActivateObservable.remove(this._onActivateObserver);
  43456. }
  43457. this._onActivateObserver = this.onActivateObservable.add(callback);
  43458. },
  43459. enumerable: true,
  43460. configurable: true
  43461. });
  43462. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  43463. set: function (callback) {
  43464. if (this._onSizeChangedObserver) {
  43465. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  43466. }
  43467. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  43468. },
  43469. enumerable: true,
  43470. configurable: true
  43471. });
  43472. Object.defineProperty(PostProcess.prototype, "onApply", {
  43473. set: function (callback) {
  43474. if (this._onApplyObserver) {
  43475. this.onApplyObservable.remove(this._onApplyObserver);
  43476. }
  43477. this._onApplyObserver = this.onApplyObservable.add(callback);
  43478. },
  43479. enumerable: true,
  43480. configurable: true
  43481. });
  43482. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  43483. set: function (callback) {
  43484. if (this._onBeforeRenderObserver) {
  43485. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  43486. }
  43487. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  43488. },
  43489. enumerable: true,
  43490. configurable: true
  43491. });
  43492. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  43493. set: function (callback) {
  43494. if (this._onAfterRenderObserver) {
  43495. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  43496. }
  43497. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  43498. },
  43499. enumerable: true,
  43500. configurable: true
  43501. });
  43502. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  43503. get: function () {
  43504. return this._textures.data[this._currentRenderTextureInd];
  43505. },
  43506. enumerable: true,
  43507. configurable: true
  43508. });
  43509. PostProcess.prototype.getCamera = function () {
  43510. return this._camera;
  43511. };
  43512. Object.defineProperty(PostProcess.prototype, "texelSize", {
  43513. get: function () {
  43514. if (this._shareOutputWithPostProcess) {
  43515. return this._shareOutputWithPostProcess.texelSize;
  43516. }
  43517. return this._texelSize;
  43518. },
  43519. enumerable: true,
  43520. configurable: true
  43521. });
  43522. PostProcess.prototype.getEngine = function () {
  43523. return this._engine;
  43524. };
  43525. PostProcess.prototype.shareOutputWith = function (postProcess) {
  43526. this._disposeTextures();
  43527. this._shareOutputWithPostProcess = postProcess;
  43528. return this;
  43529. };
  43530. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  43531. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  43532. };
  43533. PostProcess.prototype.isReusable = function () {
  43534. return this._reusable;
  43535. };
  43536. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  43537. PostProcess.prototype.markTextureDirty = function () {
  43538. this.width = -1;
  43539. };
  43540. PostProcess.prototype.activate = function (camera, sourceTexture) {
  43541. var _this = this;
  43542. if (!this._shareOutputWithPostProcess) {
  43543. camera = camera || this._camera;
  43544. var scene = camera.getScene();
  43545. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  43546. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  43547. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  43548. var desiredWidth = this._options.width || requiredWidth;
  43549. var desiredHeight = this._options.height || requiredHeight;
  43550. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  43551. if (!this._options.width) {
  43552. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  43553. }
  43554. if (!this._options.height) {
  43555. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  43556. }
  43557. }
  43558. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  43559. if (this._textures.length > 0) {
  43560. for (var i = 0; i < this._textures.length; i++) {
  43561. this._engine._releaseTexture(this._textures.data[i]);
  43562. }
  43563. this._textures.reset();
  43564. }
  43565. this.width = desiredWidth;
  43566. this.height = desiredHeight;
  43567. var textureSize = { width: this.width, height: this.height };
  43568. var textureOptions = {
  43569. generateMipMaps: false,
  43570. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  43571. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  43572. samplingMode: this.renderTargetSamplingMode,
  43573. type: this._textureType
  43574. };
  43575. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43576. if (this._reusable) {
  43577. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43578. }
  43579. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  43580. this.onSizeChangedObservable.notifyObservers(this);
  43581. }
  43582. this._textures.forEach(function (texture) {
  43583. if (texture.samples !== _this.samples) {
  43584. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  43585. }
  43586. });
  43587. }
  43588. var target = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  43589. if (this.enablePixelPerfectMode) {
  43590. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  43591. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  43592. }
  43593. else {
  43594. this._scaleRatio.copyFromFloats(1, 1);
  43595. this._engine.bindFramebuffer(target);
  43596. }
  43597. this.onActivateObservable.notifyObservers(camera);
  43598. // Clear
  43599. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  43600. if (this.clearColor) {
  43601. this._engine.clear(this.clearColor, true, true, true);
  43602. }
  43603. else {
  43604. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  43605. }
  43606. }
  43607. if (this._reusable) {
  43608. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  43609. }
  43610. };
  43611. Object.defineProperty(PostProcess.prototype, "isSupported", {
  43612. get: function () {
  43613. return this._effect.isSupported;
  43614. },
  43615. enumerable: true,
  43616. configurable: true
  43617. });
  43618. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  43619. get: function () {
  43620. if (this._shareOutputWithPostProcess) {
  43621. return this._shareOutputWithPostProcess.aspectRatio;
  43622. }
  43623. return this.width / this.height;
  43624. },
  43625. enumerable: true,
  43626. configurable: true
  43627. });
  43628. PostProcess.prototype.apply = function () {
  43629. // Check
  43630. if (!this._effect || !this._effect.isReady())
  43631. return null;
  43632. // States
  43633. this._engine.enableEffect(this._effect);
  43634. this._engine.setState(false);
  43635. this._engine.setDepthBuffer(false);
  43636. this._engine.setDepthWrite(false);
  43637. // Alpha
  43638. this._engine.setAlphaMode(this.alphaMode);
  43639. if (this.alphaConstants) {
  43640. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  43641. }
  43642. // Texture
  43643. var source = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  43644. this._effect._bindTexture("textureSampler", source);
  43645. // Parameters
  43646. this._effect.setVector2("scale", this._scaleRatio);
  43647. this.onApplyObservable.notifyObservers(this._effect);
  43648. return this._effect;
  43649. };
  43650. PostProcess.prototype._disposeTextures = function () {
  43651. if (this._shareOutputWithPostProcess) {
  43652. return;
  43653. }
  43654. if (this._textures.length > 0) {
  43655. for (var i = 0; i < this._textures.length; i++) {
  43656. this._engine._releaseTexture(this._textures.data[i]);
  43657. }
  43658. }
  43659. this._textures.dispose();
  43660. };
  43661. PostProcess.prototype.dispose = function (camera) {
  43662. camera = camera || this._camera;
  43663. this._disposeTextures();
  43664. if (!camera) {
  43665. return;
  43666. }
  43667. camera.detachPostProcess(this);
  43668. var index = camera._postProcesses.indexOf(this);
  43669. if (index === 0 && camera._postProcesses.length > 0) {
  43670. this._camera._postProcesses[0].markTextureDirty();
  43671. }
  43672. this.onActivateObservable.clear();
  43673. this.onAfterRenderObservable.clear();
  43674. this.onApplyObservable.clear();
  43675. this.onBeforeRenderObservable.clear();
  43676. this.onSizeChangedObservable.clear();
  43677. };
  43678. return PostProcess;
  43679. }());
  43680. BABYLON.PostProcess = PostProcess;
  43681. })(BABYLON || (BABYLON = {}));
  43682. //# sourceMappingURL=babylon.postProcess.js.map
  43683. var BABYLON;
  43684. (function (BABYLON) {
  43685. var PassPostProcess = (function (_super) {
  43686. __extends(PassPostProcess, _super);
  43687. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  43688. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43689. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  43690. }
  43691. return PassPostProcess;
  43692. }(BABYLON.PostProcess));
  43693. BABYLON.PassPostProcess = PassPostProcess;
  43694. })(BABYLON || (BABYLON = {}));
  43695. //# sourceMappingURL=babylon.passPostProcess.js.map
  43696. var BABYLON;
  43697. (function (BABYLON) {
  43698. var ShadowGenerator = (function () {
  43699. /**
  43700. * Creates a ShadowGenerator object.
  43701. * A ShadowGenerator is the required tool to use the shadows.
  43702. * Each light casting shadows needs to use its own ShadowGenerator.
  43703. * Required parameters :
  43704. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  43705. * - `light` : the light object generating the shadows.
  43706. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  43707. */
  43708. function ShadowGenerator(mapSize, light) {
  43709. // Members
  43710. this._filter = ShadowGenerator.FILTER_NONE;
  43711. this.blurScale = 2;
  43712. this._blurBoxOffset = 0;
  43713. this._bias = 0.00005;
  43714. this._lightDirection = BABYLON.Vector3.Zero();
  43715. this.forceBackFacesOnly = false;
  43716. this._darkness = 0;
  43717. this._transparencyShadow = false;
  43718. this._viewMatrix = BABYLON.Matrix.Zero();
  43719. this._projectionMatrix = BABYLON.Matrix.Zero();
  43720. this._transformMatrix = BABYLON.Matrix.Zero();
  43721. this._worldViewProjection = BABYLON.Matrix.Zero();
  43722. this._currentFaceIndex = 0;
  43723. this._currentFaceIndexCache = 0;
  43724. this._useFullFloat = true;
  43725. this._isCube = false;
  43726. this._mapSize = mapSize;
  43727. this._light = light;
  43728. this._scene = light.getScene();
  43729. light._shadowGenerator = this;
  43730. // Texture type fallback from float to int if not supported.
  43731. var caps = this._scene.getEngine().getCaps();
  43732. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  43733. this._useFullFloat = true;
  43734. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43735. }
  43736. else {
  43737. this._useFullFloat = false;
  43738. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43739. }
  43740. this._initializeGenerator(1);
  43741. }
  43742. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  43743. // Static
  43744. get: function () {
  43745. return ShadowGenerator._FILTER_NONE;
  43746. },
  43747. enumerable: true,
  43748. configurable: true
  43749. });
  43750. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  43751. get: function () {
  43752. return ShadowGenerator._FILTER_POISSONSAMPLING;
  43753. },
  43754. enumerable: true,
  43755. configurable: true
  43756. });
  43757. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  43758. get: function () {
  43759. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  43760. },
  43761. enumerable: true,
  43762. configurable: true
  43763. });
  43764. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  43765. get: function () {
  43766. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  43767. },
  43768. enumerable: true,
  43769. configurable: true
  43770. });
  43771. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  43772. get: function () {
  43773. return this._bias;
  43774. },
  43775. set: function (bias) {
  43776. this._bias = bias;
  43777. },
  43778. enumerable: true,
  43779. configurable: true
  43780. });
  43781. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  43782. get: function () {
  43783. return this._blurBoxOffset;
  43784. },
  43785. set: function (value) {
  43786. var _this = this;
  43787. if (this._blurBoxOffset === value) {
  43788. return;
  43789. }
  43790. this._blurBoxOffset = value;
  43791. if (this._boxBlurPostprocess) {
  43792. this._boxBlurPostprocess.dispose();
  43793. }
  43794. var textureType;
  43795. var caps = this._scene.getEngine().getCaps();
  43796. if (this._useFullFloat) {
  43797. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43798. }
  43799. else {
  43800. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43801. }
  43802. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value, textureType);
  43803. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  43804. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  43805. });
  43806. },
  43807. enumerable: true,
  43808. configurable: true
  43809. });
  43810. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  43811. get: function () {
  43812. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  43813. },
  43814. set: function (value) {
  43815. this._depthScale = value;
  43816. },
  43817. enumerable: true,
  43818. configurable: true
  43819. });
  43820. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  43821. get: function () {
  43822. return this._filter;
  43823. },
  43824. set: function (value) {
  43825. if (this._filter === value) {
  43826. return;
  43827. }
  43828. this._filter = value;
  43829. this._applyFilterValues();
  43830. this._light._markMeshesAsLightDirty();
  43831. },
  43832. enumerable: true,
  43833. configurable: true
  43834. });
  43835. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  43836. get: function () {
  43837. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  43838. return this.useExponentialShadowMap;
  43839. },
  43840. set: function (value) {
  43841. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  43842. this.useExponentialShadowMap = value;
  43843. },
  43844. enumerable: true,
  43845. configurable: true
  43846. });
  43847. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  43848. get: function () {
  43849. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  43850. },
  43851. set: function (value) {
  43852. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  43853. },
  43854. enumerable: true,
  43855. configurable: true
  43856. });
  43857. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  43858. get: function () {
  43859. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  43860. },
  43861. set: function (value) {
  43862. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  43863. },
  43864. enumerable: true,
  43865. configurable: true
  43866. });
  43867. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  43868. get: function () {
  43869. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  43870. return this.useBlurExponentialShadowMap;
  43871. },
  43872. set: function (value) {
  43873. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  43874. this.useBlurExponentialShadowMap = value;
  43875. },
  43876. enumerable: true,
  43877. configurable: true
  43878. });
  43879. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  43880. get: function () {
  43881. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  43882. },
  43883. set: function (value) {
  43884. if (this._light.needCube() && value) {
  43885. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  43886. }
  43887. else {
  43888. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  43889. }
  43890. },
  43891. enumerable: true,
  43892. configurable: true
  43893. });
  43894. ShadowGenerator.prototype._initializeGenerator = function (boxBlurOffset) {
  43895. var _this = this;
  43896. var light = this._light;
  43897. var scene = this._scene;
  43898. var textureType = this._textureType;
  43899. light._markMeshesAsLightDirty();
  43900. // Render target
  43901. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", this._mapSize, this._scene, false, true, textureType, light.needCube());
  43902. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43903. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43904. this._shadowMap.anisotropicFilteringLevel = 1;
  43905. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43906. this._shadowMap.renderParticles = false;
  43907. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  43908. _this._currentFaceIndex = faceIndex;
  43909. });
  43910. this._shadowMap.onAfterUnbindObservable.add(function () {
  43911. if (!_this.useBlurExponentialShadowMap) {
  43912. return;
  43913. }
  43914. if (!_this._shadowMap2) {
  43915. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", _this._mapSize, _this._scene, false, true, textureType);
  43916. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43917. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43918. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43919. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  43920. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  43921. effect.setTexture("textureSampler", _this._shadowMap);
  43922. });
  43923. _this.blurBoxOffset = boxBlurOffset;
  43924. }
  43925. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  43926. });
  43927. // Custom render function
  43928. var renderSubMesh = function (subMesh) {
  43929. var mesh = subMesh.getRenderingMesh();
  43930. var scene = _this._scene;
  43931. var engine = scene.getEngine();
  43932. // Culling
  43933. engine.setState(subMesh.getMaterial().backFaceCulling);
  43934. // Managing instances
  43935. var batch = mesh._getInstancesRenderList(subMesh._id);
  43936. if (batch.mustReturn) {
  43937. return;
  43938. }
  43939. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43940. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  43941. engine.enableEffect(_this._effect);
  43942. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  43943. var material = subMesh.getMaterial();
  43944. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  43945. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  43946. _this._effect.setVector3("lightPosition", _this.getLight().position);
  43947. if (_this.getLight().needCube()) {
  43948. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  43949. }
  43950. // Alpha test
  43951. if (material && material.needAlphaTesting()) {
  43952. var alphaTexture = material.getAlphaTestTexture();
  43953. _this._effect.setTexture("diffuseSampler", alphaTexture);
  43954. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43955. }
  43956. // Bones
  43957. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43958. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43959. }
  43960. if (_this.forceBackFacesOnly) {
  43961. engine.setState(true, 0, false, true);
  43962. }
  43963. // Draw
  43964. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  43965. if (_this.forceBackFacesOnly) {
  43966. engine.setState(true, 0, false, false);
  43967. }
  43968. }
  43969. else {
  43970. // Need to reset refresh rate of the shadowMap
  43971. _this._shadowMap.resetRefreshCounter();
  43972. }
  43973. };
  43974. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  43975. var index;
  43976. for (index = 0; index < opaqueSubMeshes.length; index++) {
  43977. renderSubMesh(opaqueSubMeshes.data[index]);
  43978. }
  43979. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  43980. renderSubMesh(alphaTestSubMeshes.data[index]);
  43981. }
  43982. if (_this._transparencyShadow) {
  43983. for (index = 0; index < transparentSubMeshes.length; index++) {
  43984. renderSubMesh(transparentSubMeshes.data[index]);
  43985. }
  43986. }
  43987. };
  43988. this._shadowMap.onClearObservable.add(function (engine) {
  43989. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  43990. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  43991. }
  43992. else {
  43993. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  43994. }
  43995. });
  43996. };
  43997. ShadowGenerator.prototype._applyFilterValues = function () {
  43998. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  43999. this._shadowMap.anisotropicFilteringLevel = 16;
  44000. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44001. }
  44002. else {
  44003. this._shadowMap.anisotropicFilteringLevel = 1;
  44004. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  44005. }
  44006. };
  44007. ShadowGenerator.prototype.recreateShadowMap = function () {
  44008. // Clean up existing data.
  44009. this._disposeRTTandPostProcesses();
  44010. // Reinitializes.
  44011. this._initializeGenerator(this.blurBoxOffset);
  44012. // Reaffect the filter.
  44013. this._applyFilterValues();
  44014. };
  44015. /**
  44016. * Boolean : true when the ShadowGenerator is finally computed.
  44017. */
  44018. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  44019. var defines = [];
  44020. if (this._useFullFloat) {
  44021. defines.push("#define FULLFLOAT");
  44022. }
  44023. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44024. defines.push("#define ESM");
  44025. }
  44026. if (this.getLight().needCube()) {
  44027. defines.push("#define CUBEMAP");
  44028. }
  44029. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44030. var mesh = subMesh.getMesh();
  44031. var material = subMesh.getMaterial();
  44032. // Alpha test
  44033. if (material && material.needAlphaTesting()) {
  44034. defines.push("#define ALPHATEST");
  44035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44036. attribs.push(BABYLON.VertexBuffer.UVKind);
  44037. defines.push("#define UV1");
  44038. }
  44039. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44040. var alphaTexture = material.getAlphaTestTexture();
  44041. if (alphaTexture.coordinatesIndex === 1) {
  44042. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44043. defines.push("#define UV2");
  44044. }
  44045. }
  44046. }
  44047. // Bones
  44048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44051. if (mesh.numBoneInfluencers > 4) {
  44052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44054. }
  44055. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44056. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44057. }
  44058. else {
  44059. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44060. }
  44061. // Instances
  44062. if (useInstances) {
  44063. defines.push("#define INSTANCES");
  44064. attribs.push("world0");
  44065. attribs.push("world1");
  44066. attribs.push("world2");
  44067. attribs.push("world3");
  44068. }
  44069. // Get correct effect
  44070. var join = defines.join("\n");
  44071. if (this._cachedDefines !== join) {
  44072. this._cachedDefines = join;
  44073. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  44074. }
  44075. return this._effect.isReady();
  44076. };
  44077. /**
  44078. * Returns a RenderTargetTexture object : the shadow map texture.
  44079. */
  44080. ShadowGenerator.prototype.getShadowMap = function () {
  44081. return this._shadowMap;
  44082. };
  44083. /**
  44084. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  44085. */
  44086. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  44087. if (this._shadowMap2) {
  44088. return this._shadowMap2;
  44089. }
  44090. return this._shadowMap;
  44091. };
  44092. /**
  44093. * Returns the associated light object.
  44094. */
  44095. ShadowGenerator.prototype.getLight = function () {
  44096. return this._light;
  44097. };
  44098. // Methods
  44099. /**
  44100. * Returns a Matrix object : the updated transformation matrix.
  44101. */
  44102. ShadowGenerator.prototype.getTransformMatrix = function () {
  44103. var scene = this._scene;
  44104. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  44105. return this._transformMatrix;
  44106. }
  44107. this._currentRenderID = scene.getRenderId();
  44108. this._currentFaceIndexCache = this._currentFaceIndex;
  44109. var lightPosition = this._light.position;
  44110. if (this._light.computeTransformedInformation()) {
  44111. lightPosition = this._light.transformedPosition;
  44112. }
  44113. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  44114. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  44115. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  44116. }
  44117. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  44118. this._cachedPosition = lightPosition.clone();
  44119. this._cachedDirection = this._lightDirection.clone();
  44120. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  44121. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  44122. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  44123. }
  44124. return this._transformMatrix;
  44125. };
  44126. /**
  44127. * Returns the darkness value (float).
  44128. */
  44129. ShadowGenerator.prototype.getDarkness = function () {
  44130. return this._darkness;
  44131. };
  44132. /**
  44133. * Sets the ShadowGenerator darkness value (float <= 1.0).
  44134. * Returns the ShadowGenerator.
  44135. */
  44136. ShadowGenerator.prototype.setDarkness = function (darkness) {
  44137. if (darkness >= 1.0)
  44138. this._darkness = 1.0;
  44139. else if (darkness <= 0.0)
  44140. this._darkness = 0.0;
  44141. else
  44142. this._darkness = darkness;
  44143. return this;
  44144. };
  44145. /**
  44146. * Sets the ability to have transparent shadow (boolean).
  44147. * Returns the ShadowGenerator.
  44148. */
  44149. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  44150. this._transparencyShadow = hasShadow;
  44151. return this;
  44152. };
  44153. ShadowGenerator.prototype._packHalf = function (depth) {
  44154. var scale = depth * 255.0;
  44155. var fract = scale - Math.floor(scale);
  44156. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  44157. };
  44158. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  44159. if (this._shadowMap) {
  44160. this._shadowMap.dispose();
  44161. }
  44162. if (this._shadowMap2) {
  44163. this._shadowMap2.dispose();
  44164. }
  44165. if (this._downSamplePostprocess) {
  44166. this._downSamplePostprocess.dispose();
  44167. }
  44168. if (this._boxBlurPostprocess) {
  44169. this._boxBlurPostprocess.dispose();
  44170. }
  44171. };
  44172. /**
  44173. * Disposes the ShadowGenerator.
  44174. * Returns nothing.
  44175. */
  44176. ShadowGenerator.prototype.dispose = function () {
  44177. this._disposeRTTandPostProcesses();
  44178. this._light._shadowGenerator = null;
  44179. this._light._markMeshesAsLightDirty();
  44180. };
  44181. /**
  44182. * Serializes the ShadowGenerator and returns a serializationObject.
  44183. */
  44184. ShadowGenerator.prototype.serialize = function () {
  44185. var serializationObject = {};
  44186. var shadowMap = this.getShadowMap();
  44187. serializationObject.lightId = this._light.id;
  44188. serializationObject.mapSize = shadowMap.getRenderSize();
  44189. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  44190. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  44191. serializationObject.usePoissonSampling = this.usePoissonSampling;
  44192. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  44193. serializationObject.depthScale = this.depthScale;
  44194. serializationObject.darkness = this.getDarkness();
  44195. serializationObject.renderList = [];
  44196. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  44197. var mesh = shadowMap.renderList[meshIndex];
  44198. serializationObject.renderList.push(mesh.id);
  44199. }
  44200. return serializationObject;
  44201. };
  44202. /**
  44203. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  44204. */
  44205. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  44206. //casting to point light, as light is missing the position attr and typescript complains.
  44207. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  44208. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  44209. var shadowMap = shadowGenerator.getShadowMap();
  44210. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  44211. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  44212. meshes.forEach(function (mesh) {
  44213. shadowMap.renderList.push(mesh);
  44214. });
  44215. }
  44216. if (parsedShadowGenerator.usePoissonSampling) {
  44217. shadowGenerator.usePoissonSampling = true;
  44218. }
  44219. else if (parsedShadowGenerator.useExponentialShadowMap) {
  44220. shadowGenerator.useExponentialShadowMap = true;
  44221. }
  44222. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  44223. shadowGenerator.useBlurExponentialShadowMap = true;
  44224. }
  44225. else if (parsedShadowGenerator.useVarianceShadowMap) {
  44226. shadowGenerator.useExponentialShadowMap = true;
  44227. }
  44228. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  44229. shadowGenerator.useBlurExponentialShadowMap = true;
  44230. }
  44231. if (parsedShadowGenerator.depthScale) {
  44232. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  44233. }
  44234. if (parsedShadowGenerator.blurScale) {
  44235. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  44236. }
  44237. if (parsedShadowGenerator.blurBoxOffset) {
  44238. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  44239. }
  44240. if (parsedShadowGenerator.bias !== undefined) {
  44241. shadowGenerator.bias = parsedShadowGenerator.bias;
  44242. }
  44243. if (parsedShadowGenerator.darkness) {
  44244. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  44245. }
  44246. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  44247. return shadowGenerator;
  44248. };
  44249. /**
  44250. * This creates the defines related to the standard BJS materials.
  44251. */
  44252. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  44253. var scene = this._scene;
  44254. var light = this._light;
  44255. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44256. return;
  44257. }
  44258. defines["SHADOW" + lightIndex] = true;
  44259. if (this.usePoissonSampling) {
  44260. defines["SHADOWPCF" + lightIndex] = true;
  44261. }
  44262. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44263. defines["SHADOWESM" + lightIndex] = true;
  44264. }
  44265. if (light.needCube()) {
  44266. defines["SHADOWCUBE" + lightIndex] = true;
  44267. }
  44268. };
  44269. /**
  44270. * This binds shadow lights related to the standard BJS materials.
  44271. * It implies the unifroms available on the materials are the standard BJS ones.
  44272. */
  44273. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect, depthValuesAlreadySet) {
  44274. var light = this._light;
  44275. var scene = this._scene;
  44276. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44277. return;
  44278. }
  44279. if (!light.needCube()) {
  44280. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  44281. }
  44282. else {
  44283. if (!depthValuesAlreadySet) {
  44284. depthValuesAlreadySet = true;
  44285. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  44286. }
  44287. }
  44288. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  44289. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  44290. return depthValuesAlreadySet;
  44291. };
  44292. return ShadowGenerator;
  44293. }());
  44294. ShadowGenerator._FILTER_NONE = 0;
  44295. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  44296. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  44297. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  44298. BABYLON.ShadowGenerator = ShadowGenerator;
  44299. })(BABYLON || (BABYLON = {}));
  44300. //# sourceMappingURL=babylon.shadowGenerator.js.map
  44301. var BABYLON;
  44302. (function (BABYLON) {
  44303. var DefaultLoadingScreen = (function () {
  44304. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  44305. if (_loadingText === void 0) { _loadingText = ""; }
  44306. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  44307. var _this = this;
  44308. this._renderingCanvas = _renderingCanvas;
  44309. this._loadingText = _loadingText;
  44310. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  44311. // Resize
  44312. this._resizeLoadingUI = function () {
  44313. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  44314. _this._loadingDiv.style.position = "absolute";
  44315. _this._loadingDiv.style.left = canvasRect.left + "px";
  44316. _this._loadingDiv.style.top = canvasRect.top + "px";
  44317. _this._loadingDiv.style.width = canvasRect.width + "px";
  44318. _this._loadingDiv.style.height = canvasRect.height + "px";
  44319. };
  44320. }
  44321. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  44322. var _this = this;
  44323. if (this._loadingDiv) {
  44324. // Do not add a loading screen if there is already one
  44325. return;
  44326. }
  44327. this._loadingDiv = document.createElement("div");
  44328. this._loadingDiv.id = "babylonjsLoadingDiv";
  44329. this._loadingDiv.style.opacity = "0";
  44330. this._loadingDiv.style.transition = "opacity 1.5s ease";
  44331. // Loading text
  44332. this._loadingTextDiv = document.createElement("div");
  44333. this._loadingTextDiv.style.position = "absolute";
  44334. this._loadingTextDiv.style.left = "0";
  44335. this._loadingTextDiv.style.top = "50%";
  44336. this._loadingTextDiv.style.marginTop = "80px";
  44337. this._loadingTextDiv.style.width = "100%";
  44338. this._loadingTextDiv.style.height = "20px";
  44339. this._loadingTextDiv.style.fontFamily = "Arial";
  44340. this._loadingTextDiv.style.fontSize = "14px";
  44341. this._loadingTextDiv.style.color = "white";
  44342. this._loadingTextDiv.style.textAlign = "center";
  44343. this._loadingTextDiv.innerHTML = "Loading";
  44344. this._loadingDiv.appendChild(this._loadingTextDiv);
  44345. //set the predefined text
  44346. this._loadingTextDiv.innerHTML = this._loadingText;
  44347. // Loading img
  44348. var imgBack = new Image();
  44349. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  44350. imgBack.style.position = "absolute";
  44351. imgBack.style.left = "50%";
  44352. imgBack.style.top = "50%";
  44353. imgBack.style.marginLeft = "-50px";
  44354. imgBack.style.marginTop = "-50px";
  44355. imgBack.style.transition = "transform 1.0s ease";
  44356. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  44357. var deg = 360;
  44358. var onTransitionEnd = function () {
  44359. deg += 360;
  44360. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  44361. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  44362. };
  44363. imgBack.addEventListener("transitionend", onTransitionEnd);
  44364. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  44365. this._loadingDiv.appendChild(imgBack);
  44366. // front image
  44367. var imgFront = new Image();
  44368. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  44369. imgFront.style.position = "absolute";
  44370. imgFront.style.left = "50%";
  44371. imgFront.style.top = "50%";
  44372. imgFront.style.marginLeft = "-50px";
  44373. imgFront.style.marginTop = "-50px";
  44374. this._loadingDiv.appendChild(imgFront);
  44375. this._resizeLoadingUI();
  44376. window.addEventListener("resize", this._resizeLoadingUI);
  44377. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44378. document.body.appendChild(this._loadingDiv);
  44379. setTimeout(function () {
  44380. _this._loadingDiv.style.opacity = "1";
  44381. imgBack.style.transform = "rotateZ(360deg)";
  44382. imgBack.style.webkitTransform = "rotateZ(360deg)";
  44383. }, 0);
  44384. };
  44385. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  44386. var _this = this;
  44387. if (!this._loadingDiv) {
  44388. return;
  44389. }
  44390. var onTransitionEnd = function () {
  44391. if (!_this._loadingDiv) {
  44392. return;
  44393. }
  44394. document.body.removeChild(_this._loadingDiv);
  44395. window.removeEventListener("resize", _this._resizeLoadingUI);
  44396. _this._loadingDiv = null;
  44397. };
  44398. this._loadingDiv.style.opacity = "0";
  44399. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  44400. };
  44401. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  44402. set: function (text) {
  44403. this._loadingText = text;
  44404. if (this._loadingTextDiv) {
  44405. this._loadingTextDiv.innerHTML = this._loadingText;
  44406. }
  44407. },
  44408. enumerable: true,
  44409. configurable: true
  44410. });
  44411. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  44412. get: function () {
  44413. return this._loadingDivBackgroundColor;
  44414. },
  44415. set: function (color) {
  44416. this._loadingDivBackgroundColor = color;
  44417. if (!this._loadingDiv) {
  44418. return;
  44419. }
  44420. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44421. },
  44422. enumerable: true,
  44423. configurable: true
  44424. });
  44425. return DefaultLoadingScreen;
  44426. }());
  44427. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  44428. })(BABYLON || (BABYLON = {}));
  44429. //# sourceMappingURL=babylon.loadingScreen.js.map
  44430. var BABYLON;
  44431. (function (BABYLON) {
  44432. var SceneLoader = (function () {
  44433. function SceneLoader() {
  44434. }
  44435. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  44436. get: function () {
  44437. return 0;
  44438. },
  44439. enumerable: true,
  44440. configurable: true
  44441. });
  44442. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  44443. get: function () {
  44444. return 1;
  44445. },
  44446. enumerable: true,
  44447. configurable: true
  44448. });
  44449. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  44450. get: function () {
  44451. return 2;
  44452. },
  44453. enumerable: true,
  44454. configurable: true
  44455. });
  44456. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  44457. get: function () {
  44458. return 3;
  44459. },
  44460. enumerable: true,
  44461. configurable: true
  44462. });
  44463. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  44464. get: function () {
  44465. return SceneLoader._ForceFullSceneLoadingForIncremental;
  44466. },
  44467. set: function (value) {
  44468. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  44469. },
  44470. enumerable: true,
  44471. configurable: true
  44472. });
  44473. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  44474. get: function () {
  44475. return SceneLoader._ShowLoadingScreen;
  44476. },
  44477. set: function (value) {
  44478. SceneLoader._ShowLoadingScreen = value;
  44479. },
  44480. enumerable: true,
  44481. configurable: true
  44482. });
  44483. Object.defineProperty(SceneLoader, "loggingLevel", {
  44484. get: function () {
  44485. return SceneLoader._loggingLevel;
  44486. },
  44487. set: function (value) {
  44488. SceneLoader._loggingLevel = value;
  44489. },
  44490. enumerable: true,
  44491. configurable: true
  44492. });
  44493. SceneLoader._getDefaultPlugin = function () {
  44494. return SceneLoader._registeredPlugins[".babylon"];
  44495. };
  44496. SceneLoader._getPluginForExtension = function (extension) {
  44497. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  44498. if (registeredPlugin) {
  44499. return registeredPlugin;
  44500. }
  44501. return SceneLoader._getDefaultPlugin();
  44502. };
  44503. SceneLoader._getPluginForDirectLoad = function (data) {
  44504. for (var extension in SceneLoader._registeredPlugins) {
  44505. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  44506. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  44507. return SceneLoader._registeredPlugins[extension];
  44508. }
  44509. }
  44510. return SceneLoader._getDefaultPlugin();
  44511. };
  44512. SceneLoader._getPluginForFilename = function (sceneFilename) {
  44513. if (sceneFilename.name) {
  44514. sceneFilename = sceneFilename.name;
  44515. }
  44516. var dotPosition = sceneFilename.lastIndexOf(".");
  44517. var queryStringPosition = sceneFilename.indexOf("?");
  44518. if (queryStringPosition === -1) {
  44519. queryStringPosition = sceneFilename.length;
  44520. }
  44521. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  44522. return SceneLoader._getPluginForExtension(extension);
  44523. };
  44524. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  44525. SceneLoader._getDirectLoad = function (sceneFilename) {
  44526. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  44527. return sceneFilename.substr(5);
  44528. }
  44529. return null;
  44530. };
  44531. // Public functions
  44532. SceneLoader.GetPluginForExtension = function (extension) {
  44533. return SceneLoader._getPluginForExtension(extension).plugin;
  44534. };
  44535. SceneLoader.RegisterPlugin = function (plugin) {
  44536. if (typeof plugin.extensions === "string") {
  44537. var extension = plugin.extensions;
  44538. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44539. plugin: plugin,
  44540. isBinary: false
  44541. };
  44542. }
  44543. else {
  44544. var extensions = plugin.extensions;
  44545. Object.keys(extensions).forEach(function (extension) {
  44546. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44547. plugin: plugin,
  44548. isBinary: extensions[extension].isBinary
  44549. };
  44550. });
  44551. }
  44552. };
  44553. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44554. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44555. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44556. return;
  44557. }
  44558. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44559. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44560. return;
  44561. }
  44562. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44563. var loadingToken = {};
  44564. scene._addPendingData(loadingToken);
  44565. var manifestChecked = function (success) {
  44566. scene.database = database;
  44567. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  44568. var plugin = registeredPlugin.plugin;
  44569. var useArrayBuffer = registeredPlugin.isBinary;
  44570. var importMeshFromData = function (data) {
  44571. var meshes = [];
  44572. var particleSystems = [];
  44573. var skeletons = [];
  44574. if (scene.isDisposed) {
  44575. if (onerror) {
  44576. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  44577. }
  44578. return;
  44579. }
  44580. try {
  44581. if (plugin.importMesh) {
  44582. var syncedPlugin = plugin;
  44583. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  44584. if (onerror) {
  44585. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44586. }
  44587. scene._removePendingData(loadingToken);
  44588. return;
  44589. }
  44590. if (onsuccess) {
  44591. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44592. onsuccess(meshes, particleSystems, skeletons);
  44593. scene._removePendingData(loadingToken);
  44594. }
  44595. }
  44596. else {
  44597. var asyncedPlugin = plugin;
  44598. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  44599. if (onsuccess) {
  44600. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44601. onsuccess(meshes, particleSystems, skeletons);
  44602. scene._removePendingData(loadingToken);
  44603. }
  44604. }, function () {
  44605. if (onerror) {
  44606. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44607. }
  44608. scene._removePendingData(loadingToken);
  44609. });
  44610. }
  44611. }
  44612. catch (e) {
  44613. if (onerror) {
  44614. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  44615. }
  44616. scene._removePendingData(loadingToken);
  44617. }
  44618. };
  44619. if (directLoad) {
  44620. importMeshFromData(directLoad);
  44621. return;
  44622. }
  44623. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  44624. importMeshFromData(data);
  44625. }, progressCallBack, database, useArrayBuffer, function () {
  44626. if (onerror) {
  44627. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  44628. }
  44629. });
  44630. };
  44631. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  44632. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  44633. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  44634. }
  44635. else {
  44636. // If the scene is a data stream or offline support is not enabled, it's a direct load
  44637. manifestChecked(true);
  44638. }
  44639. };
  44640. /**
  44641. * Load a scene
  44642. * @param rootUrl a string that defines the root url for scene and resources
  44643. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44644. * @param engine is the instance of BABYLON.Engine to use to create the scene
  44645. */
  44646. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  44647. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  44648. };
  44649. /**
  44650. * Append a scene
  44651. * @param rootUrl a string that defines the root url for scene and resources
  44652. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44653. * @param scene is the instance of BABYLON.Scene to append to
  44654. */
  44655. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44656. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44657. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44658. return;
  44659. }
  44660. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44661. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  44662. var plugin = registeredPlugin.plugin;
  44663. var useArrayBuffer = registeredPlugin.isBinary;
  44664. var database;
  44665. var loadingToken = {};
  44666. scene._addPendingData(loadingToken);
  44667. if (SceneLoader.ShowLoadingScreen) {
  44668. scene.getEngine().displayLoadingUI();
  44669. }
  44670. var loadSceneFromData = function (data) {
  44671. scene.database = database;
  44672. if (plugin.load) {
  44673. var syncedPlugin = plugin;
  44674. if (!syncedPlugin.load(scene, data, rootUrl)) {
  44675. if (onerror) {
  44676. onerror(scene);
  44677. }
  44678. scene._removePendingData(loadingToken);
  44679. scene.getEngine().hideLoadingUI();
  44680. return;
  44681. }
  44682. if (onsuccess) {
  44683. onsuccess(scene);
  44684. }
  44685. scene._removePendingData(loadingToken);
  44686. }
  44687. else {
  44688. var asyncedPlugin = plugin;
  44689. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  44690. if (onsuccess) {
  44691. onsuccess(scene);
  44692. }
  44693. scene._removePendingData(loadingToken);
  44694. }, function () {
  44695. if (onerror) {
  44696. onerror(scene);
  44697. }
  44698. scene._removePendingData(loadingToken);
  44699. scene.getEngine().hideLoadingUI();
  44700. });
  44701. }
  44702. if (SceneLoader.ShowLoadingScreen) {
  44703. scene.executeWhenReady(function () {
  44704. scene.getEngine().hideLoadingUI();
  44705. });
  44706. }
  44707. };
  44708. var manifestChecked = function (success) {
  44709. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  44710. };
  44711. if (directLoad) {
  44712. loadSceneFromData(directLoad);
  44713. return;
  44714. }
  44715. if (rootUrl.indexOf("file:") === -1) {
  44716. if (scene.getEngine().enableOfflineSupport) {
  44717. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  44718. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  44719. }
  44720. else {
  44721. manifestChecked(true);
  44722. }
  44723. }
  44724. else {
  44725. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  44726. }
  44727. };
  44728. return SceneLoader;
  44729. }());
  44730. // Flags
  44731. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  44732. SceneLoader._ShowLoadingScreen = true;
  44733. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  44734. // Members
  44735. SceneLoader._registeredPlugins = {};
  44736. BABYLON.SceneLoader = SceneLoader;
  44737. ;
  44738. })(BABYLON || (BABYLON = {}));
  44739. //# sourceMappingURL=babylon.sceneLoader.js.map
  44740. var BABYLON;
  44741. (function (BABYLON) {
  44742. var Internals;
  44743. (function (Internals) {
  44744. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  44745. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  44746. var parsedMaterial = parsedData.materials[index];
  44747. if (parsedMaterial.id === id) {
  44748. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  44749. }
  44750. }
  44751. return null;
  44752. };
  44753. var isDescendantOf = function (mesh, names, hierarchyIds) {
  44754. names = (names instanceof Array) ? names : [names];
  44755. for (var i in names) {
  44756. if (mesh.name === names[i]) {
  44757. hierarchyIds.push(mesh.id);
  44758. return true;
  44759. }
  44760. }
  44761. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  44762. hierarchyIds.push(mesh.id);
  44763. return true;
  44764. }
  44765. return false;
  44766. };
  44767. var logOperation = function (operation, producer) {
  44768. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  44769. };
  44770. BABYLON.SceneLoader.RegisterPlugin({
  44771. extensions: ".babylon",
  44772. canDirectLoad: function (data) {
  44773. if (data.indexOf("babylon") !== -1) {
  44774. return true;
  44775. }
  44776. return false;
  44777. },
  44778. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  44779. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  44780. // when SceneLoader.debugLogging = true (default), or exception encountered.
  44781. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  44782. // and avoid problems with multiple concurrent .babylon loads.
  44783. var log = "importMesh has failed JSON parse";
  44784. try {
  44785. var parsedData = JSON.parse(data);
  44786. log = "";
  44787. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  44788. var loadedSkeletonsIds = [];
  44789. var loadedMaterialsIds = [];
  44790. var hierarchyIds = [];
  44791. var index;
  44792. var cache;
  44793. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  44794. var parsedMesh = parsedData.meshes[index];
  44795. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  44796. if (meshesNames instanceof Array) {
  44797. // Remove found mesh name from list.
  44798. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  44799. }
  44800. //Geometry?
  44801. if (parsedMesh.geometryId) {
  44802. //does the file contain geometries?
  44803. if (parsedData.geometries) {
  44804. //find the correct geometry and add it to the scene
  44805. var found = false;
  44806. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  44807. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  44808. return;
  44809. }
  44810. else {
  44811. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  44812. if (parsedGeometryData.id === parsedMesh.geometryId) {
  44813. switch (geometryType) {
  44814. case "boxes":
  44815. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  44816. break;
  44817. case "spheres":
  44818. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  44819. break;
  44820. case "cylinders":
  44821. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  44822. break;
  44823. case "toruses":
  44824. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  44825. break;
  44826. case "grounds":
  44827. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  44828. break;
  44829. case "planes":
  44830. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  44831. break;
  44832. case "torusKnots":
  44833. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  44834. break;
  44835. case "vertexData":
  44836. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  44837. break;
  44838. }
  44839. found = true;
  44840. }
  44841. });
  44842. }
  44843. });
  44844. if (!found) {
  44845. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  44846. }
  44847. }
  44848. }
  44849. // Material ?
  44850. if (parsedMesh.materialId) {
  44851. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  44852. if (!materialFound && parsedData.multiMaterials) {
  44853. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  44854. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  44855. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  44856. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  44857. var subMatId = parsedMultiMaterial.materials[matIndex];
  44858. loadedMaterialsIds.push(subMatId);
  44859. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  44860. log += "\n\tMaterial " + mat.toString(fullDetails);
  44861. }
  44862. loadedMaterialsIds.push(parsedMultiMaterial.id);
  44863. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  44864. materialFound = true;
  44865. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  44866. break;
  44867. }
  44868. }
  44869. }
  44870. if (!materialFound) {
  44871. loadedMaterialsIds.push(parsedMesh.materialId);
  44872. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  44873. if (!mat) {
  44874. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  44875. }
  44876. else {
  44877. log += "\n\tMaterial " + mat.toString(fullDetails);
  44878. }
  44879. }
  44880. }
  44881. // Skeleton ?
  44882. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  44883. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  44884. if (!skeletonAlreadyLoaded) {
  44885. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  44886. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  44887. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  44888. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  44889. skeletons.push(skeleton);
  44890. loadedSkeletonsIds.push(parsedSkeleton.id);
  44891. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  44892. }
  44893. }
  44894. }
  44895. }
  44896. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  44897. meshes.push(mesh);
  44898. log += "\n\tMesh " + mesh.toString(fullDetails);
  44899. }
  44900. }
  44901. // Connecting parents
  44902. var currentMesh;
  44903. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  44904. currentMesh = scene.meshes[index];
  44905. if (currentMesh._waitingParentId) {
  44906. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  44907. currentMesh._waitingParentId = undefined;
  44908. }
  44909. }
  44910. // freeze and compute world matrix application
  44911. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  44912. currentMesh = scene.meshes[index];
  44913. if (currentMesh._waitingFreezeWorldMatrix) {
  44914. currentMesh.freezeWorldMatrix();
  44915. currentMesh._waitingFreezeWorldMatrix = undefined;
  44916. }
  44917. else {
  44918. currentMesh.computeWorldMatrix(true);
  44919. }
  44920. }
  44921. // Particles
  44922. if (parsedData.particleSystems) {
  44923. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  44924. var parsedParticleSystem = parsedData.particleSystems[index];
  44925. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  44926. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  44927. }
  44928. }
  44929. }
  44930. return true;
  44931. }
  44932. catch (err) {
  44933. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  44934. log = null;
  44935. throw err;
  44936. }
  44937. finally {
  44938. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  44939. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  44940. }
  44941. }
  44942. },
  44943. load: function (scene, data, rootUrl) {
  44944. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  44945. // when SceneLoader.debugLogging = true (default), or exception encountered.
  44946. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  44947. // and avoid problems with multiple concurrent .babylon loads.
  44948. var log = "importScene has failed JSON parse";
  44949. try {
  44950. var parsedData = JSON.parse(data);
  44951. log = "";
  44952. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  44953. // Scene
  44954. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  44955. scene.autoClear = parsedData.autoClear;
  44956. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  44957. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  44958. if (parsedData.gravity) {
  44959. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  44960. }
  44961. // Fog
  44962. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  44963. scene.fogMode = parsedData.fogMode;
  44964. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  44965. scene.fogStart = parsedData.fogStart;
  44966. scene.fogEnd = parsedData.fogEnd;
  44967. scene.fogDensity = parsedData.fogDensity;
  44968. log += "\tFog mode for scene: ";
  44969. switch (scene.fogMode) {
  44970. // getters not compiling, so using hardcoded
  44971. case 1:
  44972. log += "exp\n";
  44973. break;
  44974. case 2:
  44975. log += "exp2\n";
  44976. break;
  44977. case 3:
  44978. log += "linear\n";
  44979. break;
  44980. }
  44981. }
  44982. //Physics
  44983. if (parsedData.physicsEnabled) {
  44984. var physicsPlugin;
  44985. if (parsedData.physicsEngine === "cannon") {
  44986. physicsPlugin = new BABYLON.CannonJSPlugin();
  44987. }
  44988. else if (parsedData.physicsEngine === "oimo") {
  44989. physicsPlugin = new BABYLON.OimoJSPlugin();
  44990. }
  44991. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  44992. //else - default engine, which is currently oimo
  44993. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  44994. scene.enablePhysics(physicsGravity, physicsPlugin);
  44995. }
  44996. // Metadata
  44997. if (parsedData.metadata !== undefined) {
  44998. scene.metadata = parsedData.metadata;
  44999. }
  45000. //collisions, if defined. otherwise, default is true
  45001. if (parsedData.collisionsEnabled != undefined) {
  45002. scene.collisionsEnabled = parsedData.collisionsEnabled;
  45003. }
  45004. scene.workerCollisions = !!parsedData.workerCollisions;
  45005. var index;
  45006. var cache;
  45007. // Lights
  45008. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  45009. var parsedLight = parsedData.lights[index];
  45010. var light = BABYLON.Light.Parse(parsedLight, scene);
  45011. log += (index === 0 ? "\n\tLights:" : "");
  45012. log += "\n\t\t" + light.toString(fullDetails);
  45013. }
  45014. // Animations
  45015. if (parsedData.animations) {
  45016. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  45017. var parsedAnimation = parsedData.animations[index];
  45018. var animation = BABYLON.Animation.Parse(parsedAnimation);
  45019. scene.animations.push(animation);
  45020. log += (index === 0 ? "\n\tAnimations:" : "");
  45021. log += "\n\t\t" + animation.toString(fullDetails);
  45022. }
  45023. }
  45024. if (parsedData.autoAnimate) {
  45025. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  45026. }
  45027. // Materials
  45028. if (parsedData.materials) {
  45029. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45030. var parsedMaterial = parsedData.materials[index];
  45031. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45032. log += (index === 0 ? "\n\tMaterials:" : "");
  45033. log += "\n\t\t" + mat.toString(fullDetails);
  45034. }
  45035. }
  45036. if (parsedData.multiMaterials) {
  45037. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  45038. var parsedMultiMaterial = parsedData.multiMaterials[index];
  45039. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45040. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  45041. log += "\n\t\t" + mmat.toString(fullDetails);
  45042. }
  45043. }
  45044. // Morph targets
  45045. if (parsedData.morphTargetManagers) {
  45046. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  45047. var managerData = _a[_i];
  45048. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  45049. }
  45050. }
  45051. // Skeletons
  45052. if (parsedData.skeletons) {
  45053. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  45054. var parsedSkeleton = parsedData.skeletons[index];
  45055. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45056. log += (index === 0 ? "\n\tSkeletons:" : "");
  45057. log += "\n\t\t" + skeleton.toString(fullDetails);
  45058. }
  45059. }
  45060. // Geometries
  45061. var geometries = parsedData.geometries;
  45062. if (geometries) {
  45063. // Boxes
  45064. var boxes = geometries.boxes;
  45065. if (boxes) {
  45066. for (index = 0, cache = boxes.length; index < cache; index++) {
  45067. var parsedBox = boxes[index];
  45068. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  45069. }
  45070. }
  45071. // Spheres
  45072. var spheres = geometries.spheres;
  45073. if (spheres) {
  45074. for (index = 0, cache = spheres.length; index < cache; index++) {
  45075. var parsedSphere = spheres[index];
  45076. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  45077. }
  45078. }
  45079. // Cylinders
  45080. var cylinders = geometries.cylinders;
  45081. if (cylinders) {
  45082. for (index = 0, cache = cylinders.length; index < cache; index++) {
  45083. var parsedCylinder = cylinders[index];
  45084. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  45085. }
  45086. }
  45087. // Toruses
  45088. var toruses = geometries.toruses;
  45089. if (toruses) {
  45090. for (index = 0, cache = toruses.length; index < cache; index++) {
  45091. var parsedTorus = toruses[index];
  45092. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  45093. }
  45094. }
  45095. // Grounds
  45096. var grounds = geometries.grounds;
  45097. if (grounds) {
  45098. for (index = 0, cache = grounds.length; index < cache; index++) {
  45099. var parsedGround = grounds[index];
  45100. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  45101. }
  45102. }
  45103. // Planes
  45104. var planes = geometries.planes;
  45105. if (planes) {
  45106. for (index = 0, cache = planes.length; index < cache; index++) {
  45107. var parsedPlane = planes[index];
  45108. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  45109. }
  45110. }
  45111. // TorusKnots
  45112. var torusKnots = geometries.torusKnots;
  45113. if (torusKnots) {
  45114. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  45115. var parsedTorusKnot = torusKnots[index];
  45116. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  45117. }
  45118. }
  45119. // VertexData
  45120. var vertexData = geometries.vertexData;
  45121. if (vertexData) {
  45122. for (index = 0, cache = vertexData.length; index < cache; index++) {
  45123. var parsedVertexData = vertexData[index];
  45124. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  45125. }
  45126. }
  45127. }
  45128. // Meshes
  45129. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45130. var parsedMesh = parsedData.meshes[index];
  45131. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45132. log += (index === 0 ? "\n\tMeshes:" : "");
  45133. log += "\n\t\t" + mesh.toString(fullDetails);
  45134. }
  45135. // Cameras
  45136. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  45137. var parsedCamera = parsedData.cameras[index];
  45138. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  45139. log += (index === 0 ? "\n\tCameras:" : "");
  45140. log += "\n\t\t" + camera.toString(fullDetails);
  45141. }
  45142. if (parsedData.activeCameraID) {
  45143. scene.setActiveCameraByID(parsedData.activeCameraID);
  45144. }
  45145. // Browsing all the graph to connect the dots
  45146. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  45147. var camera = scene.cameras[index];
  45148. if (camera._waitingParentId) {
  45149. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  45150. camera._waitingParentId = undefined;
  45151. }
  45152. }
  45153. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45154. var light = scene.lights[index];
  45155. if (light._waitingParentId) {
  45156. light.parent = scene.getLastEntryByID(light._waitingParentId);
  45157. light._waitingParentId = undefined;
  45158. }
  45159. }
  45160. // Sounds
  45161. var loadedSounds = [];
  45162. var loadedSound;
  45163. if (BABYLON.AudioEngine && parsedData.sounds) {
  45164. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  45165. var parsedSound = parsedData.sounds[index];
  45166. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45167. if (!parsedSound.url)
  45168. parsedSound.url = parsedSound.name;
  45169. if (!loadedSounds[parsedSound.url]) {
  45170. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  45171. loadedSounds[parsedSound.url] = loadedSound;
  45172. }
  45173. else {
  45174. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  45175. }
  45176. }
  45177. else {
  45178. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  45179. }
  45180. }
  45181. }
  45182. loadedSounds = [];
  45183. // Connect parents & children and parse actions
  45184. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45185. var mesh = scene.meshes[index];
  45186. if (mesh._waitingParentId) {
  45187. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  45188. mesh._waitingParentId = undefined;
  45189. }
  45190. if (mesh._waitingActions) {
  45191. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  45192. mesh._waitingActions = undefined;
  45193. }
  45194. }
  45195. // freeze world matrix application
  45196. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45197. var currentMesh = scene.meshes[index];
  45198. if (currentMesh._waitingFreezeWorldMatrix) {
  45199. currentMesh.freezeWorldMatrix();
  45200. currentMesh._waitingFreezeWorldMatrix = undefined;
  45201. }
  45202. else {
  45203. currentMesh.computeWorldMatrix(true);
  45204. }
  45205. }
  45206. // Particles Systems
  45207. if (parsedData.particleSystems) {
  45208. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45209. var parsedParticleSystem = parsedData.particleSystems[index];
  45210. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  45211. }
  45212. }
  45213. // Lens flares
  45214. if (parsedData.lensFlareSystems) {
  45215. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  45216. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  45217. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  45218. }
  45219. }
  45220. // Shadows
  45221. if (parsedData.shadowGenerators) {
  45222. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  45223. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  45224. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  45225. }
  45226. }
  45227. // Lights exclusions / inclusions
  45228. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45229. var light = scene.lights[index];
  45230. // Excluded check
  45231. if (light._excludedMeshesIds.length > 0) {
  45232. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  45233. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  45234. if (excludedMesh) {
  45235. light.excludedMeshes.push(excludedMesh);
  45236. }
  45237. }
  45238. light._excludedMeshesIds = [];
  45239. }
  45240. // Included check
  45241. if (light._includedOnlyMeshesIds.length > 0) {
  45242. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  45243. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  45244. if (includedOnlyMesh) {
  45245. light.includedOnlyMeshes.push(includedOnlyMesh);
  45246. }
  45247. }
  45248. light._includedOnlyMeshesIds = [];
  45249. }
  45250. }
  45251. // Actions (scene)
  45252. if (parsedData.actions) {
  45253. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  45254. }
  45255. // Finish
  45256. return true;
  45257. }
  45258. catch (err) {
  45259. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  45260. log = null;
  45261. throw err;
  45262. }
  45263. finally {
  45264. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45265. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45266. }
  45267. }
  45268. }
  45269. });
  45270. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45271. })(BABYLON || (BABYLON = {}));
  45272. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  45273. var BABYLON;
  45274. (function (BABYLON) {
  45275. var FilesInput = (function () {
  45276. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  45277. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  45278. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  45279. this._engine = p_engine;
  45280. this._canvas = p_canvas;
  45281. this._currentScene = p_scene;
  45282. this._sceneLoadedCallback = p_sceneLoadedCallback;
  45283. this._progressCallback = p_progressCallback;
  45284. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  45285. this._textureLoadingCallback = p_textureLoadingCallback;
  45286. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  45287. }
  45288. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  45289. var _this = this;
  45290. if (p_elementToMonitor) {
  45291. this._elementToMonitor = p_elementToMonitor;
  45292. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  45293. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  45294. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  45295. }
  45296. };
  45297. FilesInput.prototype.renderFunction = function () {
  45298. if (this._additionnalRenderLoopLogicCallback) {
  45299. this._additionnalRenderLoopLogicCallback();
  45300. }
  45301. if (this._currentScene) {
  45302. if (this._textureLoadingCallback) {
  45303. var remaining = this._currentScene.getWaitingItemsCount();
  45304. if (remaining > 0) {
  45305. this._textureLoadingCallback(remaining);
  45306. }
  45307. }
  45308. this._currentScene.render();
  45309. }
  45310. };
  45311. FilesInput.prototype.drag = function (e) {
  45312. e.stopPropagation();
  45313. e.preventDefault();
  45314. };
  45315. FilesInput.prototype.drop = function (eventDrop) {
  45316. eventDrop.stopPropagation();
  45317. eventDrop.preventDefault();
  45318. this.loadFiles(eventDrop);
  45319. };
  45320. FilesInput.prototype.loadFiles = function (event) {
  45321. if (this._startingProcessingFilesCallback)
  45322. this._startingProcessingFilesCallback();
  45323. // Handling data transfer via drag'n'drop
  45324. if (event && event.dataTransfer && event.dataTransfer.files) {
  45325. this._filesToLoad = event.dataTransfer.files;
  45326. }
  45327. // Handling files from input files
  45328. if (event && event.target && event.target.files) {
  45329. this._filesToLoad = event.target.files;
  45330. }
  45331. if (this._filesToLoad && this._filesToLoad.length > 0) {
  45332. for (var i = 0; i < this._filesToLoad.length; i++) {
  45333. var name_1 = this._filesToLoad[i].name.toLowerCase();
  45334. var extension = name_1.split('.').pop();
  45335. var type = this._filesToLoad[i].type;
  45336. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  45337. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  45338. this._sceneFileToLoad = this._filesToLoad[i];
  45339. }
  45340. else {
  45341. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  45342. }
  45343. }
  45344. this.reload();
  45345. }
  45346. };
  45347. FilesInput.prototype.reload = function () {
  45348. var _this = this;
  45349. var that = this;
  45350. // If a ".babylon" file has been provided
  45351. if (this._sceneFileToLoad) {
  45352. if (this._currentScene) {
  45353. if (BABYLON.Tools.errorsCount > 0) {
  45354. BABYLON.Tools.ClearLogCache();
  45355. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  45356. }
  45357. this._engine.stopRenderLoop();
  45358. this._currentScene.dispose();
  45359. }
  45360. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  45361. that._currentScene = newScene;
  45362. // Wait for textures and shaders to be ready
  45363. that._currentScene.executeWhenReady(function () {
  45364. if (that._sceneLoadedCallback) {
  45365. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  45366. }
  45367. that._engine.runRenderLoop(function () { that.renderFunction(); });
  45368. });
  45369. }, function (progress) {
  45370. if (_this._progressCallback) {
  45371. _this._progressCallback(progress);
  45372. }
  45373. });
  45374. }
  45375. else {
  45376. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  45377. }
  45378. };
  45379. return FilesInput;
  45380. }());
  45381. FilesInput.FilesToLoad = new Array();
  45382. BABYLON.FilesInput = FilesInput;
  45383. })(BABYLON || (BABYLON = {}));
  45384. //# sourceMappingURL=babylon.filesInput.js.map
  45385. var BABYLON;
  45386. (function (BABYLON) {
  45387. /**
  45388. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45389. * The underlying implementation relies on an associative array to ensure the best performances.
  45390. * The value can be anything including 'null' but except 'undefined'
  45391. */
  45392. var StringDictionary = (function () {
  45393. function StringDictionary() {
  45394. this._count = 0;
  45395. this._data = {};
  45396. }
  45397. /**
  45398. * This will clear this dictionary and copy the content from the 'source' one.
  45399. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45400. * @param source the dictionary to take the content from and copy to this dictionary
  45401. */
  45402. StringDictionary.prototype.copyFrom = function (source) {
  45403. var _this = this;
  45404. this.clear();
  45405. source.forEach(function (t, v) { return _this.add(t, v); });
  45406. };
  45407. /**
  45408. * Get a value based from its key
  45409. * @param key the given key to get the matching value from
  45410. * @return the value if found, otherwise undefined is returned
  45411. */
  45412. StringDictionary.prototype.get = function (key) {
  45413. var val = this._data[key];
  45414. if (val !== undefined) {
  45415. return val;
  45416. }
  45417. return undefined;
  45418. };
  45419. /**
  45420. * Get a value from its key or add it if it doesn't exist.
  45421. * This method will ensure you that a given key/data will be present in the dictionary.
  45422. * @param key the given key to get the matching value from
  45423. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45424. * The factory will only be invoked if there's no data for the given key.
  45425. * @return the value corresponding to the key.
  45426. */
  45427. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45428. var val = this.get(key);
  45429. if (val !== undefined) {
  45430. return val;
  45431. }
  45432. val = factory(key);
  45433. if (val) {
  45434. this.add(key, val);
  45435. }
  45436. return val;
  45437. };
  45438. /**
  45439. * Get a value from its key if present in the dictionary otherwise add it
  45440. * @param key the key to get the value from
  45441. * @param val if there's no such key/value pair in the dictionary add it with this value
  45442. * @return the value corresponding to the key
  45443. */
  45444. StringDictionary.prototype.getOrAdd = function (key, val) {
  45445. var curVal = this.get(key);
  45446. if (curVal !== undefined) {
  45447. return curVal;
  45448. }
  45449. this.add(key, val);
  45450. return val;
  45451. };
  45452. /**
  45453. * Check if there's a given key in the dictionary
  45454. * @param key the key to check for
  45455. * @return true if the key is present, false otherwise
  45456. */
  45457. StringDictionary.prototype.contains = function (key) {
  45458. return this._data[key] !== undefined;
  45459. };
  45460. /**
  45461. * Add a new key and its corresponding value
  45462. * @param key the key to add
  45463. * @param value the value corresponding to the key
  45464. * @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
  45465. */
  45466. StringDictionary.prototype.add = function (key, value) {
  45467. if (this._data[key] !== undefined) {
  45468. return false;
  45469. }
  45470. this._data[key] = value;
  45471. ++this._count;
  45472. return true;
  45473. };
  45474. StringDictionary.prototype.set = function (key, value) {
  45475. if (this._data[key] === undefined) {
  45476. return false;
  45477. }
  45478. this._data[key] = value;
  45479. return true;
  45480. };
  45481. /**
  45482. * Get the element of the given key and remove it from the dictionary
  45483. * @param key
  45484. */
  45485. StringDictionary.prototype.getAndRemove = function (key) {
  45486. var val = this.get(key);
  45487. if (val !== undefined) {
  45488. delete this._data[key];
  45489. --this._count;
  45490. return val;
  45491. }
  45492. return null;
  45493. };
  45494. /**
  45495. * Remove a key/value from the dictionary.
  45496. * @param key the key to remove
  45497. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45498. */
  45499. StringDictionary.prototype.remove = function (key) {
  45500. if (this.contains(key)) {
  45501. delete this._data[key];
  45502. --this._count;
  45503. return true;
  45504. }
  45505. return false;
  45506. };
  45507. /**
  45508. * Clear the whole content of the dictionary
  45509. */
  45510. StringDictionary.prototype.clear = function () {
  45511. this._data = {};
  45512. this._count = 0;
  45513. };
  45514. Object.defineProperty(StringDictionary.prototype, "count", {
  45515. get: function () {
  45516. return this._count;
  45517. },
  45518. enumerable: true,
  45519. configurable: true
  45520. });
  45521. /**
  45522. * Execute a callback on each key/val of the dictionary.
  45523. * Note that you can remove any element in this dictionary in the callback implementation
  45524. * @param callback the callback to execute on a given key/value pair
  45525. */
  45526. StringDictionary.prototype.forEach = function (callback) {
  45527. for (var cur in this._data) {
  45528. var val = this._data[cur];
  45529. callback(cur, val);
  45530. }
  45531. };
  45532. /**
  45533. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45534. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45535. * Note that you can remove any element in this dictionary in the callback implementation
  45536. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45537. */
  45538. StringDictionary.prototype.first = function (callback) {
  45539. for (var cur in this._data) {
  45540. var val = this._data[cur];
  45541. var res = callback(cur, val);
  45542. if (res) {
  45543. return res;
  45544. }
  45545. }
  45546. return null;
  45547. };
  45548. return StringDictionary;
  45549. }());
  45550. BABYLON.StringDictionary = StringDictionary;
  45551. })(BABYLON || (BABYLON = {}));
  45552. //# sourceMappingURL=babylon.stringDictionary.js.map
  45553. var BABYLON;
  45554. (function (BABYLON) {
  45555. var Tags = (function () {
  45556. function Tags() {
  45557. }
  45558. Tags.EnableFor = function (obj) {
  45559. obj._tags = obj._tags || {};
  45560. obj.hasTags = function () {
  45561. return Tags.HasTags(obj);
  45562. };
  45563. obj.addTags = function (tagsString) {
  45564. return Tags.AddTagsTo(obj, tagsString);
  45565. };
  45566. obj.removeTags = function (tagsString) {
  45567. return Tags.RemoveTagsFrom(obj, tagsString);
  45568. };
  45569. obj.matchesTagsQuery = function (tagsQuery) {
  45570. return Tags.MatchesQuery(obj, tagsQuery);
  45571. };
  45572. };
  45573. Tags.DisableFor = function (obj) {
  45574. delete obj._tags;
  45575. delete obj.hasTags;
  45576. delete obj.addTags;
  45577. delete obj.removeTags;
  45578. delete obj.matchesTagsQuery;
  45579. };
  45580. Tags.HasTags = function (obj) {
  45581. if (!obj._tags) {
  45582. return false;
  45583. }
  45584. return !BABYLON.Tools.IsEmpty(obj._tags);
  45585. };
  45586. Tags.GetTags = function (obj, asString) {
  45587. if (asString === void 0) { asString = true; }
  45588. if (!obj._tags) {
  45589. return null;
  45590. }
  45591. if (asString) {
  45592. var tagsArray = [];
  45593. for (var tag in obj._tags) {
  45594. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  45595. tagsArray.push(tag);
  45596. }
  45597. }
  45598. return tagsArray.join(" ");
  45599. }
  45600. else {
  45601. return obj._tags;
  45602. }
  45603. };
  45604. // the tags 'true' and 'false' are reserved and cannot be used as tags
  45605. // a tag cannot start with '||', '&&', and '!'
  45606. // it cannot contain whitespaces
  45607. Tags.AddTagsTo = function (obj, tagsString) {
  45608. if (!tagsString) {
  45609. return;
  45610. }
  45611. if (typeof tagsString !== "string") {
  45612. return;
  45613. }
  45614. var tags = tagsString.split(" ");
  45615. tags.forEach(function (tag, index, array) {
  45616. Tags._AddTagTo(obj, tag);
  45617. });
  45618. };
  45619. Tags._AddTagTo = function (obj, tag) {
  45620. tag = tag.trim();
  45621. if (tag === "" || tag === "true" || tag === "false") {
  45622. return;
  45623. }
  45624. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  45625. return;
  45626. }
  45627. Tags.EnableFor(obj);
  45628. obj._tags[tag] = true;
  45629. };
  45630. Tags.RemoveTagsFrom = function (obj, tagsString) {
  45631. if (!Tags.HasTags(obj)) {
  45632. return;
  45633. }
  45634. var tags = tagsString.split(" ");
  45635. for (var t in tags) {
  45636. Tags._RemoveTagFrom(obj, tags[t]);
  45637. }
  45638. };
  45639. Tags._RemoveTagFrom = function (obj, tag) {
  45640. delete obj._tags[tag];
  45641. };
  45642. Tags.MatchesQuery = function (obj, tagsQuery) {
  45643. if (tagsQuery === undefined) {
  45644. return true;
  45645. }
  45646. if (tagsQuery === "") {
  45647. return Tags.HasTags(obj);
  45648. }
  45649. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  45650. };
  45651. return Tags;
  45652. }());
  45653. BABYLON.Tags = Tags;
  45654. })(BABYLON || (BABYLON = {}));
  45655. //# sourceMappingURL=babylon.tags.js.map
  45656. var BABYLON;
  45657. (function (BABYLON) {
  45658. var Internals;
  45659. (function (Internals) {
  45660. var AndOrNotEvaluator = (function () {
  45661. function AndOrNotEvaluator() {
  45662. }
  45663. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  45664. if (!query.match(/\([^\(\)]*\)/g)) {
  45665. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  45666. }
  45667. else {
  45668. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  45669. // remove parenthesis
  45670. r = r.slice(1, r.length - 1);
  45671. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  45672. });
  45673. }
  45674. if (query === "true") {
  45675. return true;
  45676. }
  45677. if (query === "false") {
  45678. return false;
  45679. }
  45680. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  45681. };
  45682. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  45683. evaluateCallback = evaluateCallback || (function (r) {
  45684. return r === "true" ? true : false;
  45685. });
  45686. var result;
  45687. var or = parenthesisContent.split("||");
  45688. for (var i in or) {
  45689. if (or.hasOwnProperty(i)) {
  45690. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  45691. var and = ori.split("&&");
  45692. if (and.length > 1) {
  45693. for (var j = 0; j < and.length; ++j) {
  45694. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  45695. if (andj !== "true" && andj !== "false") {
  45696. if (andj[0] === "!") {
  45697. result = !evaluateCallback(andj.substring(1));
  45698. }
  45699. else {
  45700. result = evaluateCallback(andj);
  45701. }
  45702. }
  45703. else {
  45704. result = andj === "true" ? true : false;
  45705. }
  45706. if (!result) {
  45707. ori = "false";
  45708. break;
  45709. }
  45710. }
  45711. }
  45712. if (result || ori === "true") {
  45713. result = true;
  45714. break;
  45715. }
  45716. // result equals false (or undefined)
  45717. if (ori !== "true" && ori !== "false") {
  45718. if (ori[0] === "!") {
  45719. result = !evaluateCallback(ori.substring(1));
  45720. }
  45721. else {
  45722. result = evaluateCallback(ori);
  45723. }
  45724. }
  45725. else {
  45726. result = ori === "true" ? true : false;
  45727. }
  45728. }
  45729. }
  45730. // the whole parenthesis scope is replaced by 'true' or 'false'
  45731. return result ? "true" : "false";
  45732. };
  45733. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  45734. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  45735. // remove whitespaces
  45736. r = r.replace(/[\s]/g, function () { return ""; });
  45737. return r.length % 2 ? "!" : "";
  45738. });
  45739. booleanString = booleanString.trim();
  45740. if (booleanString === "!true") {
  45741. booleanString = "false";
  45742. }
  45743. else if (booleanString === "!false") {
  45744. booleanString = "true";
  45745. }
  45746. return booleanString;
  45747. };
  45748. return AndOrNotEvaluator;
  45749. }());
  45750. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  45751. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45752. })(BABYLON || (BABYLON = {}));
  45753. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  45754. var BABYLON;
  45755. (function (BABYLON) {
  45756. var Database = (function () {
  45757. function Database(urlToScene, callbackManifestChecked) {
  45758. // Handling various flavors of prefixed version of IndexedDB
  45759. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  45760. this.callbackManifestChecked = callbackManifestChecked;
  45761. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  45762. this.db = null;
  45763. this.enableSceneOffline = false;
  45764. this.enableTexturesOffline = false;
  45765. this.manifestVersionFound = 0;
  45766. this.mustUpdateRessources = false;
  45767. this.hasReachedQuota = false;
  45768. if (!Database.IDBStorageEnabled) {
  45769. this.callbackManifestChecked(true);
  45770. }
  45771. else {
  45772. this.checkManifestFile();
  45773. }
  45774. }
  45775. Database.prototype.checkManifestFile = function () {
  45776. var _this = this;
  45777. function noManifestFile() {
  45778. that.enableSceneOffline = false;
  45779. that.enableTexturesOffline = false;
  45780. that.callbackManifestChecked(false);
  45781. }
  45782. var that = this;
  45783. var timeStampUsed = false;
  45784. var manifestURL = this.currentSceneUrl + ".manifest";
  45785. var xhr = new XMLHttpRequest();
  45786. if (navigator.onLine) {
  45787. // Adding a timestamp to by-pass browsers' cache
  45788. timeStampUsed = true;
  45789. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  45790. }
  45791. xhr.open("GET", manifestURL, true);
  45792. xhr.addEventListener("load", function () {
  45793. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  45794. try {
  45795. var manifestFile = JSON.parse(xhr.response);
  45796. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  45797. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  45798. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  45799. _this.manifestVersionFound = manifestFile.version;
  45800. }
  45801. if (_this.callbackManifestChecked) {
  45802. _this.callbackManifestChecked(true);
  45803. }
  45804. }
  45805. catch (ex) {
  45806. noManifestFile();
  45807. }
  45808. }
  45809. else {
  45810. noManifestFile();
  45811. }
  45812. }, false);
  45813. xhr.addEventListener("error", function (event) {
  45814. if (timeStampUsed) {
  45815. timeStampUsed = false;
  45816. // Let's retry without the timeStamp
  45817. // It could fail when coupled with HTML5 Offline API
  45818. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  45819. xhr.open("GET", retryManifestURL, true);
  45820. xhr.send();
  45821. }
  45822. else {
  45823. noManifestFile();
  45824. }
  45825. }, false);
  45826. try {
  45827. xhr.send();
  45828. }
  45829. catch (ex) {
  45830. BABYLON.Tools.Error("Error on XHR send request.");
  45831. that.callbackManifestChecked(false);
  45832. }
  45833. };
  45834. Database.prototype.openAsync = function (successCallback, errorCallback) {
  45835. var _this = this;
  45836. function handleError() {
  45837. that.isSupported = false;
  45838. if (errorCallback)
  45839. errorCallback();
  45840. }
  45841. var that = this;
  45842. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  45843. // Your browser doesn't support IndexedDB
  45844. this.isSupported = false;
  45845. if (errorCallback)
  45846. errorCallback();
  45847. }
  45848. else {
  45849. // If the DB hasn't been opened or created yet
  45850. if (!this.db) {
  45851. this.hasReachedQuota = false;
  45852. this.isSupported = true;
  45853. var request = this.idbFactory.open("babylonjs", 1);
  45854. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  45855. request.onerror = function (event) {
  45856. handleError();
  45857. };
  45858. // executes when a version change transaction cannot complete due to other active transactions
  45859. request.onblocked = function (event) {
  45860. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  45861. handleError();
  45862. };
  45863. // DB has been opened successfully
  45864. request.onsuccess = function (event) {
  45865. _this.db = request.result;
  45866. successCallback();
  45867. };
  45868. // Initialization of the DB. Creating Scenes & Textures stores
  45869. request.onupgradeneeded = function (event) {
  45870. _this.db = (event.target).result;
  45871. try {
  45872. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  45873. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  45874. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  45875. }
  45876. catch (ex) {
  45877. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  45878. handleError();
  45879. }
  45880. };
  45881. }
  45882. else {
  45883. if (successCallback)
  45884. successCallback();
  45885. }
  45886. }
  45887. };
  45888. Database.prototype.loadImageFromDB = function (url, image) {
  45889. var _this = this;
  45890. var completeURL = Database.ReturnFullUrlLocation(url);
  45891. var saveAndLoadImage = function () {
  45892. if (!_this.hasReachedQuota && _this.db !== null) {
  45893. // the texture is not yet in the DB, let's try to save it
  45894. _this._saveImageIntoDBAsync(completeURL, image);
  45895. }
  45896. else {
  45897. image.src = url;
  45898. }
  45899. };
  45900. if (!this.mustUpdateRessources) {
  45901. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  45902. }
  45903. else {
  45904. saveAndLoadImage();
  45905. }
  45906. };
  45907. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  45908. if (this.isSupported && this.db !== null) {
  45909. var texture;
  45910. var transaction = this.db.transaction(["textures"]);
  45911. transaction.onabort = function (event) {
  45912. image.src = url;
  45913. };
  45914. transaction.oncomplete = function (event) {
  45915. var blobTextureURL;
  45916. if (texture) {
  45917. var URL = window.URL || window.webkitURL;
  45918. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  45919. image.onerror = function () {
  45920. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  45921. image.src = url;
  45922. };
  45923. image.src = blobTextureURL;
  45924. }
  45925. else {
  45926. notInDBCallback();
  45927. }
  45928. };
  45929. var getRequest = transaction.objectStore("textures").get(url);
  45930. getRequest.onsuccess = function (event) {
  45931. texture = (event.target).result;
  45932. };
  45933. getRequest.onerror = function (event) {
  45934. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  45935. image.src = url;
  45936. };
  45937. }
  45938. else {
  45939. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  45940. image.src = url;
  45941. }
  45942. };
  45943. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  45944. var _this = this;
  45945. if (this.isSupported) {
  45946. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  45947. var generateBlobUrl = function () {
  45948. var blobTextureURL;
  45949. if (blob) {
  45950. var URL = window.URL || window.webkitURL;
  45951. try {
  45952. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  45953. }
  45954. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  45955. catch (ex) {
  45956. blobTextureURL = URL.createObjectURL(blob);
  45957. }
  45958. }
  45959. image.src = blobTextureURL;
  45960. };
  45961. if (Database.IsUASupportingBlobStorage) {
  45962. var xhr = new XMLHttpRequest(), blob;
  45963. xhr.open("GET", url, true);
  45964. xhr.responseType = "blob";
  45965. xhr.addEventListener("load", function () {
  45966. if (xhr.status === 200) {
  45967. // Blob as response (XHR2)
  45968. blob = xhr.response;
  45969. var transaction = _this.db.transaction(["textures"], "readwrite");
  45970. // the transaction could abort because of a QuotaExceededError error
  45971. transaction.onabort = function (event) {
  45972. try {
  45973. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  45974. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  45975. _this.hasReachedQuota = true;
  45976. }
  45977. }
  45978. catch (ex) { }
  45979. generateBlobUrl();
  45980. };
  45981. transaction.oncomplete = function (event) {
  45982. generateBlobUrl();
  45983. };
  45984. var newTexture = { textureUrl: url, data: blob };
  45985. try {
  45986. // Put the blob into the dabase
  45987. var addRequest = transaction.objectStore("textures").put(newTexture);
  45988. addRequest.onsuccess = function (event) {
  45989. };
  45990. addRequest.onerror = function (event) {
  45991. generateBlobUrl();
  45992. };
  45993. }
  45994. catch (ex) {
  45995. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  45996. if (ex.code === 25) {
  45997. Database.IsUASupportingBlobStorage = false;
  45998. }
  45999. image.src = url;
  46000. }
  46001. }
  46002. else {
  46003. image.src = url;
  46004. }
  46005. }, false);
  46006. xhr.addEventListener("error", function (event) {
  46007. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  46008. image.src = url;
  46009. }, false);
  46010. xhr.send();
  46011. }
  46012. else {
  46013. image.src = url;
  46014. }
  46015. }
  46016. else {
  46017. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46018. image.src = url;
  46019. }
  46020. };
  46021. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  46022. var _this = this;
  46023. var updateVersion = function (event) {
  46024. // the version is not yet in the DB or we need to update it
  46025. _this._saveVersionIntoDBAsync(url, versionLoaded);
  46026. };
  46027. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  46028. };
  46029. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  46030. var _this = this;
  46031. if (this.isSupported) {
  46032. var version;
  46033. try {
  46034. var transaction = this.db.transaction(["versions"]);
  46035. transaction.oncomplete = function (event) {
  46036. if (version) {
  46037. // If the version in the JSON file is > than the version in DB
  46038. if (_this.manifestVersionFound > version.data) {
  46039. _this.mustUpdateRessources = true;
  46040. updateInDBCallback();
  46041. }
  46042. else {
  46043. callback(version.data);
  46044. }
  46045. }
  46046. else {
  46047. _this.mustUpdateRessources = true;
  46048. updateInDBCallback();
  46049. }
  46050. };
  46051. transaction.onabort = function (event) {
  46052. callback(-1);
  46053. };
  46054. var getRequest = transaction.objectStore("versions").get(url);
  46055. getRequest.onsuccess = function (event) {
  46056. version = (event.target).result;
  46057. };
  46058. getRequest.onerror = function (event) {
  46059. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  46060. callback(-1);
  46061. };
  46062. }
  46063. catch (ex) {
  46064. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  46065. callback(-1);
  46066. }
  46067. }
  46068. else {
  46069. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46070. callback(-1);
  46071. }
  46072. };
  46073. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  46074. var _this = this;
  46075. if (this.isSupported && !this.hasReachedQuota) {
  46076. try {
  46077. // Open a transaction to the database
  46078. var transaction = this.db.transaction(["versions"], "readwrite");
  46079. // the transaction could abort because of a QuotaExceededError error
  46080. transaction.onabort = function (event) {
  46081. try {
  46082. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46083. _this.hasReachedQuota = true;
  46084. }
  46085. }
  46086. catch (ex) { }
  46087. callback(-1);
  46088. };
  46089. transaction.oncomplete = function (event) {
  46090. callback(_this.manifestVersionFound);
  46091. };
  46092. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  46093. // Put the scene into the database
  46094. var addRequest = transaction.objectStore("versions").put(newVersion);
  46095. addRequest.onsuccess = function (event) {
  46096. };
  46097. addRequest.onerror = function (event) {
  46098. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  46099. };
  46100. }
  46101. catch (ex) {
  46102. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  46103. callback(-1);
  46104. }
  46105. }
  46106. else {
  46107. callback(-1);
  46108. }
  46109. };
  46110. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  46111. var _this = this;
  46112. var completeUrl = Database.ReturnFullUrlLocation(url);
  46113. var saveAndLoadFile = function (event) {
  46114. // the scene is not yet in the DB, let's try to save it
  46115. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  46116. };
  46117. this._checkVersionFromDB(completeUrl, function (version) {
  46118. if (version !== -1) {
  46119. if (!_this.mustUpdateRessources) {
  46120. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  46121. }
  46122. else {
  46123. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  46124. }
  46125. }
  46126. else {
  46127. errorCallback();
  46128. }
  46129. });
  46130. };
  46131. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  46132. if (this.isSupported) {
  46133. var targetStore;
  46134. if (url.indexOf(".babylon") !== -1) {
  46135. targetStore = "scenes";
  46136. }
  46137. else {
  46138. targetStore = "textures";
  46139. }
  46140. var file;
  46141. var transaction = this.db.transaction([targetStore]);
  46142. transaction.oncomplete = function (event) {
  46143. if (file) {
  46144. callback(file.data);
  46145. }
  46146. else {
  46147. notInDBCallback();
  46148. }
  46149. };
  46150. transaction.onabort = function (event) {
  46151. notInDBCallback();
  46152. };
  46153. var getRequest = transaction.objectStore(targetStore).get(url);
  46154. getRequest.onsuccess = function (event) {
  46155. file = (event.target).result;
  46156. };
  46157. getRequest.onerror = function (event) {
  46158. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  46159. notInDBCallback();
  46160. };
  46161. }
  46162. else {
  46163. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46164. callback();
  46165. }
  46166. };
  46167. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  46168. var _this = this;
  46169. if (this.isSupported) {
  46170. var targetStore;
  46171. if (url.indexOf(".babylon") !== -1) {
  46172. targetStore = "scenes";
  46173. }
  46174. else {
  46175. targetStore = "textures";
  46176. }
  46177. // Create XHR
  46178. var xhr = new XMLHttpRequest(), fileData;
  46179. xhr.open("GET", url, true);
  46180. if (useArrayBuffer) {
  46181. xhr.responseType = "arraybuffer";
  46182. }
  46183. xhr.onprogress = progressCallback;
  46184. xhr.addEventListener("load", function () {
  46185. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  46186. // Blob as response (XHR2)
  46187. //fileData = xhr.responseText;
  46188. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  46189. if (!_this.hasReachedQuota) {
  46190. // Open a transaction to the database
  46191. var transaction = _this.db.transaction([targetStore], "readwrite");
  46192. // the transaction could abort because of a QuotaExceededError error
  46193. transaction.onabort = function (event) {
  46194. try {
  46195. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46196. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46197. _this.hasReachedQuota = true;
  46198. }
  46199. }
  46200. catch (ex) { }
  46201. callback(fileData);
  46202. };
  46203. transaction.oncomplete = function (event) {
  46204. callback(fileData);
  46205. };
  46206. var newFile;
  46207. if (targetStore === "scenes") {
  46208. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  46209. }
  46210. else {
  46211. newFile = { textureUrl: url, data: fileData };
  46212. }
  46213. try {
  46214. // Put the scene into the database
  46215. var addRequest = transaction.objectStore(targetStore).put(newFile);
  46216. addRequest.onsuccess = function (event) {
  46217. };
  46218. addRequest.onerror = function (event) {
  46219. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  46220. };
  46221. }
  46222. catch (ex) {
  46223. callback(fileData);
  46224. }
  46225. }
  46226. else {
  46227. callback(fileData);
  46228. }
  46229. }
  46230. else {
  46231. callback();
  46232. }
  46233. }, false);
  46234. xhr.addEventListener("error", function (event) {
  46235. BABYLON.Tools.Error("error on XHR request.");
  46236. callback();
  46237. }, false);
  46238. xhr.send();
  46239. }
  46240. else {
  46241. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46242. callback();
  46243. }
  46244. };
  46245. return Database;
  46246. }());
  46247. Database.IsUASupportingBlobStorage = true;
  46248. Database.IDBStorageEnabled = true;
  46249. Database.parseURL = function (url) {
  46250. var a = document.createElement('a');
  46251. a.href = url;
  46252. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  46253. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  46254. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  46255. return absLocation;
  46256. };
  46257. Database.ReturnFullUrlLocation = function (url) {
  46258. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  46259. return (Database.parseURL(window.location.href) + url);
  46260. }
  46261. else {
  46262. return url;
  46263. }
  46264. };
  46265. BABYLON.Database = Database;
  46266. })(BABYLON || (BABYLON = {}));
  46267. //# sourceMappingURL=babylon.database.js.map
  46268. var BABYLON;
  46269. (function (BABYLON) {
  46270. var FresnelParameters = (function () {
  46271. function FresnelParameters() {
  46272. this._isEnabled = true;
  46273. this.leftColor = BABYLON.Color3.White();
  46274. this.rightColor = BABYLON.Color3.Black();
  46275. this.bias = 0;
  46276. this.power = 1;
  46277. }
  46278. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  46279. get: function () {
  46280. return this._isEnabled;
  46281. },
  46282. set: function (value) {
  46283. if (this._isEnabled === value) {
  46284. return;
  46285. }
  46286. this._isEnabled = value;
  46287. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  46288. },
  46289. enumerable: true,
  46290. configurable: true
  46291. });
  46292. FresnelParameters.prototype.clone = function () {
  46293. var newFresnelParameters = new FresnelParameters();
  46294. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  46295. return newFresnelParameters;
  46296. };
  46297. FresnelParameters.prototype.serialize = function () {
  46298. var serializationObject = {};
  46299. serializationObject.isEnabled = this.isEnabled;
  46300. serializationObject.leftColor = this.leftColor;
  46301. serializationObject.rightColor = this.rightColor;
  46302. serializationObject.bias = this.bias;
  46303. serializationObject.power = this.power;
  46304. return serializationObject;
  46305. };
  46306. FresnelParameters.Parse = function (parsedFresnelParameters) {
  46307. var fresnelParameters = new FresnelParameters();
  46308. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  46309. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  46310. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  46311. fresnelParameters.bias = parsedFresnelParameters.bias;
  46312. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  46313. return fresnelParameters;
  46314. };
  46315. return FresnelParameters;
  46316. }());
  46317. BABYLON.FresnelParameters = FresnelParameters;
  46318. })(BABYLON || (BABYLON = {}));
  46319. //# sourceMappingURL=babylon.fresnelParameters.js.map
  46320. var BABYLON;
  46321. (function (BABYLON) {
  46322. var MultiMaterial = (function (_super) {
  46323. __extends(MultiMaterial, _super);
  46324. function MultiMaterial(name, scene) {
  46325. var _this = _super.call(this, name, scene, true) || this;
  46326. _this.subMaterials = new Array();
  46327. scene.multiMaterials.push(_this);
  46328. return _this;
  46329. }
  46330. // Properties
  46331. MultiMaterial.prototype.getSubMaterial = function (index) {
  46332. if (index < 0 || index >= this.subMaterials.length) {
  46333. return this.getScene().defaultMaterial;
  46334. }
  46335. return this.subMaterials[index];
  46336. };
  46337. // Methods
  46338. MultiMaterial.prototype.getClassName = function () {
  46339. return "MultiMaterial";
  46340. };
  46341. MultiMaterial.prototype.isReady = function (mesh) {
  46342. for (var index = 0; index < this.subMaterials.length; index++) {
  46343. var subMaterial = this.subMaterials[index];
  46344. if (subMaterial) {
  46345. if (!this.subMaterials[index].isReady(mesh)) {
  46346. return false;
  46347. }
  46348. }
  46349. }
  46350. return true;
  46351. };
  46352. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  46353. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  46354. for (var index = 0; index < this.subMaterials.length; index++) {
  46355. var subMaterial = null;
  46356. if (cloneChildren) {
  46357. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  46358. }
  46359. else {
  46360. subMaterial = this.subMaterials[index];
  46361. }
  46362. newMultiMaterial.subMaterials.push(subMaterial);
  46363. }
  46364. return newMultiMaterial;
  46365. };
  46366. MultiMaterial.prototype.serialize = function () {
  46367. var serializationObject = {};
  46368. serializationObject.name = this.name;
  46369. serializationObject.id = this.id;
  46370. serializationObject.tags = BABYLON.Tags.GetTags(this);
  46371. serializationObject.materials = [];
  46372. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  46373. var subMat = this.subMaterials[matIndex];
  46374. if (subMat) {
  46375. serializationObject.materials.push(subMat.id);
  46376. }
  46377. else {
  46378. serializationObject.materials.push(null);
  46379. }
  46380. }
  46381. return serializationObject;
  46382. };
  46383. return MultiMaterial;
  46384. }(BABYLON.Material));
  46385. BABYLON.MultiMaterial = MultiMaterial;
  46386. })(BABYLON || (BABYLON = {}));
  46387. //# sourceMappingURL=babylon.multiMaterial.js.map
  46388. var BABYLON;
  46389. (function (BABYLON) {
  46390. var FreeCameraTouchInput = (function () {
  46391. function FreeCameraTouchInput() {
  46392. this._offsetX = null;
  46393. this._offsetY = null;
  46394. this._pointerCount = 0;
  46395. this._pointerPressed = [];
  46396. this.touchAngularSensibility = 200000.0;
  46397. this.touchMoveSensibility = 250.0;
  46398. }
  46399. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  46400. var _this = this;
  46401. var previousPosition;
  46402. if (this._pointerInput === undefined) {
  46403. this._onLostFocus = function (evt) {
  46404. _this._offsetX = null;
  46405. _this._offsetY = null;
  46406. };
  46407. this._pointerInput = function (p, s) {
  46408. var evt = p.event;
  46409. if (evt.pointerType === "mouse") {
  46410. return;
  46411. }
  46412. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  46413. if (!noPreventDefault) {
  46414. evt.preventDefault();
  46415. }
  46416. _this._pointerPressed.push(evt.pointerId);
  46417. if (_this._pointerPressed.length !== 1) {
  46418. return;
  46419. }
  46420. previousPosition = {
  46421. x: evt.clientX,
  46422. y: evt.clientY
  46423. };
  46424. }
  46425. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  46426. if (!noPreventDefault) {
  46427. evt.preventDefault();
  46428. }
  46429. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46430. if (index === -1) {
  46431. return;
  46432. }
  46433. _this._pointerPressed.splice(index, 1);
  46434. if (index != 0) {
  46435. return;
  46436. }
  46437. previousPosition = null;
  46438. _this._offsetX = null;
  46439. _this._offsetY = null;
  46440. }
  46441. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46442. if (!noPreventDefault) {
  46443. evt.preventDefault();
  46444. }
  46445. if (!previousPosition) {
  46446. return;
  46447. }
  46448. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46449. if (index != 0) {
  46450. return;
  46451. }
  46452. _this._offsetX = evt.clientX - previousPosition.x;
  46453. _this._offsetY = -(evt.clientY - previousPosition.y);
  46454. }
  46455. };
  46456. }
  46457. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46458. element.addEventListener("blur", this._onLostFocus);
  46459. };
  46460. FreeCameraTouchInput.prototype.detachControl = function (element) {
  46461. if (this._pointerInput && element) {
  46462. this.camera.getScene().onPointerObservable.remove(this._observer);
  46463. this._observer = null;
  46464. element.removeEventListener("blur", this._onLostFocus);
  46465. this._onLostFocus = null;
  46466. this._pointerPressed = [];
  46467. this._offsetX = null;
  46468. this._offsetY = null;
  46469. this._pointerCount = 0;
  46470. }
  46471. };
  46472. FreeCameraTouchInput.prototype.checkInputs = function () {
  46473. if (this._offsetX) {
  46474. var camera = this.camera;
  46475. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  46476. if (this._pointerPressed.length > 1) {
  46477. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  46478. }
  46479. else {
  46480. var speed = camera._computeLocalCameraSpeed();
  46481. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  46482. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  46483. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  46484. }
  46485. }
  46486. };
  46487. FreeCameraTouchInput.prototype.getTypeName = function () {
  46488. return "FreeCameraTouchInput";
  46489. };
  46490. FreeCameraTouchInput.prototype.getSimpleName = function () {
  46491. return "touch";
  46492. };
  46493. return FreeCameraTouchInput;
  46494. }());
  46495. __decorate([
  46496. BABYLON.serialize()
  46497. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  46498. __decorate([
  46499. BABYLON.serialize()
  46500. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  46501. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  46502. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  46503. })(BABYLON || (BABYLON = {}));
  46504. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  46505. /// <reference path="babylon.freeCamera.ts" />
  46506. var BABYLON;
  46507. (function (BABYLON) {
  46508. // We're mainly based on the logic defined into the FreeCamera code
  46509. var TouchCamera = (function (_super) {
  46510. __extends(TouchCamera, _super);
  46511. //-- end properties for backward compatibility for inputs
  46512. function TouchCamera(name, position, scene) {
  46513. var _this = _super.call(this, name, position, scene) || this;
  46514. _this.inputs.addTouch();
  46515. _this._setupInputs();
  46516. return _this;
  46517. }
  46518. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  46519. //-- Begin properties for backward compatibility for inputs
  46520. get: function () {
  46521. var touch = this.inputs.attached["touch"];
  46522. if (touch)
  46523. return touch.touchAngularSensibility;
  46524. },
  46525. set: function (value) {
  46526. var touch = this.inputs.attached["touch"];
  46527. if (touch)
  46528. touch.touchAngularSensibility = value;
  46529. },
  46530. enumerable: true,
  46531. configurable: true
  46532. });
  46533. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  46534. get: function () {
  46535. var touch = this.inputs.attached["touch"];
  46536. if (touch)
  46537. return touch.touchMoveSensibility;
  46538. },
  46539. set: function (value) {
  46540. var touch = this.inputs.attached["touch"];
  46541. if (touch)
  46542. touch.touchMoveSensibility = value;
  46543. },
  46544. enumerable: true,
  46545. configurable: true
  46546. });
  46547. TouchCamera.prototype.getClassName = function () {
  46548. return "TouchCamera";
  46549. };
  46550. TouchCamera.prototype._setupInputs = function () {
  46551. var mouse = this.inputs.attached["mouse"];
  46552. if (mouse) {
  46553. mouse.touchEnabled = false;
  46554. }
  46555. };
  46556. return TouchCamera;
  46557. }(BABYLON.FreeCamera));
  46558. BABYLON.TouchCamera = TouchCamera;
  46559. })(BABYLON || (BABYLON = {}));
  46560. //# sourceMappingURL=babylon.touchCamera.js.map
  46561. var BABYLON;
  46562. (function (BABYLON) {
  46563. var ProceduralTexture = (function (_super) {
  46564. __extends(ProceduralTexture, _super);
  46565. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  46566. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46567. if (isCube === void 0) { isCube = false; }
  46568. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  46569. _this.isCube = isCube;
  46570. _this.isEnabled = true;
  46571. _this._currentRefreshId = -1;
  46572. _this._refreshRate = 1;
  46573. _this._vertexBuffers = {};
  46574. _this._uniforms = new Array();
  46575. _this._samplers = new Array();
  46576. _this._textures = new Array();
  46577. _this._floats = new Array();
  46578. _this._floatsArrays = {};
  46579. _this._colors3 = new Array();
  46580. _this._colors4 = new Array();
  46581. _this._vectors2 = new Array();
  46582. _this._vectors3 = new Array();
  46583. _this._matrices = new Array();
  46584. _this._fallbackTextureUsed = false;
  46585. scene._proceduralTextures.push(_this);
  46586. _this.name = name;
  46587. _this.isRenderTarget = true;
  46588. _this._size = size;
  46589. _this._generateMipMaps = generateMipMaps;
  46590. _this.setFragment(fragment);
  46591. _this._fallbackTexture = fallbackTexture;
  46592. var engine = scene.getEngine();
  46593. if (isCube) {
  46594. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  46595. _this.setFloat("face", 0);
  46596. }
  46597. else {
  46598. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  46599. }
  46600. // VBO
  46601. var vertices = [];
  46602. vertices.push(1, 1);
  46603. vertices.push(-1, 1);
  46604. vertices.push(-1, -1);
  46605. vertices.push(1, -1);
  46606. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46607. // Indices
  46608. var indices = [];
  46609. indices.push(0);
  46610. indices.push(1);
  46611. indices.push(2);
  46612. indices.push(0);
  46613. indices.push(2);
  46614. indices.push(3);
  46615. _this._indexBuffer = engine.createIndexBuffer(indices);
  46616. return _this;
  46617. }
  46618. ProceduralTexture.prototype.reset = function () {
  46619. if (this._effect === undefined) {
  46620. return;
  46621. }
  46622. var engine = this.getScene().getEngine();
  46623. engine._releaseEffect(this._effect);
  46624. };
  46625. ProceduralTexture.prototype.isReady = function () {
  46626. var _this = this;
  46627. var engine = this.getScene().getEngine();
  46628. var shaders;
  46629. if (!this._fragment) {
  46630. return false;
  46631. }
  46632. if (this._fallbackTextureUsed) {
  46633. return true;
  46634. }
  46635. if (this._fragment.fragmentElement !== undefined) {
  46636. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  46637. }
  46638. else {
  46639. shaders = { vertex: "procedural", fragment: this._fragment };
  46640. }
  46641. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  46642. _this.releaseInternalTexture();
  46643. if (_this._fallbackTexture) {
  46644. _this._texture = _this._fallbackTexture._texture;
  46645. _this._texture.references++;
  46646. }
  46647. _this._fallbackTextureUsed = true;
  46648. });
  46649. return this._effect.isReady();
  46650. };
  46651. ProceduralTexture.prototype.resetRefreshCounter = function () {
  46652. this._currentRefreshId = -1;
  46653. };
  46654. ProceduralTexture.prototype.setFragment = function (fragment) {
  46655. this._fragment = fragment;
  46656. };
  46657. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  46658. get: function () {
  46659. return this._refreshRate;
  46660. },
  46661. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46662. set: function (value) {
  46663. this._refreshRate = value;
  46664. this.resetRefreshCounter();
  46665. },
  46666. enumerable: true,
  46667. configurable: true
  46668. });
  46669. ProceduralTexture.prototype._shouldRender = function () {
  46670. if (!this.isEnabled || !this.isReady() || !this._texture) {
  46671. return false;
  46672. }
  46673. if (this._fallbackTextureUsed) {
  46674. return false;
  46675. }
  46676. if (this._currentRefreshId === -1) {
  46677. this._currentRefreshId = 1;
  46678. return true;
  46679. }
  46680. if (this.refreshRate === this._currentRefreshId) {
  46681. this._currentRefreshId = 1;
  46682. return true;
  46683. }
  46684. this._currentRefreshId++;
  46685. return false;
  46686. };
  46687. ProceduralTexture.prototype.getRenderSize = function () {
  46688. return this._size;
  46689. };
  46690. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  46691. if (this._fallbackTextureUsed) {
  46692. return;
  46693. }
  46694. this.releaseInternalTexture();
  46695. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  46696. };
  46697. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  46698. if (this._uniforms.indexOf(uniformName) === -1) {
  46699. this._uniforms.push(uniformName);
  46700. }
  46701. };
  46702. ProceduralTexture.prototype.setTexture = function (name, texture) {
  46703. if (this._samplers.indexOf(name) === -1) {
  46704. this._samplers.push(name);
  46705. }
  46706. this._textures[name] = texture;
  46707. return this;
  46708. };
  46709. ProceduralTexture.prototype.setFloat = function (name, value) {
  46710. this._checkUniform(name);
  46711. this._floats[name] = value;
  46712. return this;
  46713. };
  46714. ProceduralTexture.prototype.setFloats = function (name, value) {
  46715. this._checkUniform(name);
  46716. this._floatsArrays[name] = value;
  46717. return this;
  46718. };
  46719. ProceduralTexture.prototype.setColor3 = function (name, value) {
  46720. this._checkUniform(name);
  46721. this._colors3[name] = value;
  46722. return this;
  46723. };
  46724. ProceduralTexture.prototype.setColor4 = function (name, value) {
  46725. this._checkUniform(name);
  46726. this._colors4[name] = value;
  46727. return this;
  46728. };
  46729. ProceduralTexture.prototype.setVector2 = function (name, value) {
  46730. this._checkUniform(name);
  46731. this._vectors2[name] = value;
  46732. return this;
  46733. };
  46734. ProceduralTexture.prototype.setVector3 = function (name, value) {
  46735. this._checkUniform(name);
  46736. this._vectors3[name] = value;
  46737. return this;
  46738. };
  46739. ProceduralTexture.prototype.setMatrix = function (name, value) {
  46740. this._checkUniform(name);
  46741. this._matrices[name] = value;
  46742. return this;
  46743. };
  46744. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  46745. var scene = this.getScene();
  46746. var engine = scene.getEngine();
  46747. // Render
  46748. engine.enableEffect(this._effect);
  46749. engine.setState(false);
  46750. // Texture
  46751. for (var name in this._textures) {
  46752. this._effect.setTexture(name, this._textures[name]);
  46753. }
  46754. // Float
  46755. for (name in this._floats) {
  46756. this._effect.setFloat(name, this._floats[name]);
  46757. }
  46758. // Floats
  46759. for (name in this._floatsArrays) {
  46760. this._effect.setArray(name, this._floatsArrays[name]);
  46761. }
  46762. // Color3
  46763. for (name in this._colors3) {
  46764. this._effect.setColor3(name, this._colors3[name]);
  46765. }
  46766. // Color4
  46767. for (name in this._colors4) {
  46768. var color = this._colors4[name];
  46769. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46770. }
  46771. // Vector2
  46772. for (name in this._vectors2) {
  46773. this._effect.setVector2(name, this._vectors2[name]);
  46774. }
  46775. // Vector3
  46776. for (name in this._vectors3) {
  46777. this._effect.setVector3(name, this._vectors3[name]);
  46778. }
  46779. // Matrix
  46780. for (name in this._matrices) {
  46781. this._effect.setMatrix(name, this._matrices[name]);
  46782. }
  46783. if (this.isCube) {
  46784. for (var face = 0; face < 6; face++) {
  46785. engine.bindFramebuffer(this._texture, face);
  46786. // VBOs
  46787. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46788. this._effect.setFloat("face", face);
  46789. // Clear
  46790. engine.clear(scene.clearColor, true, true, true);
  46791. // Draw order
  46792. engine.draw(true, 0, 6);
  46793. // Mipmaps
  46794. if (face === 5) {
  46795. engine.generateMipMapsForCubemap(this._texture);
  46796. }
  46797. }
  46798. }
  46799. else {
  46800. engine.bindFramebuffer(this._texture);
  46801. // VBOs
  46802. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46803. // Clear
  46804. engine.clear(scene.clearColor, true, true, true);
  46805. // Draw order
  46806. engine.draw(true, 0, 6);
  46807. }
  46808. // Unbind
  46809. engine.unBindFramebuffer(this._texture, this.isCube);
  46810. if (this.onGenerated) {
  46811. this.onGenerated();
  46812. }
  46813. };
  46814. ProceduralTexture.prototype.clone = function () {
  46815. var textureSize = this.getSize();
  46816. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  46817. // Base texture
  46818. newTexture.hasAlpha = this.hasAlpha;
  46819. newTexture.level = this.level;
  46820. // RenderTarget Texture
  46821. newTexture.coordinatesMode = this.coordinatesMode;
  46822. return newTexture;
  46823. };
  46824. ProceduralTexture.prototype.dispose = function () {
  46825. var index = this.getScene()._proceduralTextures.indexOf(this);
  46826. if (index >= 0) {
  46827. this.getScene()._proceduralTextures.splice(index, 1);
  46828. }
  46829. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46830. if (vertexBuffer) {
  46831. vertexBuffer.dispose();
  46832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46833. }
  46834. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  46835. this._indexBuffer = null;
  46836. }
  46837. _super.prototype.dispose.call(this);
  46838. };
  46839. return ProceduralTexture;
  46840. }(BABYLON.Texture));
  46841. BABYLON.ProceduralTexture = ProceduralTexture;
  46842. })(BABYLON || (BABYLON = {}));
  46843. //# sourceMappingURL=babylon.proceduralTexture.js.map
  46844. /// <reference path="babylon.proceduralTexture.ts" />
  46845. var BABYLON;
  46846. (function (BABYLON) {
  46847. var CustomProceduralTexture = (function (_super) {
  46848. __extends(CustomProceduralTexture, _super);
  46849. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  46850. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  46851. _this._animate = true;
  46852. _this._time = 0;
  46853. _this._texturePath = texturePath;
  46854. //Try to load json
  46855. _this.loadJson(texturePath);
  46856. _this.refreshRate = 1;
  46857. return _this;
  46858. }
  46859. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  46860. var _this = this;
  46861. var that = this;
  46862. function noConfigFile() {
  46863. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  46864. try {
  46865. that.setFragment(that._texturePath);
  46866. }
  46867. catch (ex) {
  46868. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  46869. }
  46870. }
  46871. var configFileUrl = jsonUrl + "/config.json";
  46872. var xhr = new XMLHttpRequest();
  46873. xhr.open("GET", configFileUrl, true);
  46874. xhr.addEventListener("load", function () {
  46875. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  46876. try {
  46877. _this._config = JSON.parse(xhr.response);
  46878. _this.updateShaderUniforms();
  46879. _this.updateTextures();
  46880. _this.setFragment(_this._texturePath + "/custom");
  46881. _this._animate = _this._config.animate;
  46882. _this.refreshRate = _this._config.refreshrate;
  46883. }
  46884. catch (ex) {
  46885. noConfigFile();
  46886. }
  46887. }
  46888. else {
  46889. noConfigFile();
  46890. }
  46891. }, false);
  46892. xhr.addEventListener("error", function () {
  46893. noConfigFile();
  46894. }, false);
  46895. try {
  46896. xhr.send();
  46897. }
  46898. catch (ex) {
  46899. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  46900. }
  46901. };
  46902. CustomProceduralTexture.prototype.isReady = function () {
  46903. if (!_super.prototype.isReady.call(this)) {
  46904. return false;
  46905. }
  46906. for (var name in this._textures) {
  46907. var texture = this._textures[name];
  46908. if (!texture.isReady()) {
  46909. return false;
  46910. }
  46911. }
  46912. return true;
  46913. };
  46914. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  46915. if (this._animate) {
  46916. this._time += this.getScene().getAnimationRatio() * 0.03;
  46917. this.updateShaderUniforms();
  46918. }
  46919. _super.prototype.render.call(this, useCameraPostProcess);
  46920. };
  46921. CustomProceduralTexture.prototype.updateTextures = function () {
  46922. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  46923. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  46924. }
  46925. };
  46926. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  46927. if (this._config) {
  46928. for (var j = 0; j < this._config.uniforms.length; j++) {
  46929. var uniform = this._config.uniforms[j];
  46930. switch (uniform.type) {
  46931. case "float":
  46932. this.setFloat(uniform.name, uniform.value);
  46933. break;
  46934. case "color3":
  46935. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  46936. break;
  46937. case "color4":
  46938. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  46939. break;
  46940. case "vector2":
  46941. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  46942. break;
  46943. case "vector3":
  46944. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  46945. break;
  46946. }
  46947. }
  46948. }
  46949. this.setFloat("time", this._time);
  46950. };
  46951. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  46952. get: function () {
  46953. return this._animate;
  46954. },
  46955. set: function (value) {
  46956. this._animate = value;
  46957. },
  46958. enumerable: true,
  46959. configurable: true
  46960. });
  46961. return CustomProceduralTexture;
  46962. }(BABYLON.ProceduralTexture));
  46963. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  46964. })(BABYLON || (BABYLON = {}));
  46965. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  46966. var BABYLON;
  46967. (function (BABYLON) {
  46968. var FreeCameraGamepadInput = (function () {
  46969. function FreeCameraGamepadInput() {
  46970. this.gamepadAngularSensibility = 200;
  46971. this.gamepadMoveSensibility = 40;
  46972. // private members
  46973. this._cameraTransform = BABYLON.Matrix.Identity();
  46974. this._deltaTransform = BABYLON.Vector3.Zero();
  46975. this._vector3 = BABYLON.Vector3.Zero();
  46976. this._vector2 = BABYLON.Vector2.Zero();
  46977. }
  46978. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  46979. var _this = this;
  46980. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  46981. };
  46982. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  46983. if (this._gamepads) {
  46984. this._gamepads.dispose();
  46985. }
  46986. this.gamepad = null;
  46987. };
  46988. FreeCameraGamepadInput.prototype.checkInputs = function () {
  46989. if (this.gamepad && this.gamepad.leftStick) {
  46990. var camera = this.camera;
  46991. var LSValues = this.gamepad.leftStick;
  46992. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  46993. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  46994. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  46995. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  46996. var RSValues = this.gamepad.rightStick;
  46997. if (RSValues) {
  46998. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  46999. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  47000. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  47001. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  47002. }
  47003. else {
  47004. RSValues = { x: 0, y: 0 };
  47005. }
  47006. if (!camera.rotationQuaternion) {
  47007. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  47008. }
  47009. else {
  47010. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  47011. }
  47012. var speed = camera._computeLocalCameraSpeed() * 50.0;
  47013. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  47014. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  47015. camera.cameraDirection.addInPlace(this._deltaTransform);
  47016. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  47017. camera.cameraRotation.addInPlace(this._vector2);
  47018. }
  47019. };
  47020. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47021. // Only the first gamepad found can control the camera
  47022. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47023. // prioritize XBOX gamepads.
  47024. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47025. this.gamepad = gamepad;
  47026. }
  47027. }
  47028. };
  47029. FreeCameraGamepadInput.prototype.getTypeName = function () {
  47030. return "FreeCameraGamepadInput";
  47031. };
  47032. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  47033. return "gamepad";
  47034. };
  47035. return FreeCameraGamepadInput;
  47036. }());
  47037. __decorate([
  47038. BABYLON.serialize()
  47039. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  47040. __decorate([
  47041. BABYLON.serialize()
  47042. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  47043. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  47044. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  47045. })(BABYLON || (BABYLON = {}));
  47046. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  47047. var BABYLON;
  47048. (function (BABYLON) {
  47049. var ArcRotateCameraGamepadInput = (function () {
  47050. function ArcRotateCameraGamepadInput() {
  47051. this.gamepadRotationSensibility = 80;
  47052. this.gamepadMoveSensibility = 40;
  47053. }
  47054. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47055. var _this = this;
  47056. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47057. };
  47058. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  47059. if (this._gamepads) {
  47060. this._gamepads.dispose();
  47061. }
  47062. this.gamepad = null;
  47063. };
  47064. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  47065. if (this.gamepad) {
  47066. var camera = this.camera;
  47067. var RSValues = this.gamepad.rightStick;
  47068. if (RSValues) {
  47069. if (RSValues.x != 0) {
  47070. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  47071. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  47072. camera.inertialAlphaOffset += normalizedRX;
  47073. }
  47074. }
  47075. if (RSValues.y != 0) {
  47076. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  47077. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  47078. camera.inertialBetaOffset += normalizedRY;
  47079. }
  47080. }
  47081. }
  47082. var LSValues = this.gamepad.leftStick;
  47083. if (LSValues && LSValues.y != 0) {
  47084. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47085. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  47086. this.camera.inertialRadiusOffset -= normalizedLY;
  47087. }
  47088. }
  47089. }
  47090. };
  47091. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47092. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47093. // prioritize XBOX gamepads.
  47094. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47095. this.gamepad = gamepad;
  47096. }
  47097. }
  47098. };
  47099. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  47100. return "ArcRotateCameraGamepadInput";
  47101. };
  47102. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  47103. return "gamepad";
  47104. };
  47105. return ArcRotateCameraGamepadInput;
  47106. }());
  47107. __decorate([
  47108. BABYLON.serialize()
  47109. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  47110. __decorate([
  47111. BABYLON.serialize()
  47112. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  47113. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  47114. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  47115. })(BABYLON || (BABYLON = {}));
  47116. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  47117. var BABYLON;
  47118. (function (BABYLON) {
  47119. var Gamepads = (function () {
  47120. function Gamepads(ongamedpadconnected) {
  47121. var _this = this;
  47122. this.babylonGamepads = [];
  47123. this.oneGamepadConnected = false;
  47124. this.isMonitoring = false;
  47125. this.gamepadEventSupported = 'GamepadEvent' in window;
  47126. this.gamepadSupport = (navigator.getGamepads ||
  47127. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  47128. this._callbackGamepadConnected = ongamedpadconnected;
  47129. if (this.gamepadSupport) {
  47130. //first add already-connected gamepads
  47131. this._updateGamepadObjects();
  47132. if (this.babylonGamepads.length) {
  47133. this._startMonitoringGamepads();
  47134. }
  47135. // Checking if the gamepad connected event is supported (like in Firefox)
  47136. if (this.gamepadEventSupported) {
  47137. this._onGamepadConnectedEvent = function (evt) {
  47138. _this._onGamepadConnected(evt.gamepad);
  47139. };
  47140. this._onGamepadDisonnectedEvent = function (evt) {
  47141. _this._onGamepadDisconnected(evt);
  47142. };
  47143. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47144. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47145. }
  47146. else {
  47147. this._startMonitoringGamepads();
  47148. }
  47149. }
  47150. }
  47151. Gamepads.prototype.dispose = function () {
  47152. if (Gamepads.gamepadDOMInfo) {
  47153. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47154. }
  47155. if (this._onGamepadConnectedEvent) {
  47156. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47157. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47158. this._onGamepadConnectedEvent = null;
  47159. this._onGamepadDisonnectedEvent = null;
  47160. }
  47161. };
  47162. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  47163. var newGamepad = this._addNewGamepad(gamepad);
  47164. if (this._callbackGamepadConnected)
  47165. this._callbackGamepadConnected(newGamepad);
  47166. this._startMonitoringGamepads();
  47167. };
  47168. Gamepads.prototype._addNewGamepad = function (gamepad) {
  47169. if (!this.oneGamepadConnected) {
  47170. this.oneGamepadConnected = true;
  47171. if (Gamepads.gamepadDOMInfo) {
  47172. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47173. Gamepads.gamepadDOMInfo = null;
  47174. }
  47175. }
  47176. var newGamepad;
  47177. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  47178. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  47179. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  47180. }
  47181. else if (gamepad.pose) {
  47182. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  47183. }
  47184. else {
  47185. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  47186. }
  47187. this.babylonGamepads.push(newGamepad);
  47188. return newGamepad;
  47189. };
  47190. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  47191. // Remove the gamepad from the list of gamepads to monitor.
  47192. for (var i in this.babylonGamepads) {
  47193. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  47194. this.babylonGamepads.splice(+i, 1);
  47195. break;
  47196. }
  47197. }
  47198. // If no gamepads are left, stop the polling loop.
  47199. if (this.babylonGamepads.length == 0) {
  47200. this._stopMonitoringGamepads();
  47201. }
  47202. };
  47203. Gamepads.prototype._startMonitoringGamepads = function () {
  47204. if (!this.isMonitoring) {
  47205. this.isMonitoring = true;
  47206. this._checkGamepadsStatus();
  47207. }
  47208. };
  47209. Gamepads.prototype._stopMonitoringGamepads = function () {
  47210. this.isMonitoring = false;
  47211. };
  47212. Gamepads.prototype._checkGamepadsStatus = function () {
  47213. var _this = this;
  47214. // updating gamepad objects
  47215. this._updateGamepadObjects();
  47216. for (var i in this.babylonGamepads) {
  47217. this.babylonGamepads[i].update();
  47218. }
  47219. if (this.isMonitoring) {
  47220. if (window.requestAnimationFrame) {
  47221. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47222. }
  47223. else if (window.mozRequestAnimationFrame) {
  47224. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47225. }
  47226. else if (window.webkitRequestAnimationFrame) {
  47227. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47228. }
  47229. }
  47230. };
  47231. // This function is called only on Chrome, which does not yet support
  47232. // connection/disconnection events, but requires you to monitor
  47233. // an array for changes.
  47234. Gamepads.prototype._updateGamepadObjects = function () {
  47235. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47236. for (var i = 0; i < gamepads.length; i++) {
  47237. if (gamepads[i]) {
  47238. if (!(gamepads[i].index in this.babylonGamepads)) {
  47239. var newGamepad = this._addNewGamepad(gamepads[i]);
  47240. if (this._callbackGamepadConnected) {
  47241. this._callbackGamepadConnected(newGamepad);
  47242. }
  47243. }
  47244. else {
  47245. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47246. }
  47247. }
  47248. }
  47249. };
  47250. return Gamepads;
  47251. }());
  47252. BABYLON.Gamepads = Gamepads;
  47253. var StickValues = (function () {
  47254. function StickValues(x, y) {
  47255. this.x = x;
  47256. this.y = y;
  47257. }
  47258. return StickValues;
  47259. }());
  47260. BABYLON.StickValues = StickValues;
  47261. var Gamepad = (function () {
  47262. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47263. if (leftStickX === void 0) { leftStickX = 0; }
  47264. if (leftStickY === void 0) { leftStickY = 1; }
  47265. if (rightStickX === void 0) { rightStickX = 2; }
  47266. if (rightStickY === void 0) { rightStickY = 3; }
  47267. this.id = id;
  47268. this.index = index;
  47269. this.browserGamepad = browserGamepad;
  47270. this.type = Gamepad.GAMEPAD;
  47271. this._leftStickAxisX = leftStickX;
  47272. this._leftStickAxisY = leftStickY;
  47273. this._rightStickAxisX = rightStickX;
  47274. this._rightStickAxisY = rightStickY;
  47275. if (this.browserGamepad.axes.length >= 2) {
  47276. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47277. }
  47278. if (this.browserGamepad.axes.length >= 4) {
  47279. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47280. }
  47281. }
  47282. Gamepad.prototype.onleftstickchanged = function (callback) {
  47283. this._onleftstickchanged = callback;
  47284. };
  47285. Gamepad.prototype.onrightstickchanged = function (callback) {
  47286. this._onrightstickchanged = callback;
  47287. };
  47288. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47289. get: function () {
  47290. return this._leftStick;
  47291. },
  47292. set: function (newValues) {
  47293. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47294. this._onleftstickchanged(newValues);
  47295. }
  47296. this._leftStick = newValues;
  47297. },
  47298. enumerable: true,
  47299. configurable: true
  47300. });
  47301. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47302. get: function () {
  47303. return this._rightStick;
  47304. },
  47305. set: function (newValues) {
  47306. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47307. this._onrightstickchanged(newValues);
  47308. }
  47309. this._rightStick = newValues;
  47310. },
  47311. enumerable: true,
  47312. configurable: true
  47313. });
  47314. Gamepad.prototype.update = function () {
  47315. if (this._leftStick) {
  47316. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47317. }
  47318. if (this._rightStick) {
  47319. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47320. }
  47321. };
  47322. return Gamepad;
  47323. }());
  47324. Gamepad.GAMEPAD = 0;
  47325. Gamepad.GENERIC = 1;
  47326. Gamepad.XBOX = 2;
  47327. Gamepad.POSE_ENABLED = 3;
  47328. BABYLON.Gamepad = Gamepad;
  47329. var GenericPad = (function (_super) {
  47330. __extends(GenericPad, _super);
  47331. function GenericPad(id, index, gamepad) {
  47332. var _this = _super.call(this, id, index, gamepad) || this;
  47333. _this.id = id;
  47334. _this.index = index;
  47335. _this.gamepad = gamepad;
  47336. _this.type = Gamepad.GENERIC;
  47337. _this._buttons = new Array(gamepad.buttons.length);
  47338. return _this;
  47339. }
  47340. GenericPad.prototype.onbuttondown = function (callback) {
  47341. this._onbuttondown = callback;
  47342. };
  47343. GenericPad.prototype.onbuttonup = function (callback) {
  47344. this._onbuttonup = callback;
  47345. };
  47346. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47347. if (newValue !== currentValue) {
  47348. if (this._onbuttondown && newValue === 1) {
  47349. this._onbuttondown(buttonIndex);
  47350. }
  47351. if (this._onbuttonup && newValue === 0) {
  47352. this._onbuttonup(buttonIndex);
  47353. }
  47354. }
  47355. return newValue;
  47356. };
  47357. GenericPad.prototype.update = function () {
  47358. _super.prototype.update.call(this);
  47359. for (var index = 0; index < this._buttons.length; index++) {
  47360. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  47361. }
  47362. };
  47363. return GenericPad;
  47364. }(Gamepad));
  47365. BABYLON.GenericPad = GenericPad;
  47366. var Xbox360Button;
  47367. (function (Xbox360Button) {
  47368. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47369. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47370. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47371. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47372. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47373. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47374. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47375. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47376. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47377. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47378. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47379. var Xbox360Dpad;
  47380. (function (Xbox360Dpad) {
  47381. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47382. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47383. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47384. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47385. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47386. var Xbox360Pad = (function (_super) {
  47387. __extends(Xbox360Pad, _super);
  47388. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47389. if (xboxOne === void 0) { xboxOne = false; }
  47390. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47391. _this._leftTrigger = 0;
  47392. _this._rightTrigger = 0;
  47393. _this._buttonA = 0;
  47394. _this._buttonB = 0;
  47395. _this._buttonX = 0;
  47396. _this._buttonY = 0;
  47397. _this._buttonBack = 0;
  47398. _this._buttonStart = 0;
  47399. _this._buttonLB = 0;
  47400. _this._buttonRB = 0;
  47401. _this._buttonLeftStick = 0;
  47402. _this._buttonRightStick = 0;
  47403. _this._dPadUp = 0;
  47404. _this._dPadDown = 0;
  47405. _this._dPadLeft = 0;
  47406. _this._dPadRight = 0;
  47407. _this._isXboxOnePad = false;
  47408. _this.type = Gamepad.XBOX;
  47409. _this._isXboxOnePad = xboxOne;
  47410. return _this;
  47411. }
  47412. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47413. this._onlefttriggerchanged = callback;
  47414. };
  47415. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47416. this._onrighttriggerchanged = callback;
  47417. };
  47418. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47419. get: function () {
  47420. return this._leftTrigger;
  47421. },
  47422. set: function (newValue) {
  47423. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47424. this._onlefttriggerchanged(newValue);
  47425. }
  47426. this._leftTrigger = newValue;
  47427. },
  47428. enumerable: true,
  47429. configurable: true
  47430. });
  47431. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47432. get: function () {
  47433. return this._rightTrigger;
  47434. },
  47435. set: function (newValue) {
  47436. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47437. this._onrighttriggerchanged(newValue);
  47438. }
  47439. this._rightTrigger = newValue;
  47440. },
  47441. enumerable: true,
  47442. configurable: true
  47443. });
  47444. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47445. this._onbuttondown = callback;
  47446. };
  47447. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47448. this._onbuttonup = callback;
  47449. };
  47450. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47451. this._ondpaddown = callback;
  47452. };
  47453. Xbox360Pad.prototype.ondpadup = function (callback) {
  47454. this._ondpadup = callback;
  47455. };
  47456. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47457. if (newValue !== currentValue) {
  47458. if (this._onbuttondown && newValue === 1) {
  47459. this._onbuttondown(buttonType);
  47460. }
  47461. if (this._onbuttonup && newValue === 0) {
  47462. this._onbuttonup(buttonType);
  47463. }
  47464. }
  47465. return newValue;
  47466. };
  47467. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47468. if (newValue !== currentValue) {
  47469. if (this._ondpaddown && newValue === 1) {
  47470. this._ondpaddown(buttonType);
  47471. }
  47472. if (this._ondpadup && newValue === 0) {
  47473. this._ondpadup(buttonType);
  47474. }
  47475. }
  47476. return newValue;
  47477. };
  47478. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47479. get: function () {
  47480. return this._buttonA;
  47481. },
  47482. set: function (value) {
  47483. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47484. },
  47485. enumerable: true,
  47486. configurable: true
  47487. });
  47488. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47489. get: function () {
  47490. return this._buttonB;
  47491. },
  47492. set: function (value) {
  47493. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47494. },
  47495. enumerable: true,
  47496. configurable: true
  47497. });
  47498. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47499. get: function () {
  47500. return this._buttonX;
  47501. },
  47502. set: function (value) {
  47503. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47504. },
  47505. enumerable: true,
  47506. configurable: true
  47507. });
  47508. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47509. get: function () {
  47510. return this._buttonY;
  47511. },
  47512. set: function (value) {
  47513. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47514. },
  47515. enumerable: true,
  47516. configurable: true
  47517. });
  47518. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47519. get: function () {
  47520. return this._buttonStart;
  47521. },
  47522. set: function (value) {
  47523. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47524. },
  47525. enumerable: true,
  47526. configurable: true
  47527. });
  47528. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47529. get: function () {
  47530. return this._buttonBack;
  47531. },
  47532. set: function (value) {
  47533. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47534. },
  47535. enumerable: true,
  47536. configurable: true
  47537. });
  47538. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47539. get: function () {
  47540. return this._buttonLB;
  47541. },
  47542. set: function (value) {
  47543. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47544. },
  47545. enumerable: true,
  47546. configurable: true
  47547. });
  47548. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47549. get: function () {
  47550. return this._buttonRB;
  47551. },
  47552. set: function (value) {
  47553. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47554. },
  47555. enumerable: true,
  47556. configurable: true
  47557. });
  47558. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47559. get: function () {
  47560. return this._buttonLeftStick;
  47561. },
  47562. set: function (value) {
  47563. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47569. get: function () {
  47570. return this._buttonRightStick;
  47571. },
  47572. set: function (value) {
  47573. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47574. },
  47575. enumerable: true,
  47576. configurable: true
  47577. });
  47578. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47579. get: function () {
  47580. return this._dPadUp;
  47581. },
  47582. set: function (value) {
  47583. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47584. },
  47585. enumerable: true,
  47586. configurable: true
  47587. });
  47588. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47589. get: function () {
  47590. return this._dPadDown;
  47591. },
  47592. set: function (value) {
  47593. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47594. },
  47595. enumerable: true,
  47596. configurable: true
  47597. });
  47598. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47599. get: function () {
  47600. return this._dPadLeft;
  47601. },
  47602. set: function (value) {
  47603. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47609. get: function () {
  47610. return this._dPadRight;
  47611. },
  47612. set: function (value) {
  47613. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47614. },
  47615. enumerable: true,
  47616. configurable: true
  47617. });
  47618. Xbox360Pad.prototype.update = function () {
  47619. _super.prototype.update.call(this);
  47620. if (this._isXboxOnePad) {
  47621. this.buttonA = this.browserGamepad.buttons[0].value;
  47622. this.buttonB = this.browserGamepad.buttons[1].value;
  47623. this.buttonX = this.browserGamepad.buttons[2].value;
  47624. this.buttonY = this.browserGamepad.buttons[3].value;
  47625. this.buttonLB = this.browserGamepad.buttons[4].value;
  47626. this.buttonRB = this.browserGamepad.buttons[5].value;
  47627. this.leftTrigger = this.browserGamepad.axes[2];
  47628. this.rightTrigger = this.browserGamepad.axes[5];
  47629. this.buttonBack = this.browserGamepad.buttons[9].value;
  47630. this.buttonStart = this.browserGamepad.buttons[8].value;
  47631. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47632. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47633. this.dPadUp = this.browserGamepad.buttons[11].value;
  47634. this.dPadDown = this.browserGamepad.buttons[12].value;
  47635. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47636. this.dPadRight = this.browserGamepad.buttons[14].value;
  47637. }
  47638. else {
  47639. this.buttonA = this.browserGamepad.buttons[0].value;
  47640. this.buttonB = this.browserGamepad.buttons[1].value;
  47641. this.buttonX = this.browserGamepad.buttons[2].value;
  47642. this.buttonY = this.browserGamepad.buttons[3].value;
  47643. this.buttonLB = this.browserGamepad.buttons[4].value;
  47644. this.buttonRB = this.browserGamepad.buttons[5].value;
  47645. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47646. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47647. this.buttonBack = this.browserGamepad.buttons[8].value;
  47648. this.buttonStart = this.browserGamepad.buttons[9].value;
  47649. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47650. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47651. this.dPadUp = this.browserGamepad.buttons[12].value;
  47652. this.dPadDown = this.browserGamepad.buttons[13].value;
  47653. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47654. this.dPadRight = this.browserGamepad.buttons[15].value;
  47655. }
  47656. };
  47657. return Xbox360Pad;
  47658. }(Gamepad));
  47659. BABYLON.Xbox360Pad = Xbox360Pad;
  47660. })(BABYLON || (BABYLON = {}));
  47661. //# sourceMappingURL=babylon.gamepads.js.map
  47662. var BABYLON;
  47663. (function (BABYLON) {
  47664. var PoseEnabledControllerType;
  47665. (function (PoseEnabledControllerType) {
  47666. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  47667. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  47668. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  47669. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  47670. var PoseEnabledControllerHelper = (function () {
  47671. function PoseEnabledControllerHelper() {
  47672. }
  47673. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  47674. // for now, only Oculus and Vive are supported
  47675. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  47676. return new OculusTouchController(vrGamepad);
  47677. }
  47678. else {
  47679. return new ViveController(vrGamepad);
  47680. }
  47681. };
  47682. return PoseEnabledControllerHelper;
  47683. }());
  47684. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  47685. var PoseEnabledController = (function (_super) {
  47686. __extends(PoseEnabledController, _super);
  47687. function PoseEnabledController(vrGamepad) {
  47688. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  47689. _this.vrGamepad = vrGamepad;
  47690. _this.deviceScaleFactor = 1;
  47691. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  47692. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  47693. _this.controllerType = PoseEnabledControllerType.GENERIC;
  47694. _this.position = BABYLON.Vector3.Zero();
  47695. _this.rotationQuaternion = new BABYLON.Quaternion();
  47696. _this.devicePosition = BABYLON.Vector3.Zero();
  47697. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  47698. _this._calculatedPosition = BABYLON.Vector3.Zero();
  47699. _this._calculatedRotation = new BABYLON.Quaternion();
  47700. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  47701. return _this;
  47702. }
  47703. PoseEnabledController.prototype.update = function () {
  47704. _super.prototype.update.call(this);
  47705. var pose = this.vrGamepad.pose;
  47706. this.updateFromDevice(pose);
  47707. if (this._mesh) {
  47708. this._mesh.position.copyFrom(this._calculatedPosition);
  47709. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  47710. }
  47711. };
  47712. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  47713. if (poseData) {
  47714. this.rawPose = poseData;
  47715. if (poseData.position) {
  47716. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  47717. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  47718. this.devicePosition.z *= -1;
  47719. }
  47720. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  47721. this._calculatedPosition.addInPlace(this.position);
  47722. }
  47723. if (poseData.orientation) {
  47724. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  47725. if (this._mesh) {
  47726. if (this._mesh.getScene().useRightHandedSystem) {
  47727. this.deviceRotationQuaternion.z *= -1;
  47728. this.deviceRotationQuaternion.w *= -1;
  47729. }
  47730. else {
  47731. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  47732. }
  47733. }
  47734. // if the camera is set, rotate to the camera's rotation
  47735. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  47736. }
  47737. }
  47738. };
  47739. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  47740. if (this._mesh) {
  47741. this._mesh.parent = undefined;
  47742. }
  47743. this._mesh = mesh;
  47744. if (this._poseControlledCamera) {
  47745. this._mesh.parent = this._poseControlledCamera;
  47746. }
  47747. if (!this._mesh.rotationQuaternion) {
  47748. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  47749. }
  47750. };
  47751. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  47752. this._poseControlledCamera = camera;
  47753. if (this._mesh) {
  47754. this._mesh.parent = this._poseControlledCamera;
  47755. }
  47756. };
  47757. PoseEnabledController.prototype.detachMesh = function () {
  47758. this._mesh = undefined;
  47759. };
  47760. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  47761. get: function () {
  47762. return this._mesh;
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. PoseEnabledController.prototype.getForwardRay = function (length) {
  47768. if (length === void 0) { length = 100; }
  47769. if (!this.mesh) {
  47770. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  47771. }
  47772. var m = this.mesh.getWorldMatrix();
  47773. var origin = m.getTranslation();
  47774. var forward = new BABYLON.Vector3(0, 0, -1);
  47775. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  47776. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  47777. return new BABYLON.Ray(origin, direction, length);
  47778. };
  47779. return PoseEnabledController;
  47780. }(BABYLON.Gamepad));
  47781. BABYLON.PoseEnabledController = PoseEnabledController;
  47782. var WebVRController = (function (_super) {
  47783. __extends(WebVRController, _super);
  47784. function WebVRController(vrGamepad) {
  47785. var _this = _super.call(this, vrGamepad) || this;
  47786. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  47787. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  47788. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  47789. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  47790. _this.onPadStateChangedObservable = new BABYLON.Observable();
  47791. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  47792. _this.pad = { x: 0, y: 0 };
  47793. // avoid GC, store state in a tmp object
  47794. _this._changes = {
  47795. pressChanged: false,
  47796. touchChanged: false,
  47797. valueChanged: false,
  47798. changed: false
  47799. };
  47800. _this._buttons = new Array(vrGamepad.buttons.length);
  47801. _this.hand = vrGamepad.hand;
  47802. return _this;
  47803. }
  47804. WebVRController.prototype.onButtonStateChange = function (callback) {
  47805. this._onButtonStateChange = callback;
  47806. };
  47807. WebVRController.prototype.update = function () {
  47808. _super.prototype.update.call(this);
  47809. for (var index = 0; index < this._buttons.length; index++) {
  47810. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  47811. }
  47812. ;
  47813. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  47814. this.pad.x = this.leftStick.x;
  47815. this.pad.y = this.leftStick.y;
  47816. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  47817. }
  47818. };
  47819. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  47820. if (!currentState) {
  47821. this._buttons[buttonIndex] = {
  47822. pressed: newState.pressed,
  47823. touched: newState.touched,
  47824. value: newState.value
  47825. };
  47826. return;
  47827. }
  47828. this._checkChanges(newState, currentState);
  47829. if (this._changes.changed) {
  47830. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  47831. this.handleButtonChange(buttonIndex, newState, this._changes);
  47832. }
  47833. this._buttons[buttonIndex].pressed = newState.pressed;
  47834. this._buttons[buttonIndex].touched = newState.touched;
  47835. // oculus triggers are never 0, thou not touched.
  47836. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  47837. };
  47838. WebVRController.prototype._checkChanges = function (newState, currentState) {
  47839. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  47840. this._changes.touchChanged = newState.touched !== currentState.touched;
  47841. this._changes.valueChanged = newState.value !== currentState.value;
  47842. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  47843. return this._changes;
  47844. };
  47845. return WebVRController;
  47846. }(PoseEnabledController));
  47847. BABYLON.WebVRController = WebVRController;
  47848. var OculusTouchController = (function (_super) {
  47849. __extends(OculusTouchController, _super);
  47850. function OculusTouchController(vrGamepad) {
  47851. var _this = _super.call(this, vrGamepad) || this;
  47852. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  47853. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  47854. _this.controllerType = PoseEnabledControllerType.OCULUS;
  47855. return _this;
  47856. }
  47857. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  47858. var _this = this;
  47859. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  47860. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  47861. /*
  47862. Parent Mesh name: oculus_touch_left
  47863. - body
  47864. - trigger
  47865. - thumbstick
  47866. - grip
  47867. - button_y
  47868. - button_x
  47869. - button_enter
  47870. */
  47871. _this._defaultModel = newMeshes[1];
  47872. if (meshLoaded) {
  47873. meshLoaded(_this._defaultModel);
  47874. }
  47875. _this.attachToMesh(_this._defaultModel);
  47876. });
  47877. };
  47878. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  47879. // helper getters for left and right hand.
  47880. get: function () {
  47881. if (this.hand === 'right') {
  47882. return this.onMainButtonStateChangedObservable;
  47883. }
  47884. else {
  47885. throw new Error('No A button on left hand');
  47886. }
  47887. },
  47888. enumerable: true,
  47889. configurable: true
  47890. });
  47891. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  47892. get: function () {
  47893. if (this.hand === 'right') {
  47894. return this.onSecondaryButtonStateChangedObservable;
  47895. }
  47896. else {
  47897. throw new Error('No B button on left hand');
  47898. }
  47899. },
  47900. enumerable: true,
  47901. configurable: true
  47902. });
  47903. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  47904. get: function () {
  47905. if (this.hand === 'left') {
  47906. return this.onMainButtonStateChangedObservable;
  47907. }
  47908. else {
  47909. throw new Error('No X button on right hand');
  47910. }
  47911. },
  47912. enumerable: true,
  47913. configurable: true
  47914. });
  47915. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  47916. get: function () {
  47917. if (this.hand === 'left') {
  47918. return this.onSecondaryButtonStateChangedObservable;
  47919. }
  47920. else {
  47921. throw new Error('No Y button on right hand');
  47922. }
  47923. },
  47924. enumerable: true,
  47925. configurable: true
  47926. });
  47927. /*
  47928. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  47929. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  47930. 2) secondary trigger (same)
  47931. 3) A (right) X (left), touch, pressed = value
  47932. 4) B / Y
  47933. 5) thumb rest
  47934. */
  47935. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  47936. var notifyObject = state; //{ state: state, changes: changes };
  47937. var triggerDirection = this.hand === 'right' ? -1 : 1;
  47938. switch (buttonIdx) {
  47939. case 0:
  47940. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  47941. return;
  47942. case 1:
  47943. if (this._defaultModel) {
  47944. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  47945. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  47946. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  47947. }
  47948. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  47949. return;
  47950. case 2:
  47951. if (this._defaultModel) {
  47952. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  47953. }
  47954. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  47955. return;
  47956. case 3:
  47957. if (this._defaultModel) {
  47958. if (notifyObject.pressed) {
  47959. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  47960. }
  47961. else {
  47962. (this._defaultModel.getChildren()[1]).position.y = 0;
  47963. }
  47964. }
  47965. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  47966. return;
  47967. case 4:
  47968. if (this._defaultModel) {
  47969. if (notifyObject.pressed) {
  47970. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  47971. }
  47972. else {
  47973. (this._defaultModel.getChildren()[2]).position.y = 0;
  47974. }
  47975. }
  47976. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  47977. return;
  47978. case 5:
  47979. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  47980. return;
  47981. }
  47982. };
  47983. return OculusTouchController;
  47984. }(WebVRController));
  47985. BABYLON.OculusTouchController = OculusTouchController;
  47986. var ViveController = (function (_super) {
  47987. __extends(ViveController, _super);
  47988. function ViveController(vrGamepad) {
  47989. var _this = _super.call(this, vrGamepad) || this;
  47990. _this.controllerType = PoseEnabledControllerType.VIVE;
  47991. return _this;
  47992. }
  47993. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  47994. var _this = this;
  47995. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  47996. /*
  47997. Parent Mesh name: ViveWand
  47998. - body
  47999. - r_gripper
  48000. - l_gripper
  48001. - menu_button
  48002. - system_button
  48003. - trackpad
  48004. - trigger
  48005. - LED
  48006. */
  48007. _this._defaultModel = newMeshes[1];
  48008. if (meshLoaded) {
  48009. meshLoaded(_this._defaultModel);
  48010. }
  48011. _this.attachToMesh(_this._defaultModel);
  48012. });
  48013. };
  48014. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  48015. get: function () {
  48016. return this.onMainButtonStateChangedObservable;
  48017. },
  48018. enumerable: true,
  48019. configurable: true
  48020. });
  48021. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  48022. get: function () {
  48023. return this.onMainButtonStateChangedObservable;
  48024. },
  48025. enumerable: true,
  48026. configurable: true
  48027. });
  48028. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  48029. get: function () {
  48030. return this.onSecondaryButtonStateChangedObservable;
  48031. },
  48032. enumerable: true,
  48033. configurable: true
  48034. });
  48035. /**
  48036. * Vive mapping:
  48037. * 0: touchpad
  48038. * 1: trigger
  48039. * 2: left AND right buttons
  48040. * 3: menu button
  48041. */
  48042. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48043. var notifyObject = state; //{ state: state, changes: changes };
  48044. switch (buttonIdx) {
  48045. case 0:
  48046. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48047. return;
  48048. case 1:
  48049. if (this._defaultModel) {
  48050. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  48051. }
  48052. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48053. return;
  48054. case 2:
  48055. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48056. return;
  48057. case 3:
  48058. if (this._defaultModel) {
  48059. if (notifyObject.pressed) {
  48060. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48061. }
  48062. else {
  48063. (this._defaultModel.getChildren()[2]).position.y = 0;
  48064. }
  48065. }
  48066. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48067. return;
  48068. }
  48069. };
  48070. return ViveController;
  48071. }(WebVRController));
  48072. BABYLON.ViveController = ViveController;
  48073. })(BABYLON || (BABYLON = {}));
  48074. //# sourceMappingURL=babylon.extendedGamepad.js.map
  48075. /// <reference path="babylon.targetCamera.ts" />
  48076. var BABYLON;
  48077. (function (BABYLON) {
  48078. var FollowCamera = (function (_super) {
  48079. __extends(FollowCamera, _super);
  48080. function FollowCamera(name, position, scene, lockedTarget) {
  48081. var _this = _super.call(this, name, position, scene) || this;
  48082. _this.radius = 12;
  48083. _this.rotationOffset = 0;
  48084. _this.heightOffset = 4;
  48085. _this.cameraAcceleration = 0.05;
  48086. _this.maxCameraSpeed = 20;
  48087. _this.lockedTarget = lockedTarget;
  48088. return _this;
  48089. }
  48090. FollowCamera.prototype.getRadians = function (degrees) {
  48091. return degrees * Math.PI / 180;
  48092. };
  48093. FollowCamera.prototype.follow = function (cameraTarget) {
  48094. if (!cameraTarget)
  48095. return;
  48096. var yRotation;
  48097. if (cameraTarget.rotationQuaternion) {
  48098. var rotMatrix = new BABYLON.Matrix();
  48099. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  48100. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  48101. }
  48102. else {
  48103. yRotation = cameraTarget.rotation.y;
  48104. }
  48105. var radians = this.getRadians(this.rotationOffset) + yRotation;
  48106. var targetPosition = cameraTarget.getAbsolutePosition();
  48107. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  48108. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  48109. var dx = targetX - this.position.x;
  48110. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  48111. var dz = (targetZ) - this.position.z;
  48112. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  48113. var vy = dy * this.cameraAcceleration;
  48114. var vz = dz * this.cameraAcceleration * 2;
  48115. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  48116. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48117. }
  48118. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  48119. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48120. }
  48121. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  48122. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48123. }
  48124. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  48125. this.setTarget(targetPosition);
  48126. };
  48127. FollowCamera.prototype._checkInputs = function () {
  48128. _super.prototype._checkInputs.call(this);
  48129. this.follow(this.lockedTarget);
  48130. };
  48131. FollowCamera.prototype.getClassName = function () {
  48132. return "FollowCamera";
  48133. };
  48134. return FollowCamera;
  48135. }(BABYLON.TargetCamera));
  48136. __decorate([
  48137. BABYLON.serialize()
  48138. ], FollowCamera.prototype, "radius", void 0);
  48139. __decorate([
  48140. BABYLON.serialize()
  48141. ], FollowCamera.prototype, "rotationOffset", void 0);
  48142. __decorate([
  48143. BABYLON.serialize()
  48144. ], FollowCamera.prototype, "heightOffset", void 0);
  48145. __decorate([
  48146. BABYLON.serialize()
  48147. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  48148. __decorate([
  48149. BABYLON.serialize()
  48150. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  48151. __decorate([
  48152. BABYLON.serializeAsMeshReference("lockedTargetId")
  48153. ], FollowCamera.prototype, "lockedTarget", void 0);
  48154. BABYLON.FollowCamera = FollowCamera;
  48155. var ArcFollowCamera = (function (_super) {
  48156. __extends(ArcFollowCamera, _super);
  48157. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  48158. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48159. _this.alpha = alpha;
  48160. _this.beta = beta;
  48161. _this.radius = radius;
  48162. _this.target = target;
  48163. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  48164. _this.follow();
  48165. return _this;
  48166. }
  48167. ArcFollowCamera.prototype.follow = function () {
  48168. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  48169. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  48170. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  48171. var targetPosition = this.target.getAbsolutePosition();
  48172. this.position = targetPosition.add(this._cartesianCoordinates);
  48173. this.setTarget(targetPosition);
  48174. };
  48175. ArcFollowCamera.prototype._checkInputs = function () {
  48176. _super.prototype._checkInputs.call(this);
  48177. this.follow();
  48178. };
  48179. ArcFollowCamera.prototype.getClassName = function () {
  48180. return "ArcFollowCamera";
  48181. };
  48182. return ArcFollowCamera;
  48183. }(BABYLON.TargetCamera));
  48184. BABYLON.ArcFollowCamera = ArcFollowCamera;
  48185. })(BABYLON || (BABYLON = {}));
  48186. //# sourceMappingURL=babylon.followCamera.js.map
  48187. /// <reference path="babylon.touchCamera.ts" />
  48188. var BABYLON;
  48189. (function (BABYLON) {
  48190. // We're mainly based on the logic defined into the FreeCamera code
  48191. var UniversalCamera = (function (_super) {
  48192. __extends(UniversalCamera, _super);
  48193. //-- end properties for backward compatibility for inputs
  48194. function UniversalCamera(name, position, scene) {
  48195. var _this = _super.call(this, name, position, scene) || this;
  48196. _this.inputs.addGamepad();
  48197. return _this;
  48198. }
  48199. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  48200. //-- Begin properties for backward compatibility for inputs
  48201. get: function () {
  48202. var gamepad = this.inputs.attached["gamepad"];
  48203. if (gamepad)
  48204. return gamepad.gamepadAngularSensibility;
  48205. },
  48206. set: function (value) {
  48207. var gamepad = this.inputs.attached["gamepad"];
  48208. if (gamepad)
  48209. gamepad.gamepadAngularSensibility = value;
  48210. },
  48211. enumerable: true,
  48212. configurable: true
  48213. });
  48214. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  48215. get: function () {
  48216. var gamepad = this.inputs.attached["gamepad"];
  48217. if (gamepad)
  48218. return gamepad.gamepadMoveSensibility;
  48219. },
  48220. set: function (value) {
  48221. var gamepad = this.inputs.attached["gamepad"];
  48222. if (gamepad)
  48223. gamepad.gamepadMoveSensibility = value;
  48224. },
  48225. enumerable: true,
  48226. configurable: true
  48227. });
  48228. UniversalCamera.prototype.getClassName = function () {
  48229. return "UniversalCamera";
  48230. };
  48231. return UniversalCamera;
  48232. }(BABYLON.TouchCamera));
  48233. BABYLON.UniversalCamera = UniversalCamera;
  48234. })(BABYLON || (BABYLON = {}));
  48235. //# sourceMappingURL=babylon.universalCamera.js.map
  48236. /// <reference path="babylon.universalCamera.ts" />
  48237. var BABYLON;
  48238. (function (BABYLON) {
  48239. // We're mainly based on the logic defined into the FreeCamera code
  48240. var GamepadCamera = (function (_super) {
  48241. __extends(GamepadCamera, _super);
  48242. //-- end properties for backward compatibility for inputs
  48243. function GamepadCamera(name, position, scene) {
  48244. return _super.call(this, name, position, scene) || this;
  48245. }
  48246. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  48247. //-- Begin properties for backward compatibility for inputs
  48248. get: function () {
  48249. var gamepad = this.inputs.attached["gamepad"];
  48250. if (gamepad)
  48251. return gamepad.gamepadAngularSensibility;
  48252. },
  48253. set: function (value) {
  48254. var gamepad = this.inputs.attached["gamepad"];
  48255. if (gamepad)
  48256. gamepad.gamepadAngularSensibility = value;
  48257. },
  48258. enumerable: true,
  48259. configurable: true
  48260. });
  48261. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  48262. get: function () {
  48263. var gamepad = this.inputs.attached["gamepad"];
  48264. if (gamepad)
  48265. return gamepad.gamepadMoveSensibility;
  48266. },
  48267. set: function (value) {
  48268. var gamepad = this.inputs.attached["gamepad"];
  48269. if (gamepad)
  48270. gamepad.gamepadMoveSensibility = value;
  48271. },
  48272. enumerable: true,
  48273. configurable: true
  48274. });
  48275. GamepadCamera.prototype.getClassName = function () {
  48276. return "GamepadCamera";
  48277. };
  48278. return GamepadCamera;
  48279. }(BABYLON.UniversalCamera));
  48280. BABYLON.GamepadCamera = GamepadCamera;
  48281. })(BABYLON || (BABYLON = {}));
  48282. //# sourceMappingURL=babylon.gamepadCamera.js.map
  48283. var BABYLON;
  48284. (function (BABYLON) {
  48285. var PostProcessRenderPipelineManager = (function () {
  48286. function PostProcessRenderPipelineManager() {
  48287. this._renderPipelines = {};
  48288. }
  48289. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  48290. this._renderPipelines[renderPipeline._name] = renderPipeline;
  48291. };
  48292. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  48293. var renderPipeline = this._renderPipelines[renderPipelineName];
  48294. if (!renderPipeline) {
  48295. return;
  48296. }
  48297. renderPipeline._attachCameras(cameras, unique);
  48298. };
  48299. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  48300. var renderPipeline = this._renderPipelines[renderPipelineName];
  48301. if (!renderPipeline) {
  48302. return;
  48303. }
  48304. renderPipeline._detachCameras(cameras);
  48305. };
  48306. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48307. var renderPipeline = this._renderPipelines[renderPipelineName];
  48308. if (!renderPipeline) {
  48309. return;
  48310. }
  48311. renderPipeline._enableEffect(renderEffectName, cameras);
  48312. };
  48313. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48314. var renderPipeline = this._renderPipelines[renderPipelineName];
  48315. if (!renderPipeline) {
  48316. return;
  48317. }
  48318. renderPipeline._disableEffect(renderEffectName, cameras);
  48319. };
  48320. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  48321. var renderPipeline = this._renderPipelines[renderPipelineName];
  48322. if (!renderPipeline) {
  48323. return;
  48324. }
  48325. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  48326. };
  48327. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  48328. var renderPipeline = this._renderPipelines[renderPipelineName];
  48329. if (!renderPipeline) {
  48330. return;
  48331. }
  48332. renderPipeline._disableDisplayOnlyPass(cameras);
  48333. };
  48334. PostProcessRenderPipelineManager.prototype.update = function () {
  48335. for (var renderPipelineName in this._renderPipelines) {
  48336. var pipeline = this._renderPipelines[renderPipelineName];
  48337. if (!pipeline.isSupported) {
  48338. pipeline.dispose();
  48339. delete this._renderPipelines[renderPipelineName];
  48340. }
  48341. else {
  48342. pipeline._update();
  48343. }
  48344. }
  48345. };
  48346. return PostProcessRenderPipelineManager;
  48347. }());
  48348. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  48349. })(BABYLON || (BABYLON = {}));
  48350. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  48351. var BABYLON;
  48352. (function (BABYLON) {
  48353. var PostProcessRenderPass = (function () {
  48354. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  48355. this._enabled = true;
  48356. this._refCount = 0;
  48357. this._name = name;
  48358. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  48359. this.setRenderList(renderList);
  48360. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  48361. this._renderTexture.onAfterRenderObservable.add(afterRender);
  48362. this._scene = scene;
  48363. this._renderList = renderList;
  48364. }
  48365. // private
  48366. PostProcessRenderPass.prototype._incRefCount = function () {
  48367. if (this._refCount === 0) {
  48368. this._scene.customRenderTargets.push(this._renderTexture);
  48369. }
  48370. return ++this._refCount;
  48371. };
  48372. PostProcessRenderPass.prototype._decRefCount = function () {
  48373. this._refCount--;
  48374. if (this._refCount <= 0) {
  48375. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  48376. }
  48377. return this._refCount;
  48378. };
  48379. PostProcessRenderPass.prototype._update = function () {
  48380. this.setRenderList(this._renderList);
  48381. };
  48382. // public
  48383. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  48384. this._renderTexture.renderList = renderList;
  48385. };
  48386. PostProcessRenderPass.prototype.getRenderTexture = function () {
  48387. return this._renderTexture;
  48388. };
  48389. return PostProcessRenderPass;
  48390. }());
  48391. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  48392. })(BABYLON || (BABYLON = {}));
  48393. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  48394. var BABYLON;
  48395. (function (BABYLON) {
  48396. var PostProcessRenderEffect = (function () {
  48397. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  48398. this._engine = engine;
  48399. this._name = name;
  48400. this._singleInstance = singleInstance || true;
  48401. this._getPostProcess = getPostProcess;
  48402. this._cameras = [];
  48403. this._indicesForCamera = [];
  48404. this._postProcesses = {};
  48405. this._renderPasses = {};
  48406. this._renderEffectAsPasses = {};
  48407. }
  48408. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  48409. get: function () {
  48410. for (var index in this._postProcesses) {
  48411. if (!this._postProcesses[index].isSupported) {
  48412. return false;
  48413. }
  48414. }
  48415. return true;
  48416. },
  48417. enumerable: true,
  48418. configurable: true
  48419. });
  48420. PostProcessRenderEffect.prototype._update = function () {
  48421. for (var renderPassName in this._renderPasses) {
  48422. this._renderPasses[renderPassName]._update();
  48423. }
  48424. };
  48425. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  48426. this._renderPasses[renderPass._name] = renderPass;
  48427. this._linkParameters();
  48428. };
  48429. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  48430. delete this._renderPasses[renderPass._name];
  48431. this._linkParameters();
  48432. };
  48433. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  48434. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  48435. this._linkParameters();
  48436. };
  48437. PostProcessRenderEffect.prototype.getPass = function (passName) {
  48438. for (var renderPassName in this._renderPasses) {
  48439. if (renderPassName === passName) {
  48440. return this._renderPasses[passName];
  48441. }
  48442. }
  48443. };
  48444. PostProcessRenderEffect.prototype.emptyPasses = function () {
  48445. this._renderPasses = {};
  48446. this._linkParameters();
  48447. };
  48448. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  48449. var cameraKey;
  48450. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48451. for (var i = 0; i < _cam.length; i++) {
  48452. var camera = _cam[i];
  48453. var cameraName = camera.name;
  48454. if (this._singleInstance) {
  48455. cameraKey = 0;
  48456. }
  48457. else {
  48458. cameraKey = cameraName;
  48459. }
  48460. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  48461. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  48462. if (!this._indicesForCamera[cameraName]) {
  48463. this._indicesForCamera[cameraName] = [];
  48464. }
  48465. this._indicesForCamera[cameraName].push(index);
  48466. if (this._cameras.indexOf(camera) === -1) {
  48467. this._cameras[cameraName] = camera;
  48468. }
  48469. for (var passName in this._renderPasses) {
  48470. this._renderPasses[passName]._incRefCount();
  48471. }
  48472. }
  48473. this._linkParameters();
  48474. };
  48475. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  48476. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48477. for (var i = 0; i < _cam.length; i++) {
  48478. var camera = _cam[i];
  48479. var cameraName = camera.name;
  48480. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48481. var index = this._cameras.indexOf(cameraName);
  48482. this._indicesForCamera.splice(index, 1);
  48483. this._cameras.splice(index, 1);
  48484. for (var passName in this._renderPasses) {
  48485. this._renderPasses[passName]._decRefCount();
  48486. }
  48487. }
  48488. };
  48489. PostProcessRenderEffect.prototype._enable = function (cameras) {
  48490. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48491. for (var i = 0; i < _cam.length; i++) {
  48492. var camera = _cam[i];
  48493. var cameraName = camera.name;
  48494. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  48495. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  48496. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  48497. }
  48498. }
  48499. for (var passName in this._renderPasses) {
  48500. this._renderPasses[passName]._incRefCount();
  48501. }
  48502. }
  48503. };
  48504. PostProcessRenderEffect.prototype._disable = function (cameras) {
  48505. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48506. for (var i = 0; i < _cam.length; i++) {
  48507. var camera = _cam[i];
  48508. var cameraName = camera.Name;
  48509. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48510. for (var passName in this._renderPasses) {
  48511. this._renderPasses[passName]._decRefCount();
  48512. }
  48513. }
  48514. };
  48515. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  48516. if (this._singleInstance) {
  48517. return this._postProcesses[0];
  48518. }
  48519. else {
  48520. return this._postProcesses[camera.name];
  48521. }
  48522. };
  48523. PostProcessRenderEffect.prototype._linkParameters = function () {
  48524. var _this = this;
  48525. for (var index in this._postProcesses) {
  48526. if (this.applyParameters) {
  48527. this.applyParameters(this._postProcesses[index]);
  48528. }
  48529. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  48530. _this._linkTextures(effect);
  48531. });
  48532. }
  48533. };
  48534. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  48535. for (var renderPassName in this._renderPasses) {
  48536. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  48537. }
  48538. for (var renderEffectName in this._renderEffectAsPasses) {
  48539. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  48540. }
  48541. };
  48542. return PostProcessRenderEffect;
  48543. }());
  48544. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  48545. })(BABYLON || (BABYLON = {}));
  48546. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  48547. var BABYLON;
  48548. (function (BABYLON) {
  48549. var PostProcessRenderPipeline = (function () {
  48550. function PostProcessRenderPipeline(engine, name) {
  48551. this._engine = engine;
  48552. this._name = name;
  48553. this._renderEffects = {};
  48554. this._renderEffectsForIsolatedPass = {};
  48555. this._cameras = [];
  48556. }
  48557. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  48558. get: function () {
  48559. for (var renderEffectName in this._renderEffects) {
  48560. if (!this._renderEffects[renderEffectName].isSupported) {
  48561. return false;
  48562. }
  48563. }
  48564. return true;
  48565. },
  48566. enumerable: true,
  48567. configurable: true
  48568. });
  48569. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  48570. this._renderEffects[renderEffect._name] = renderEffect;
  48571. };
  48572. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  48573. var renderEffects = this._renderEffects[renderEffectName];
  48574. if (!renderEffects) {
  48575. return;
  48576. }
  48577. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48578. };
  48579. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  48580. var renderEffects = this._renderEffects[renderEffectName];
  48581. if (!renderEffects) {
  48582. return;
  48583. }
  48584. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48585. };
  48586. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  48587. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48588. var indicesToDelete = [];
  48589. var i;
  48590. for (i = 0; i < _cam.length; i++) {
  48591. var camera = _cam[i];
  48592. var cameraName = camera.name;
  48593. if (this._cameras.indexOf(camera) === -1) {
  48594. this._cameras[cameraName] = camera;
  48595. }
  48596. else if (unique) {
  48597. indicesToDelete.push(i);
  48598. }
  48599. }
  48600. for (i = 0; i < indicesToDelete.length; i++) {
  48601. cameras.splice(indicesToDelete[i], 1);
  48602. }
  48603. for (var renderEffectName in this._renderEffects) {
  48604. this._renderEffects[renderEffectName]._attachCameras(_cam);
  48605. }
  48606. };
  48607. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  48608. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48609. for (var renderEffectName in this._renderEffects) {
  48610. this._renderEffects[renderEffectName]._detachCameras(_cam);
  48611. }
  48612. for (var i = 0; i < _cam.length; i++) {
  48613. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  48614. }
  48615. };
  48616. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  48617. var _this = this;
  48618. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48619. var pass = null;
  48620. var renderEffectName;
  48621. for (renderEffectName in this._renderEffects) {
  48622. pass = this._renderEffects[renderEffectName].getPass(passName);
  48623. if (pass != null) {
  48624. break;
  48625. }
  48626. }
  48627. if (pass === null) {
  48628. return;
  48629. }
  48630. for (renderEffectName in this._renderEffects) {
  48631. this._renderEffects[renderEffectName]._disable(_cam);
  48632. }
  48633. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  48634. for (var i = 0; i < _cam.length; i++) {
  48635. var camera = _cam[i];
  48636. var cameraName = camera.name;
  48637. 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); });
  48638. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  48639. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  48640. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  48641. }
  48642. };
  48643. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  48644. var _this = this;
  48645. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48646. for (var i = 0; i < _cam.length; i++) {
  48647. var camera = _cam[i];
  48648. var cameraName = camera.name;
  48649. 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); });
  48650. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  48651. }
  48652. for (var renderEffectName in this._renderEffects) {
  48653. this._renderEffects[renderEffectName]._enable(_cam);
  48654. }
  48655. };
  48656. PostProcessRenderPipeline.prototype._update = function () {
  48657. for (var renderEffectName in this._renderEffects) {
  48658. this._renderEffects[renderEffectName]._update();
  48659. }
  48660. for (var i = 0; i < this._cameras.length; i++) {
  48661. var cameraName = this._cameras[i].name;
  48662. if (this._renderEffectsForIsolatedPass[cameraName]) {
  48663. this._renderEffectsForIsolatedPass[cameraName]._update();
  48664. }
  48665. }
  48666. };
  48667. PostProcessRenderPipeline.prototype.dispose = function () {
  48668. // Must be implemented by children
  48669. };
  48670. return PostProcessRenderPipeline;
  48671. }());
  48672. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  48673. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  48674. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  48675. })(BABYLON || (BABYLON = {}));
  48676. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  48677. var BABYLON;
  48678. (function (BABYLON) {
  48679. var DepthRenderer = (function () {
  48680. function DepthRenderer(scene, type) {
  48681. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  48682. var _this = this;
  48683. this._viewMatrix = BABYLON.Matrix.Zero();
  48684. this._projectionMatrix = BABYLON.Matrix.Zero();
  48685. this._transformMatrix = BABYLON.Matrix.Zero();
  48686. this._worldViewProjection = BABYLON.Matrix.Zero();
  48687. this._scene = scene;
  48688. var engine = scene.getEngine();
  48689. // Render target
  48690. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  48691. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48692. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48693. this._depthMap.refreshRate = 1;
  48694. this._depthMap.renderParticles = false;
  48695. this._depthMap.renderList = null;
  48696. // set default depth value to 1.0 (far away)
  48697. this._depthMap.onClearObservable.add(function (engine) {
  48698. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  48699. });
  48700. // Custom render function
  48701. var renderSubMesh = function (subMesh) {
  48702. var mesh = subMesh.getRenderingMesh();
  48703. var scene = _this._scene;
  48704. var engine = scene.getEngine();
  48705. // Culling
  48706. engine.setState(subMesh.getMaterial().backFaceCulling);
  48707. // Managing instances
  48708. var batch = mesh._getInstancesRenderList(subMesh._id);
  48709. if (batch.mustReturn) {
  48710. return;
  48711. }
  48712. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48713. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48714. engine.enableEffect(_this._effect);
  48715. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  48716. var material = subMesh.getMaterial();
  48717. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48718. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  48719. // Alpha test
  48720. if (material && material.needAlphaTesting()) {
  48721. var alphaTexture = material.getAlphaTestTexture();
  48722. _this._effect.setTexture("diffuseSampler", alphaTexture);
  48723. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48724. }
  48725. // Bones
  48726. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48727. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48728. }
  48729. // Draw
  48730. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  48731. }
  48732. };
  48733. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  48734. var index;
  48735. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48736. renderSubMesh(opaqueSubMeshes.data[index]);
  48737. }
  48738. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48739. renderSubMesh(alphaTestSubMeshes.data[index]);
  48740. }
  48741. };
  48742. }
  48743. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  48744. var material = subMesh.getMaterial();
  48745. if (material.disableDepthWrite) {
  48746. return false;
  48747. }
  48748. var defines = [];
  48749. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48750. var mesh = subMesh.getMesh();
  48751. var scene = mesh.getScene();
  48752. // Alpha test
  48753. if (material && material.needAlphaTesting()) {
  48754. defines.push("#define ALPHATEST");
  48755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48756. attribs.push(BABYLON.VertexBuffer.UVKind);
  48757. defines.push("#define UV1");
  48758. }
  48759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48760. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48761. defines.push("#define UV2");
  48762. }
  48763. }
  48764. // Bones
  48765. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48766. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48767. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48768. if (mesh.numBoneInfluencers > 4) {
  48769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48771. }
  48772. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48773. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48774. }
  48775. else {
  48776. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48777. }
  48778. // Instances
  48779. if (useInstances) {
  48780. defines.push("#define INSTANCES");
  48781. attribs.push("world0");
  48782. attribs.push("world1");
  48783. attribs.push("world2");
  48784. attribs.push("world3");
  48785. }
  48786. // Get correct effect
  48787. var join = defines.join("\n");
  48788. if (this._cachedDefines !== join) {
  48789. this._cachedDefines = join;
  48790. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  48791. }
  48792. return this._effect.isReady();
  48793. };
  48794. DepthRenderer.prototype.getDepthMap = function () {
  48795. return this._depthMap;
  48796. };
  48797. // Methods
  48798. DepthRenderer.prototype.dispose = function () {
  48799. this._depthMap.dispose();
  48800. };
  48801. return DepthRenderer;
  48802. }());
  48803. BABYLON.DepthRenderer = DepthRenderer;
  48804. })(BABYLON || (BABYLON = {}));
  48805. //# sourceMappingURL=babylon.depthRenderer.js.map
  48806. var BABYLON;
  48807. (function (BABYLON) {
  48808. var SSAORenderingPipeline = (function (_super) {
  48809. __extends(SSAORenderingPipeline, _super);
  48810. /**
  48811. * @constructor
  48812. * @param {string} name - The rendering pipeline name
  48813. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48814. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  48815. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48816. */
  48817. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  48818. var _this = _super.call(this, scene.getEngine(), name) || this;
  48819. // Members
  48820. /**
  48821. * The PassPostProcess id in the pipeline that contains the original scene color
  48822. * @type {string}
  48823. */
  48824. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  48825. /**
  48826. * The SSAO PostProcess id in the pipeline
  48827. * @type {string}
  48828. */
  48829. _this.SSAORenderEffect = "SSAORenderEffect";
  48830. /**
  48831. * The horizontal blur PostProcess id in the pipeline
  48832. * @type {string}
  48833. */
  48834. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  48835. /**
  48836. * The vertical blur PostProcess id in the pipeline
  48837. * @type {string}
  48838. */
  48839. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  48840. /**
  48841. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  48842. * @type {string}
  48843. */
  48844. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  48845. /**
  48846. * The output strength of the SSAO post-process. Default value is 1.0.
  48847. * @type {number}
  48848. */
  48849. _this.totalStrength = 1.0;
  48850. /**
  48851. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  48852. * @type {number}
  48853. */
  48854. _this.radius = 0.0001;
  48855. /**
  48856. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  48857. * Must not be equal to fallOff and superior to fallOff.
  48858. * Default value is 0.975
  48859. * @type {number}
  48860. */
  48861. _this.area = 0.0075;
  48862. /**
  48863. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  48864. * Must not be equal to area and inferior to area.
  48865. * Default value is 0.0
  48866. * @type {number}
  48867. */
  48868. _this.fallOff = 0.000001;
  48869. /**
  48870. * The base color of the SSAO post-process
  48871. * The final result is "base + ssao" between [0, 1]
  48872. * @type {number}
  48873. */
  48874. _this.base = 0.5;
  48875. _this._firstUpdate = true;
  48876. _this._scene = scene;
  48877. // Set up assets
  48878. _this._createRandomTexture();
  48879. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48880. var ssaoRatio = ratio.ssaoRatio || ratio;
  48881. var combineRatio = ratio.combineRatio || ratio;
  48882. _this._ratio = {
  48883. ssaoRatio: ssaoRatio,
  48884. combineRatio: combineRatio
  48885. };
  48886. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48887. _this._createSSAOPostProcess(ssaoRatio);
  48888. _this._createBlurPostProcess(ssaoRatio);
  48889. _this._createSSAOCombinePostProcess(combineRatio);
  48890. // Set up pipeline
  48891. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  48892. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  48893. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  48894. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  48895. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  48896. // Finish
  48897. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48898. if (cameras)
  48899. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48900. return _this;
  48901. }
  48902. // Public Methods
  48903. /**
  48904. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  48905. */
  48906. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48907. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48908. for (var i = 0; i < this._scene.cameras.length; i++) {
  48909. var camera = this._scene.cameras[i];
  48910. this._originalColorPostProcess.dispose(camera);
  48911. this._ssaoPostProcess.dispose(camera);
  48912. this._blurHPostProcess.dispose(camera);
  48913. this._blurVPostProcess.dispose(camera);
  48914. this._ssaoCombinePostProcess.dispose(camera);
  48915. }
  48916. this._randomTexture.dispose();
  48917. if (disableDepthRender)
  48918. this._scene.disableDepthRenderer();
  48919. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48920. _super.prototype.dispose.call(this);
  48921. };
  48922. // Private Methods
  48923. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  48924. var _this = this;
  48925. /*
  48926. var samplerOffsets = [
  48927. -8.0, -6.0, -4.0, -2.0,
  48928. 0.0,
  48929. 2.0, 4.0, 6.0, 8.0
  48930. ];
  48931. */
  48932. var samples = 16;
  48933. var samplerOffsets = [];
  48934. for (var i = -8; i < 8; i++) {
  48935. samplerOffsets.push(i * 2);
  48936. }
  48937. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  48938. this._blurHPostProcess.onApply = function (effect) {
  48939. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  48940. effect.setTexture("depthSampler", _this._depthTexture);
  48941. if (_this._firstUpdate) {
  48942. effect.setArray("samplerOffsets", samplerOffsets);
  48943. }
  48944. };
  48945. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  48946. this._blurVPostProcess.onApply = function (effect) {
  48947. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  48948. effect.setTexture("depthSampler", _this._depthTexture);
  48949. if (_this._firstUpdate) {
  48950. effect.setArray("samplerOffsets", samplerOffsets);
  48951. _this._firstUpdate = false;
  48952. }
  48953. };
  48954. };
  48955. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  48956. var _this = this;
  48957. var numSamples = 16;
  48958. var sampleSphere = [
  48959. 0.5381, 0.1856, -0.4319,
  48960. 0.1379, 0.2486, 0.4430,
  48961. 0.3371, 0.5679, -0.0057,
  48962. -0.6999, -0.0451, -0.0019,
  48963. 0.0689, -0.1598, -0.8547,
  48964. 0.0560, 0.0069, -0.1843,
  48965. -0.0146, 0.1402, 0.0762,
  48966. 0.0100, -0.1924, -0.0344,
  48967. -0.3577, -0.5301, -0.4358,
  48968. -0.3169, 0.1063, 0.0158,
  48969. 0.0103, -0.5869, 0.0046,
  48970. -0.0897, -0.4940, 0.3287,
  48971. 0.7119, -0.0154, -0.0918,
  48972. -0.0533, 0.0596, -0.5411,
  48973. 0.0352, -0.0631, 0.5460,
  48974. -0.4776, 0.2847, -0.0271
  48975. ];
  48976. var samplesFactor = 1.0 / numSamples;
  48977. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  48978. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  48979. "area", "fallOff", "base", "range", "viewport"
  48980. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  48981. var viewport = new BABYLON.Vector2(0, 0);
  48982. this._ssaoPostProcess.onApply = function (effect) {
  48983. if (_this._firstUpdate) {
  48984. effect.setArray3("sampleSphere", sampleSphere);
  48985. effect.setFloat("samplesFactor", samplesFactor);
  48986. effect.setFloat("randTextureTiles", 4.0);
  48987. }
  48988. effect.setFloat("totalStrength", _this.totalStrength);
  48989. effect.setFloat("radius", _this.radius);
  48990. effect.setFloat("area", _this.area);
  48991. effect.setFloat("fallOff", _this.fallOff);
  48992. effect.setFloat("base", _this.base);
  48993. effect.setTexture("textureSampler", _this._depthTexture);
  48994. effect.setTexture("randomSampler", _this._randomTexture);
  48995. };
  48996. };
  48997. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  48998. var _this = this;
  48999. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49000. this._ssaoCombinePostProcess.onApply = function (effect) {
  49001. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49002. };
  49003. };
  49004. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  49005. var size = 512;
  49006. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49007. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49008. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49009. var context = this._randomTexture.getContext();
  49010. var rand = function (min, max) {
  49011. return Math.random() * (max - min) + min;
  49012. };
  49013. var randVector = BABYLON.Vector3.Zero();
  49014. for (var x = 0; x < size; x++) {
  49015. for (var y = 0; y < size; y++) {
  49016. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  49017. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  49018. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  49019. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49020. context.fillRect(x, y, 1, 1);
  49021. }
  49022. }
  49023. this._randomTexture.update(false);
  49024. };
  49025. return SSAORenderingPipeline;
  49026. }(BABYLON.PostProcessRenderPipeline));
  49027. __decorate([
  49028. BABYLON.serialize()
  49029. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  49030. __decorate([
  49031. BABYLON.serialize()
  49032. ], SSAORenderingPipeline.prototype, "radius", void 0);
  49033. __decorate([
  49034. BABYLON.serialize()
  49035. ], SSAORenderingPipeline.prototype, "area", void 0);
  49036. __decorate([
  49037. BABYLON.serialize()
  49038. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  49039. __decorate([
  49040. BABYLON.serialize()
  49041. ], SSAORenderingPipeline.prototype, "base", void 0);
  49042. __decorate([
  49043. BABYLON.serialize()
  49044. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  49045. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  49046. })(BABYLON || (BABYLON = {}));
  49047. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  49048. var BABYLON;
  49049. (function (BABYLON) {
  49050. var SSAO2RenderingPipeline = (function (_super) {
  49051. __extends(SSAO2RenderingPipeline, _super);
  49052. /**
  49053. * @constructor
  49054. * @param {string} name - The rendering pipeline name
  49055. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49056. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  49057. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49058. */
  49059. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  49060. var _this = _super.call(this, scene.getEngine(), name) || this;
  49061. // Members
  49062. /**
  49063. * The PassPostProcess id in the pipeline that contains the original scene color
  49064. * @type {string}
  49065. */
  49066. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49067. /**
  49068. * The SSAO PostProcess id in the pipeline
  49069. * @type {string}
  49070. */
  49071. _this.SSAORenderEffect = "SSAORenderEffect";
  49072. /**
  49073. * The horizontal blur PostProcess id in the pipeline
  49074. * @type {string}
  49075. */
  49076. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49077. /**
  49078. * The vertical blur PostProcess id in the pipeline
  49079. * @type {string}
  49080. */
  49081. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49082. /**
  49083. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49084. * @type {string}
  49085. */
  49086. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49087. /**
  49088. * The output strength of the SSAO post-process. Default value is 1.0.
  49089. * @type {number}
  49090. */
  49091. _this.totalStrength = 1.0;
  49092. /**
  49093. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  49094. * @type {number}
  49095. */
  49096. _this.maxZ = 100.0;
  49097. /**
  49098. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  49099. * @type {number}
  49100. */
  49101. _this.minZAspect = 0.2;
  49102. /**
  49103. * Number of samples used for the SSAO calculations. Default value is 8
  49104. * @type {number}
  49105. */
  49106. _this._samples = 8;
  49107. /**
  49108. * Are we using bilateral blur ?
  49109. * @type {boolean}
  49110. */
  49111. _this._expensiveBlur = true;
  49112. /**
  49113. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  49114. * @type {number}
  49115. */
  49116. _this.radius = 2.0;
  49117. /**
  49118. * The base color of the SSAO post-process
  49119. * The final result is "base + ssao" between [0, 1]
  49120. * @type {number}
  49121. */
  49122. _this.base = 0.1;
  49123. _this._firstUpdate = true;
  49124. _this._scene = scene;
  49125. if (!_this.isSupported) {
  49126. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  49127. return _this;
  49128. }
  49129. var ssaoRatio = ratio.ssaoRatio || ratio;
  49130. var blurRatio = ratio.blurRatio || ratio;
  49131. _this._ratio = {
  49132. ssaoRatio: ssaoRatio,
  49133. blurRatio: blurRatio
  49134. };
  49135. // Set up assets
  49136. _this._createRandomTexture();
  49137. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  49138. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  49139. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49140. _this._createSSAOPostProcess(1.0);
  49141. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  49142. _this._createSSAOCombinePostProcess(blurRatio);
  49143. // Set up pipeline
  49144. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49145. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49146. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49147. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49148. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49149. // Finish
  49150. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49151. if (cameras)
  49152. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49153. return _this;
  49154. }
  49155. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  49156. get: function () {
  49157. return this._samples;
  49158. },
  49159. set: function (n) {
  49160. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  49161. this._samples = n;
  49162. this._sampleSphere = this._generateHemisphere();
  49163. this._firstUpdate = true;
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  49169. get: function () {
  49170. return this._expensiveBlur;
  49171. },
  49172. set: function (b) {
  49173. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  49174. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  49175. this._expensiveBlur = b;
  49176. this._firstUpdate = true;
  49177. },
  49178. enumerable: true,
  49179. configurable: true
  49180. });
  49181. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  49182. /**
  49183. * Support test.
  49184. * @type {boolean}
  49185. */
  49186. get: function () {
  49187. var engine = BABYLON.Engine.LastCreatedEngine;
  49188. return engine.webGLVersion > 1;
  49189. },
  49190. enumerable: true,
  49191. configurable: true
  49192. });
  49193. // Public Methods
  49194. /**
  49195. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49196. */
  49197. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  49198. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  49199. for (var i = 0; i < this._scene.cameras.length; i++) {
  49200. var camera = this._scene.cameras[i];
  49201. this._originalColorPostProcess.dispose(camera);
  49202. this._ssaoPostProcess.dispose(camera);
  49203. this._blurHPostProcess.dispose(camera);
  49204. this._blurVPostProcess.dispose(camera);
  49205. this._ssaoCombinePostProcess.dispose(camera);
  49206. }
  49207. this._randomTexture.dispose();
  49208. if (disableGeometryBufferRenderer)
  49209. this._scene.disableGeometryBufferRenderer();
  49210. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49211. _super.prototype.dispose.call(this);
  49212. };
  49213. // Private Methods
  49214. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  49215. var _this = this;
  49216. var samples = 16;
  49217. this._samplerOffsets = [];
  49218. var expensive = this.expensiveBlur;
  49219. for (var i = -8; i < 8; i++) {
  49220. this._samplerOffsets.push(i * 2 + 0.5);
  49221. }
  49222. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  49223. this._blurHPostProcess.onApply = function (effect) {
  49224. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49225. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49226. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49227. effect.setFloat("radius", _this.radius);
  49228. effect.setTexture("depthSampler", _this._depthTexture);
  49229. if (_this._firstUpdate) {
  49230. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49231. }
  49232. };
  49233. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  49234. this._blurVPostProcess.onApply = function (effect) {
  49235. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49236. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49237. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49238. effect.setFloat("radius", _this.radius);
  49239. effect.setTexture("depthSampler", _this._depthTexture);
  49240. if (_this._firstUpdate) {
  49241. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49242. _this._firstUpdate = false;
  49243. }
  49244. };
  49245. };
  49246. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  49247. var numSamples = this.samples;
  49248. var result = [];
  49249. var vector, scale;
  49250. var rand = function (min, max) {
  49251. return Math.random() * (max - min) + min;
  49252. };
  49253. var lerp = function (start, end, percent) {
  49254. return (start + percent * (end - start));
  49255. };
  49256. var i = 0;
  49257. var normal = new BABYLON.Vector3(0, 0, 1);
  49258. while (i < numSamples) {
  49259. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  49260. vector.normalize();
  49261. scale = i / numSamples;
  49262. scale = lerp(0.1, 1.0, scale * scale);
  49263. vector.scaleInPlace(scale);
  49264. result.push(vector.x, vector.y, vector.z);
  49265. i++;
  49266. }
  49267. return result;
  49268. };
  49269. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49270. var _this = this;
  49271. var numSamples = this.samples;
  49272. this._sampleSphere = this._generateHemisphere();
  49273. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  49274. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49275. "base", "range", "projection", "near", "far", "texelSize",
  49276. "xViewport", "yViewport", "maxZ", "minZAspect"
  49277. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49278. this._ssaoPostProcess.onApply = function (effect) {
  49279. if (_this._firstUpdate) {
  49280. effect.setArray3("sampleSphere", _this._sampleSphere);
  49281. effect.setFloat("randTextureTiles", 4.0);
  49282. }
  49283. effect.setFloat("samplesFactor", 1 / _this.samples);
  49284. effect.setFloat("totalStrength", _this.totalStrength);
  49285. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  49286. effect.setFloat("radius", _this.radius);
  49287. effect.setFloat("maxZ", _this.maxZ);
  49288. effect.setFloat("minZAspect", _this.minZAspect);
  49289. effect.setFloat("base", _this.base);
  49290. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49291. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49292. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  49293. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ);
  49294. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  49295. effect.setTexture("textureSampler", _this._depthTexture);
  49296. effect.setTexture("normalSampler", _this._normalTexture);
  49297. effect.setTexture("randomSampler", _this._randomTexture);
  49298. };
  49299. };
  49300. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49301. var _this = this;
  49302. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49303. this._ssaoCombinePostProcess.onApply = function (effect) {
  49304. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49305. };
  49306. };
  49307. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  49308. var size = 512;
  49309. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49310. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49311. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49312. var context = this._randomTexture.getContext();
  49313. var rand = function (min, max) {
  49314. return Math.random() * (max - min) + min;
  49315. };
  49316. var randVector = BABYLON.Vector3.Zero();
  49317. for (var x = 0; x < size; x++) {
  49318. for (var y = 0; y < size; y++) {
  49319. randVector.x = rand(0.0, 1.0);
  49320. randVector.y = rand(0.0, 1.0);
  49321. randVector.z = 0.0;
  49322. randVector.normalize();
  49323. randVector.scaleInPlace(255);
  49324. randVector.x = Math.floor(randVector.x);
  49325. randVector.y = Math.floor(randVector.y);
  49326. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49327. context.fillRect(x, y, 1, 1);
  49328. }
  49329. }
  49330. this._randomTexture.update(false);
  49331. };
  49332. return SSAO2RenderingPipeline;
  49333. }(BABYLON.PostProcessRenderPipeline));
  49334. __decorate([
  49335. BABYLON.serialize()
  49336. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  49337. __decorate([
  49338. BABYLON.serialize()
  49339. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  49340. __decorate([
  49341. BABYLON.serialize()
  49342. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  49343. __decorate([
  49344. BABYLON.serialize("samples")
  49345. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  49346. __decorate([
  49347. BABYLON.serialize("expensiveBlur")
  49348. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  49349. __decorate([
  49350. BABYLON.serialize()
  49351. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  49352. __decorate([
  49353. BABYLON.serialize()
  49354. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  49355. __decorate([
  49356. BABYLON.serialize()
  49357. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  49358. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  49359. })(BABYLON || (BABYLON = {}));
  49360. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  49361. // BABYLON.JS Chromatic Aberration GLSL Shader
  49362. // Author: Olivier Guyot
  49363. // Separates very slightly R, G and B colors on the edges of the screen
  49364. // Inspired by Francois Tarlier & Martins Upitis
  49365. var BABYLON;
  49366. (function (BABYLON) {
  49367. var LensRenderingPipeline = (function (_super) {
  49368. __extends(LensRenderingPipeline, _super);
  49369. /**
  49370. * @constructor
  49371. *
  49372. * Effect parameters are as follow:
  49373. * {
  49374. * chromatic_aberration: number; // from 0 to x (1 for realism)
  49375. * edge_blur: number; // from 0 to x (1 for realism)
  49376. * distortion: number; // from 0 to x (1 for realism)
  49377. * grain_amount: number; // from 0 to 1
  49378. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  49379. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  49380. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  49381. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  49382. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  49383. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  49384. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  49385. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  49386. * }
  49387. * Note: if an effect parameter is unset, effect is disabled
  49388. *
  49389. * @param {string} name - The rendering pipeline name
  49390. * @param {object} parameters - An object containing all parameters (see above)
  49391. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49392. * @param {number} 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)
  49393. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49394. */
  49395. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  49396. if (ratio === void 0) { ratio = 1.0; }
  49397. var _this = _super.call(this, scene.getEngine(), name) || this;
  49398. // Lens effects can be of the following:
  49399. // - chromatic aberration (slight shift of RGB colors)
  49400. // - blur on the edge of the lens
  49401. // - lens distortion
  49402. // - depth-of-field blur & highlights enhancing
  49403. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  49404. // - grain effect (noise or custom texture)
  49405. // Two additional texture samplers are needed:
  49406. // - depth map (for depth-of-field)
  49407. // - grain texture
  49408. /**
  49409. * The chromatic aberration PostProcess id in the pipeline
  49410. * @type {string}
  49411. */
  49412. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  49413. /**
  49414. * The highlights enhancing PostProcess id in the pipeline
  49415. * @type {string}
  49416. */
  49417. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  49418. /**
  49419. * The depth-of-field PostProcess id in the pipeline
  49420. * @type {string}
  49421. */
  49422. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  49423. _this._scene = scene;
  49424. // Fetch texture samplers
  49425. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49426. if (parameters.grain_texture) {
  49427. _this._grainTexture = parameters.grain_texture;
  49428. }
  49429. else {
  49430. _this._createGrainTexture();
  49431. }
  49432. // save parameters
  49433. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  49434. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  49435. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  49436. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  49437. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  49438. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  49439. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  49440. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  49441. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  49442. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  49443. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  49444. // Create effects
  49445. _this._createChromaticAberrationPostProcess(ratio);
  49446. _this._createHighlightsPostProcess(ratio);
  49447. _this._createDepthOfFieldPostProcess(ratio / 4);
  49448. // Set up pipeline
  49449. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  49450. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  49451. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  49452. if (_this._highlightsGain === -1) {
  49453. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  49454. }
  49455. // Finish
  49456. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49457. if (cameras) {
  49458. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49459. }
  49460. return _this;
  49461. }
  49462. // public methods (self explanatory)
  49463. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  49464. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  49465. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  49466. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  49467. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  49468. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  49469. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  49470. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  49471. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  49472. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  49473. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  49474. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  49475. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  49476. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  49477. };
  49478. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  49479. this._highlightsPostProcess.updateEffect();
  49480. };
  49481. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  49482. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  49483. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  49484. this._highlightsGain = amount;
  49485. };
  49486. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  49487. if (this._highlightsGain === -1) {
  49488. this._highlightsGain = 1.0;
  49489. }
  49490. this._highlightsThreshold = amount;
  49491. };
  49492. LensRenderingPipeline.prototype.disableHighlights = function () {
  49493. this._highlightsGain = -1;
  49494. };
  49495. /**
  49496. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  49497. */
  49498. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49499. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49500. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49501. this._chromaticAberrationPostProcess = undefined;
  49502. this._highlightsPostProcess = undefined;
  49503. this._depthOfFieldPostProcess = undefined;
  49504. this._grainTexture.dispose();
  49505. if (disableDepthRender)
  49506. this._scene.disableDepthRenderer();
  49507. };
  49508. // colors shifting and distortion
  49509. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  49510. var _this = this;
  49511. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  49512. [], // samplers
  49513. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49514. this._chromaticAberrationPostProcess.onApply = function (effect) {
  49515. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  49516. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49517. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49518. };
  49519. };
  49520. // highlights enhancing
  49521. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  49522. var _this = this;
  49523. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  49524. [], // samplers
  49525. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  49526. this._highlightsPostProcess.onApply = function (effect) {
  49527. effect.setFloat('gain', _this._highlightsGain);
  49528. effect.setFloat('threshold', _this._highlightsThreshold);
  49529. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  49530. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49531. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49532. };
  49533. };
  49534. // colors shifting and distortion
  49535. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  49536. var _this = this;
  49537. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  49538. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  49539. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  49540. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49541. this._depthOfFieldPostProcess.onApply = function (effect) {
  49542. effect.setTexture("depthSampler", _this._depthTexture);
  49543. effect.setTexture("grainSampler", _this._grainTexture);
  49544. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  49545. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  49546. effect.setFloat('grain_amount', _this._grainAmount);
  49547. effect.setBool('blur_noise', _this._blurNoise);
  49548. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49549. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49550. effect.setFloat('distortion', _this._distortion);
  49551. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  49552. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  49553. effect.setFloat('aperture', _this._dofAperture);
  49554. effect.setFloat('darken', _this._dofDarken);
  49555. effect.setFloat('edge_blur', _this._edgeBlur);
  49556. effect.setBool('highlights', (_this._highlightsGain !== -1));
  49557. effect.setFloat('near', _this._scene.activeCamera.minZ);
  49558. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  49559. };
  49560. };
  49561. // creates a black and white random noise texture, 512x512
  49562. LensRenderingPipeline.prototype._createGrainTexture = function () {
  49563. var size = 512;
  49564. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49565. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49566. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49567. var context = this._grainTexture.getContext();
  49568. var rand = function (min, max) {
  49569. return Math.random() * (max - min) + min;
  49570. };
  49571. var value;
  49572. for (var x = 0; x < size; x++) {
  49573. for (var y = 0; y < size; y++) {
  49574. value = Math.floor(rand(0.42, 0.58) * 255);
  49575. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  49576. context.fillRect(x, y, 1, 1);
  49577. }
  49578. }
  49579. this._grainTexture.update(false);
  49580. };
  49581. return LensRenderingPipeline;
  49582. }(BABYLON.PostProcessRenderPipeline));
  49583. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  49584. })(BABYLON || (BABYLON = {}));
  49585. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  49586. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  49587. var BABYLON;
  49588. (function (BABYLON) {
  49589. var StandardRenderingPipeline = (function (_super) {
  49590. __extends(StandardRenderingPipeline, _super);
  49591. /**
  49592. * @constructor
  49593. * @param {string} name - The rendering pipeline name
  49594. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49595. * @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)
  49596. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  49597. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49598. */
  49599. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  49600. if (originalPostProcess === void 0) { originalPostProcess = null; }
  49601. var _this = _super.call(this, scene.getEngine(), name) || this;
  49602. _this.downSampleX4PostProcess = null;
  49603. _this.brightPassPostProcess = null;
  49604. _this.gaussianBlurHPostProcesses = [];
  49605. _this.gaussianBlurVPostProcesses = [];
  49606. _this.textureAdderPostProcess = null;
  49607. _this.luminancePostProcess = null;
  49608. _this.luminanceDownSamplePostProcesses = [];
  49609. _this.hdrPostProcess = null;
  49610. _this.textureAdderFinalPostProcess = null;
  49611. _this.lensFlareFinalPostProcess = null;
  49612. _this.hdrFinalPostProcess = null;
  49613. _this.lensFlarePostProcess = null;
  49614. _this.lensFlareComposePostProcess = null;
  49615. _this.motionBlurPostProcess = null;
  49616. _this.depthOfFieldPostProcess = null;
  49617. // Values
  49618. _this.brightThreshold = 1.0;
  49619. _this.blurWidth = 2.0;
  49620. _this.horizontalBlur = false;
  49621. _this.gaussianCoefficient = 0.25;
  49622. _this.gaussianMean = 1.0;
  49623. _this.gaussianStandardDeviation = 1.0;
  49624. _this.exposure = 1.0;
  49625. _this.lensTexture = null;
  49626. _this.hdrMinimumLuminance = 1.0;
  49627. _this.hdrDecreaseRate = 0.5;
  49628. _this.hdrIncreaseRate = 0.5;
  49629. _this.lensColorTexture = null;
  49630. _this.lensFlareStrength = 20.0;
  49631. _this.lensFlareGhostDispersal = 1.4;
  49632. _this.lensFlareHaloWidth = 0.7;
  49633. _this.lensFlareDistortionStrength = 16.0;
  49634. _this.lensStarTexture = null;
  49635. _this.lensFlareDirtTexture = null;
  49636. _this.depthOfFieldDistance = 10.0;
  49637. _this.depthOfFieldBlurWidth = 2.0;
  49638. _this.motionStrength = 1.0;
  49639. // IAnimatable
  49640. _this.animations = [];
  49641. _this._depthRenderer = null;
  49642. _this._currentDepthOfFieldSource = null;
  49643. _this._currentHDRSource = null;
  49644. _this._hdrCurrentLuminance = 1.0;
  49645. _this._motionBlurSamples = 64;
  49646. // Getters and setters
  49647. _this._depthOfFieldEnabled = true;
  49648. _this._lensFlareEnabled = true;
  49649. _this._hdrEnabled = true;
  49650. _this._motionBlurEnabled = true;
  49651. _this._cameras = cameras || [];
  49652. // Initialize
  49653. _this._scene = scene;
  49654. // Misc
  49655. var floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49656. // Create pass post-process
  49657. if (!originalPostProcess) {
  49658. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", floatTextureType);
  49659. }
  49660. else {
  49661. _this.originalPostProcess = originalPostProcess;
  49662. }
  49663. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  49664. // Create down sample X4 post-process
  49665. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  49666. // Create bright pass post-process
  49667. _this._createBrightPassPostProcess(scene, ratio / 2);
  49668. // Create gaussian blur post-processes (down sampling blurs)
  49669. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  49670. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  49671. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  49672. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  49673. // Create texture adder post-process
  49674. _this._createTextureAdderPostProcess(scene, ratio);
  49675. // Create depth-of-field source post-process
  49676. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49677. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  49678. // Create lens flare post-process
  49679. _this._createLensFlarePostProcess(scene, ratio);
  49680. // Create depth-of-field source post-process post lens-flare and disable it now
  49681. _this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49682. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  49683. // Create luminance
  49684. _this._createLuminancePostProcesses(scene, floatTextureType);
  49685. // Create HDR
  49686. _this._createHdrPostProcess(scene, ratio);
  49687. // Create depth-of-field source post-process post hdr and disable it now
  49688. _this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49689. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  49690. // Create gaussian blur used by depth-of-field
  49691. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  49692. // Create depth-of-field post-process
  49693. _this._createDepthOfFieldPostProcess(scene, ratio);
  49694. // Create motion blur post-process
  49695. _this._createMotionBlurPostProcess(scene, ratio);
  49696. // Finish
  49697. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49698. if (cameras !== null) {
  49699. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49700. }
  49701. // Deactivate
  49702. _this.LensFlareEnabled = false;
  49703. _this.DepthOfFieldEnabled = false;
  49704. _this.HDREnabled = false;
  49705. _this.MotionBlurEnabled = false;
  49706. return _this;
  49707. }
  49708. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  49709. get: function () {
  49710. return this._depthOfFieldEnabled;
  49711. },
  49712. set: function (enabled) {
  49713. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  49714. if (enabled && !this._depthOfFieldEnabled) {
  49715. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  49716. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  49717. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  49718. this._depthRenderer = this._scene.enableDepthRenderer();
  49719. }
  49720. else if (!enabled && this._depthOfFieldEnabled) {
  49721. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  49722. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  49723. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  49724. }
  49725. this._depthOfFieldEnabled = enabled;
  49726. },
  49727. enumerable: true,
  49728. configurable: true
  49729. });
  49730. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  49731. get: function () {
  49732. return this._lensFlareEnabled;
  49733. },
  49734. set: function (enabled) {
  49735. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  49736. if (enabled && !this._lensFlareEnabled) {
  49737. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  49738. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  49739. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  49740. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  49741. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  49742. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  49743. }
  49744. else if (!enabled && this._lensFlareEnabled) {
  49745. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  49746. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  49747. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  49748. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  49749. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  49750. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  49751. }
  49752. this._lensFlareEnabled = enabled;
  49753. },
  49754. enumerable: true,
  49755. configurable: true
  49756. });
  49757. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  49758. get: function () {
  49759. return this._hdrEnabled;
  49760. },
  49761. set: function (enabled) {
  49762. if (enabled && !this._hdrEnabled) {
  49763. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  49764. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  49765. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  49766. }
  49767. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  49768. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  49769. }
  49770. else if (!enabled && this._hdrEnabled) {
  49771. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  49772. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  49773. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  49774. }
  49775. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  49776. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  49777. }
  49778. this._hdrEnabled = enabled;
  49779. },
  49780. enumerable: true,
  49781. configurable: true
  49782. });
  49783. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  49784. get: function () {
  49785. return this._motionBlurEnabled;
  49786. },
  49787. set: function (enabled) {
  49788. if (enabled && !this._motionBlurEnabled) {
  49789. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  49790. this._depthRenderer = this._scene.enableDepthRenderer();
  49791. }
  49792. else if (!enabled && this._motionBlurEnabled) {
  49793. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  49794. }
  49795. this._motionBlurEnabled = enabled;
  49796. },
  49797. enumerable: true,
  49798. configurable: true
  49799. });
  49800. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  49801. get: function () {
  49802. return this._motionBlurSamples;
  49803. },
  49804. set: function (samples) {
  49805. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  49806. this._motionBlurSamples = samples;
  49807. },
  49808. enumerable: true,
  49809. configurable: true
  49810. });
  49811. // Down Sample X4 Post-Processs
  49812. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  49813. var _this = this;
  49814. var downSampleX4Offsets = new Array(32);
  49815. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49816. this.downSampleX4PostProcess.onApply = function (effect) {
  49817. var id = 0;
  49818. for (var i = -2; i < 2; i++) {
  49819. for (var j = -2; j < 2; j++) {
  49820. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  49821. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  49822. id += 2;
  49823. }
  49824. }
  49825. effect.setArray2("dsOffsets", downSampleX4Offsets);
  49826. };
  49827. // Add to pipeline
  49828. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  49829. };
  49830. // Brightpass Post-Process
  49831. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  49832. var _this = this;
  49833. var brightOffsets = new Array(8);
  49834. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49835. this.brightPassPostProcess.onApply = function (effect) {
  49836. var sU = (1.0 / _this.brightPassPostProcess.width);
  49837. var sV = (1.0 / _this.brightPassPostProcess.height);
  49838. brightOffsets[0] = -0.5 * sU;
  49839. brightOffsets[1] = 0.5 * sV;
  49840. brightOffsets[2] = 0.5 * sU;
  49841. brightOffsets[3] = 0.5 * sV;
  49842. brightOffsets[4] = -0.5 * sU;
  49843. brightOffsets[5] = -0.5 * sV;
  49844. brightOffsets[6] = 0.5 * sU;
  49845. brightOffsets[7] = -0.5 * sV;
  49846. effect.setArray2("dsOffsets", brightOffsets);
  49847. effect.setFloat("brightThreshold", _this.brightThreshold);
  49848. };
  49849. // Add to pipeline
  49850. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  49851. };
  49852. // Create gaussian blur H&V post-processes
  49853. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  49854. var _this = this;
  49855. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  49856. var blurOffsets = new Array(9);
  49857. var blurWeights = new Array(9);
  49858. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  49859. var callback = function (height) {
  49860. return function (effect) {
  49861. // Weights
  49862. var x = 0.0;
  49863. for (var i = 0; i < 9; i++) {
  49864. x = (i - 4.0) / 4.0;
  49865. blurWeights[i] =
  49866. _this.gaussianCoefficient
  49867. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  49868. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  49869. }
  49870. var lastOutputDimensions = {
  49871. width: scene.getEngine().getRenderWidth(),
  49872. height: scene.getEngine().getRenderHeight()
  49873. };
  49874. for (var i = 0; i < 9; i++) {
  49875. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  49876. blurOffsets[i] = value;
  49877. }
  49878. effect.setArray("blurOffsets", blurOffsets);
  49879. effect.setArray("blurWeights", blurWeights);
  49880. if (height) {
  49881. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  49882. }
  49883. else {
  49884. effect.setFloat("blurWidth", _this[blurWidthKey]);
  49885. }
  49886. };
  49887. };
  49888. // Create horizontal gaussian blur post-processes
  49889. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49890. gaussianBlurHPostProcess.onApply = callback(false);
  49891. // Create vertical gaussian blur post-process
  49892. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49893. gaussianBlurVPostProcess.onApply = callback(true);
  49894. // Add to pipeline
  49895. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  49896. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  49897. // Finish
  49898. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  49899. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  49900. };
  49901. // Create texture adder post-process
  49902. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  49903. var _this = this;
  49904. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49905. this.textureAdderPostProcess.onApply = function (effect) {
  49906. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  49907. effect.setTexture("lensSampler", _this.lensTexture);
  49908. effect.setFloat("exposure", _this.exposure);
  49909. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  49910. _this._currentHDRSource = _this.textureAdderFinalPostProcess;
  49911. };
  49912. // Add to pipeline
  49913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  49914. };
  49915. // Create luminance
  49916. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  49917. var _this = this;
  49918. // Create luminance
  49919. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  49920. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  49921. var offsets = [];
  49922. this.luminancePostProcess.onApply = function (effect) {
  49923. var sU = (1.0 / _this.luminancePostProcess.width);
  49924. var sV = (1.0 / _this.luminancePostProcess.height);
  49925. offsets[0] = -0.5 * sU;
  49926. offsets[1] = 0.5 * sV;
  49927. offsets[2] = 0.5 * sU;
  49928. offsets[3] = 0.5 * sV;
  49929. offsets[4] = -0.5 * sU;
  49930. offsets[5] = -0.5 * sV;
  49931. offsets[6] = 0.5 * sU;
  49932. offsets[7] = -0.5 * sV;
  49933. effect.setArray2("lumOffsets", offsets);
  49934. };
  49935. // Add to pipeline
  49936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  49937. // Create down sample luminance
  49938. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  49939. var size = Math.pow(3, i);
  49940. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  49941. if (i === 0) {
  49942. defines += "#define FINAL_DOWN_SAMPLER";
  49943. }
  49944. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  49945. this.luminanceDownSamplePostProcesses.push(postProcess);
  49946. }
  49947. // Create callbacks and add effects
  49948. var lastLuminance = this.luminancePostProcess;
  49949. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  49950. var downSampleOffsets = new Array(18);
  49951. pp.onApply = function (effect) {
  49952. var id = 0;
  49953. for (var x = -1; x < 2; x++) {
  49954. for (var y = -1; y < 2; y++) {
  49955. downSampleOffsets[id] = x / lastLuminance.width;
  49956. downSampleOffsets[id + 1] = y / lastLuminance.height;
  49957. id += 2;
  49958. }
  49959. }
  49960. effect.setArray2("dsOffsets", downSampleOffsets);
  49961. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  49962. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  49963. lastLuminance = _this.luminancePostProcess;
  49964. }
  49965. else {
  49966. lastLuminance = pp;
  49967. }
  49968. };
  49969. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  49970. pp.onAfterRender = function (effect) {
  49971. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  49972. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  49973. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  49974. };
  49975. }
  49976. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  49977. });
  49978. };
  49979. // Create HDR post-process
  49980. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  49981. var _this = this;
  49982. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49983. var outputLiminance = 1;
  49984. var time = 0;
  49985. var lastTime = 0;
  49986. this.hdrPostProcess.onApply = function (effect) {
  49987. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentHDRSource);
  49988. time += scene.getEngine().getDeltaTime();
  49989. if (outputLiminance < 0) {
  49990. outputLiminance = _this._hdrCurrentLuminance;
  49991. }
  49992. else {
  49993. var dt = (lastTime - time) / 1000.0;
  49994. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  49995. outputLiminance += _this.hdrDecreaseRate * dt;
  49996. }
  49997. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  49998. outputLiminance -= _this.hdrIncreaseRate * dt;
  49999. }
  50000. else {
  50001. outputLiminance = _this._hdrCurrentLuminance;
  50002. }
  50003. }
  50004. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  50005. effect.setFloat("averageLuminance", outputLiminance);
  50006. lastTime = time;
  50007. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  50008. };
  50009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  50010. };
  50011. // Create lens flare post-process
  50012. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  50013. var _this = this;
  50014. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  50016. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  50017. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  50019. var resolution = new BABYLON.Vector2(0, 0);
  50020. // Lens flare
  50021. this.lensFlarePostProcess.onApply = function (effect) {
  50022. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  50023. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  50024. effect.setFloat("strength", _this.lensFlareStrength);
  50025. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  50026. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  50027. // Shift
  50028. resolution.x = _this.lensFlarePostProcess.width;
  50029. resolution.y = _this.lensFlarePostProcess.height;
  50030. effect.setVector2("resolution", resolution);
  50031. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  50032. };
  50033. // Compose
  50034. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  50035. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  50036. this.lensFlareComposePostProcess.onApply = function (effect) {
  50037. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  50038. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  50039. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  50040. // Lens start rotation matrix
  50041. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  50042. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  50043. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  50044. camRot *= 4.0;
  50045. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  50046. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  50047. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  50048. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  50049. _this._currentHDRSource = _this.lensFlareFinalPostProcess;
  50050. };
  50051. };
  50052. // Create depth-of-field post-process
  50053. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  50054. var _this = this;
  50055. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50056. this.depthOfFieldPostProcess.onApply = function (effect) {
  50057. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  50058. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  50059. effect.setFloat("distance", _this.depthOfFieldDistance);
  50060. };
  50061. // Add to pipeline
  50062. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  50063. };
  50064. // Create motion blur post-process
  50065. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  50066. var _this = this;
  50067. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50068. var motionScale = 0;
  50069. var prevViewProjection = BABYLON.Matrix.Identity();
  50070. var invViewProjection = BABYLON.Matrix.Identity();
  50071. var viewProjection = BABYLON.Matrix.Identity();
  50072. var screenSize = BABYLON.Vector2.Zero();
  50073. this.motionBlurPostProcess.onApply = function (effect) {
  50074. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  50075. viewProjection.invertToRef(invViewProjection);
  50076. effect.setMatrix("inverseViewProjection", invViewProjection);
  50077. effect.setMatrix("prevViewProjection", prevViewProjection);
  50078. prevViewProjection = viewProjection;
  50079. screenSize.x = _this.motionBlurPostProcess.width;
  50080. screenSize.y = _this.motionBlurPostProcess.height;
  50081. effect.setVector2("screenSize", screenSize);
  50082. motionScale = scene.getEngine().getFps() / 60.0;
  50083. effect.setFloat("motionScale", motionScale);
  50084. effect.setFloat("motionStrength", _this.motionStrength);
  50085. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  50086. };
  50087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  50088. };
  50089. // Dispose
  50090. StandardRenderingPipeline.prototype.dispose = function () {
  50091. for (var i = 0; i < this._cameras.length; i++) {
  50092. var camera = this._cameras[i];
  50093. this.originalPostProcess.dispose(camera);
  50094. this.downSampleX4PostProcess.dispose(camera);
  50095. this.brightPassPostProcess.dispose(camera);
  50096. this.textureAdderPostProcess.dispose(camera);
  50097. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  50098. this.gaussianBlurHPostProcesses[j].dispose(camera);
  50099. }
  50100. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  50101. this.gaussianBlurVPostProcesses[j].dispose(camera);
  50102. }
  50103. this.textureAdderFinalPostProcess.dispose(camera);
  50104. this.lensFlarePostProcess.dispose(camera);
  50105. this.lensFlareComposePostProcess.dispose(camera);
  50106. this.depthOfFieldPostProcess.dispose(camera);
  50107. this.motionBlurPostProcess.dispose(camera);
  50108. }
  50109. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  50110. _super.prototype.dispose.call(this);
  50111. };
  50112. // Serialize rendering pipeline
  50113. StandardRenderingPipeline.prototype.serialize = function () {
  50114. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50115. serializationObject.customType = "StandardRenderingPipeline";
  50116. return serializationObject;
  50117. };
  50118. // Parse serialized pipeline
  50119. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  50120. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  50121. };
  50122. return StandardRenderingPipeline;
  50123. }(BABYLON.PostProcessRenderPipeline));
  50124. // Luminance steps
  50125. StandardRenderingPipeline.LuminanceSteps = 6;
  50126. __decorate([
  50127. BABYLON.serialize()
  50128. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  50129. __decorate([
  50130. BABYLON.serialize()
  50131. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  50132. __decorate([
  50133. BABYLON.serialize()
  50134. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  50135. __decorate([
  50136. BABYLON.serialize()
  50137. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  50138. __decorate([
  50139. BABYLON.serialize()
  50140. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  50141. __decorate([
  50142. BABYLON.serialize()
  50143. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  50144. __decorate([
  50145. BABYLON.serialize()
  50146. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  50147. __decorate([
  50148. BABYLON.serializeAsTexture("lensTexture")
  50149. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  50150. __decorate([
  50151. BABYLON.serialize()
  50152. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  50153. __decorate([
  50154. BABYLON.serialize()
  50155. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  50156. __decorate([
  50157. BABYLON.serialize()
  50158. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  50159. __decorate([
  50160. BABYLON.serializeAsTexture("lensColorTexture")
  50161. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  50162. __decorate([
  50163. BABYLON.serialize()
  50164. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  50165. __decorate([
  50166. BABYLON.serialize()
  50167. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  50168. __decorate([
  50169. BABYLON.serialize()
  50170. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  50171. __decorate([
  50172. BABYLON.serialize()
  50173. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  50174. __decorate([
  50175. BABYLON.serializeAsTexture("lensStarTexture")
  50176. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  50177. __decorate([
  50178. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  50179. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  50180. __decorate([
  50181. BABYLON.serialize()
  50182. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  50183. __decorate([
  50184. BABYLON.serialize()
  50185. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  50186. __decorate([
  50187. BABYLON.serialize()
  50188. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  50189. __decorate([
  50190. BABYLON.serialize()
  50191. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  50192. __decorate([
  50193. BABYLON.serialize()
  50194. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  50195. __decorate([
  50196. BABYLON.serialize()
  50197. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  50198. __decorate([
  50199. BABYLON.serialize()
  50200. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  50201. __decorate([
  50202. BABYLON.serialize()
  50203. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  50204. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  50205. })(BABYLON || (BABYLON = {}));
  50206. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  50207. var BABYLON;
  50208. (function (BABYLON) {
  50209. var GeometryBufferRenderer = (function () {
  50210. function GeometryBufferRenderer(scene, ratio) {
  50211. if (ratio === void 0) { ratio = 1; }
  50212. var _this = this;
  50213. this._viewMatrix = BABYLON.Matrix.Zero();
  50214. this._projectionMatrix = BABYLON.Matrix.Zero();
  50215. this._transformMatrix = BABYLON.Matrix.Zero();
  50216. this._worldViewProjection = BABYLON.Matrix.Zero();
  50217. this._scene = scene;
  50218. var engine = scene.getEngine();
  50219. // Render target
  50220. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, 2, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  50221. if (!this.isSupported) {
  50222. return null;
  50223. }
  50224. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50225. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50226. this._multiRenderTarget.refreshRate = 1;
  50227. this._multiRenderTarget.renderParticles = false;
  50228. this._multiRenderTarget.renderList = null;
  50229. // set default depth value to 1.0 (far away)
  50230. this._multiRenderTarget.onClearObservable.add(function (engine) {
  50231. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  50232. });
  50233. // Custom render function
  50234. var renderSubMesh = function (subMesh) {
  50235. var mesh = subMesh.getRenderingMesh();
  50236. var scene = _this._scene;
  50237. var engine = scene.getEngine();
  50238. // Culling
  50239. engine.setState(subMesh.getMaterial().backFaceCulling);
  50240. // Managing instances
  50241. var batch = mesh._getInstancesRenderList(subMesh._id);
  50242. if (batch.mustReturn) {
  50243. return;
  50244. }
  50245. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50246. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50247. engine.enableEffect(_this._effect);
  50248. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50249. var material = subMesh.getMaterial();
  50250. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50251. _this._effect.setMatrix("view", scene.getViewMatrix());
  50252. // Alpha test
  50253. if (material && material.needAlphaTesting()) {
  50254. var alphaTexture = material.getAlphaTestTexture();
  50255. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50256. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50257. }
  50258. // Bones
  50259. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50260. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50261. }
  50262. // Draw
  50263. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50264. }
  50265. };
  50266. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50267. var index;
  50268. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50269. renderSubMesh(opaqueSubMeshes.data[index]);
  50270. }
  50271. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50272. renderSubMesh(alphaTestSubMeshes.data[index]);
  50273. }
  50274. };
  50275. }
  50276. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  50277. set: function (meshes) {
  50278. this._multiRenderTarget.renderList = meshes;
  50279. },
  50280. enumerable: true,
  50281. configurable: true
  50282. });
  50283. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  50284. get: function () {
  50285. return this._multiRenderTarget.isSupported;
  50286. },
  50287. enumerable: true,
  50288. configurable: true
  50289. });
  50290. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  50291. var material = subMesh.getMaterial();
  50292. if (material && material.disableDepthWrite) {
  50293. return false;
  50294. }
  50295. var defines = [];
  50296. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50297. var mesh = subMesh.getMesh();
  50298. var scene = mesh.getScene();
  50299. // Alpha test
  50300. if (material && material.needAlphaTesting()) {
  50301. defines.push("#define ALPHATEST");
  50302. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50303. attribs.push(BABYLON.VertexBuffer.UVKind);
  50304. defines.push("#define UV1");
  50305. }
  50306. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50307. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50308. defines.push("#define UV2");
  50309. }
  50310. }
  50311. // Bones
  50312. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50313. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50314. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50315. if (mesh.numBoneInfluencers > 4) {
  50316. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50317. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50318. }
  50319. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50320. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50321. }
  50322. else {
  50323. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50324. }
  50325. // Instances
  50326. if (useInstances) {
  50327. defines.push("#define INSTANCES");
  50328. attribs.push("world0");
  50329. attribs.push("world1");
  50330. attribs.push("world2");
  50331. attribs.push("world3");
  50332. }
  50333. // Get correct effect
  50334. var join = defines.join("\n");
  50335. if (this._cachedDefines !== join) {
  50336. this._cachedDefines = join;
  50337. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  50338. }
  50339. return this._effect.isReady();
  50340. };
  50341. GeometryBufferRenderer.prototype.getGBuffer = function () {
  50342. return this._multiRenderTarget;
  50343. };
  50344. // Methods
  50345. GeometryBufferRenderer.prototype.dispose = function () {
  50346. this.getGBuffer().dispose();
  50347. };
  50348. return GeometryBufferRenderer;
  50349. }());
  50350. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  50351. })(BABYLON || (BABYLON = {}));
  50352. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  50353. var BABYLON;
  50354. (function (BABYLON) {
  50355. var RefractionPostProcess = (function (_super) {
  50356. __extends(RefractionPostProcess, _super);
  50357. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50358. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50359. _this.color = color;
  50360. _this.depth = depth;
  50361. _this.colorLevel = colorLevel;
  50362. _this.onActivateObservable.add(function (cam) {
  50363. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50364. });
  50365. _this.onApplyObservable.add(function (effect) {
  50366. effect.setColor3("baseColor", _this.color);
  50367. effect.setFloat("depth", _this.depth);
  50368. effect.setFloat("colorLevel", _this.colorLevel);
  50369. effect.setTexture("refractionSampler", _this._refRexture);
  50370. });
  50371. return _this;
  50372. }
  50373. // Methods
  50374. RefractionPostProcess.prototype.dispose = function (camera) {
  50375. if (this._refRexture) {
  50376. this._refRexture.dispose();
  50377. }
  50378. _super.prototype.dispose.call(this, camera);
  50379. };
  50380. return RefractionPostProcess;
  50381. }(BABYLON.PostProcess));
  50382. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50383. })(BABYLON || (BABYLON = {}));
  50384. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50385. var BABYLON;
  50386. (function (BABYLON) {
  50387. var BlackAndWhitePostProcess = (function (_super) {
  50388. __extends(BlackAndWhitePostProcess, _super);
  50389. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50390. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  50391. _this.degree = 1;
  50392. _this.onApplyObservable.add(function (effect) {
  50393. effect.setFloat("degree", _this.degree);
  50394. });
  50395. return _this;
  50396. }
  50397. return BlackAndWhitePostProcess;
  50398. }(BABYLON.PostProcess));
  50399. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50400. })(BABYLON || (BABYLON = {}));
  50401. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50402. var BABYLON;
  50403. (function (BABYLON) {
  50404. var ConvolutionPostProcess = (function (_super) {
  50405. __extends(ConvolutionPostProcess, _super);
  50406. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50407. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50408. _this.kernel = kernel;
  50409. _this.onApply = function (effect) {
  50410. effect.setFloat2("screenSize", _this.width, _this.height);
  50411. effect.setArray("kernel", _this.kernel);
  50412. };
  50413. return _this;
  50414. }
  50415. return ConvolutionPostProcess;
  50416. }(BABYLON.PostProcess));
  50417. // Statics
  50418. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50419. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50420. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50421. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50422. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50423. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50424. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50425. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50426. })(BABYLON || (BABYLON = {}));
  50427. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  50428. var BABYLON;
  50429. (function (BABYLON) {
  50430. var FilterPostProcess = (function (_super) {
  50431. __extends(FilterPostProcess, _super);
  50432. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50433. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  50434. _this.kernelMatrix = kernelMatrix;
  50435. _this.onApply = function (effect) {
  50436. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50437. };
  50438. return _this;
  50439. }
  50440. return FilterPostProcess;
  50441. }(BABYLON.PostProcess));
  50442. BABYLON.FilterPostProcess = FilterPostProcess;
  50443. })(BABYLON || (BABYLON = {}));
  50444. //# sourceMappingURL=babylon.filterPostProcess.js.map
  50445. var BABYLON;
  50446. (function (BABYLON) {
  50447. var FxaaPostProcess = (function (_super) {
  50448. __extends(FxaaPostProcess, _super);
  50449. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50450. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50451. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType) || this;
  50452. _this.onApplyObservable.add(function (effect) {
  50453. var texelSize = _this.texelSize;
  50454. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  50455. });
  50456. return _this;
  50457. }
  50458. return FxaaPostProcess;
  50459. }(BABYLON.PostProcess));
  50460. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50461. })(BABYLON || (BABYLON = {}));
  50462. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50463. var BABYLON;
  50464. (function (BABYLON) {
  50465. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  50466. var VolumetricLightScatteringPostProcess = (function (_super) {
  50467. __extends(VolumetricLightScatteringPostProcess, _super);
  50468. /**
  50469. * @constructor
  50470. * @param {string} name - The post-process name
  50471. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  50472. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  50473. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  50474. * @param {number} samples - The post-process quality, default 100
  50475. * @param {number} samplingMode - The post-process filtering mode
  50476. * @param {BABYLON.Engine} engine - The babylon engine
  50477. * @param {boolean} reusable - If the post-process is reusable
  50478. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  50479. */
  50480. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  50481. if (samples === void 0) { samples = 100; }
  50482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50483. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  50484. _this._screenCoordinates = BABYLON.Vector2.Zero();
  50485. /**
  50486. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  50487. * @type {Vector3}
  50488. */
  50489. _this.customMeshPosition = BABYLON.Vector3.Zero();
  50490. /**
  50491. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  50492. * @type {boolean}
  50493. */
  50494. _this.useCustomMeshPosition = false;
  50495. /**
  50496. * If the post-process should inverse the light scattering direction
  50497. * @type {boolean}
  50498. */
  50499. _this.invert = true;
  50500. /**
  50501. * Array containing the excluded meshes not rendered in the internal pass
  50502. */
  50503. _this.excludedMeshes = new Array();
  50504. /**
  50505. * Controls the overall intensity of the post-process
  50506. * @type {number}
  50507. */
  50508. _this.exposure = 0.3;
  50509. /**
  50510. * Dissipates each sample's contribution in range [0, 1]
  50511. * @type {number}
  50512. */
  50513. _this.decay = 0.96815;
  50514. /**
  50515. * Controls the overall intensity of each sample
  50516. * @type {number}
  50517. */
  50518. _this.weight = 0.58767;
  50519. /**
  50520. * Controls the density of each sample
  50521. * @type {number}
  50522. */
  50523. _this.density = 0.926;
  50524. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  50525. var engine = scene.getEngine();
  50526. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  50527. // Configure mesh
  50528. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  50529. // Configure
  50530. _this._createPass(scene, ratio.passRatio || ratio);
  50531. _this.onActivate = function (camera) {
  50532. if (!_this.isSupported) {
  50533. _this.dispose(camera);
  50534. }
  50535. _this.onActivate = null;
  50536. };
  50537. _this.onApplyObservable.add(function (effect) {
  50538. _this._updateMeshScreenCoordinates(scene);
  50539. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  50540. effect.setFloat("exposure", _this.exposure);
  50541. effect.setFloat("decay", _this.decay);
  50542. effect.setFloat("weight", _this.weight);
  50543. effect.setFloat("density", _this.density);
  50544. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  50545. });
  50546. return _this;
  50547. }
  50548. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  50549. get: function () {
  50550. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50551. return false;
  50552. },
  50553. set: function (useDiffuseColor) {
  50554. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50555. },
  50556. enumerable: true,
  50557. configurable: true
  50558. });
  50559. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  50560. var mesh = subMesh.getMesh();
  50561. // Render this.mesh as default
  50562. if (mesh === this.mesh) {
  50563. return mesh.material.isReady(mesh);
  50564. }
  50565. var defines = [];
  50566. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50567. var material = subMesh.getMaterial();
  50568. var needUV = false;
  50569. // Alpha test
  50570. if (material) {
  50571. if (material.needAlphaTesting()) {
  50572. defines.push("#define ALPHATEST");
  50573. }
  50574. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50575. attribs.push(BABYLON.VertexBuffer.UVKind);
  50576. defines.push("#define UV1");
  50577. }
  50578. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50579. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50580. defines.push("#define UV2");
  50581. }
  50582. }
  50583. // Bones
  50584. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50585. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50586. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50587. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50588. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50589. }
  50590. else {
  50591. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50592. }
  50593. // Instances
  50594. if (useInstances) {
  50595. defines.push("#define INSTANCES");
  50596. attribs.push("world0");
  50597. attribs.push("world1");
  50598. attribs.push("world2");
  50599. attribs.push("world3");
  50600. }
  50601. // Get correct effect
  50602. var join = defines.join("\n");
  50603. if (this._cachedDefines !== join) {
  50604. this._cachedDefines = join;
  50605. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  50606. }
  50607. return this._volumetricLightScatteringPass.isReady();
  50608. };
  50609. /**
  50610. * Sets the new light position for light scattering effect
  50611. * @param {BABYLON.Vector3} The new custom light position
  50612. */
  50613. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  50614. this.customMeshPosition = position;
  50615. };
  50616. /**
  50617. * Returns the light position for light scattering effect
  50618. * @return {BABYLON.Vector3} The custom light position
  50619. */
  50620. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  50621. return this.customMeshPosition;
  50622. };
  50623. /**
  50624. * Disposes the internal assets and detaches the post-process from the camera
  50625. */
  50626. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  50627. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  50628. if (rttIndex !== -1) {
  50629. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  50630. }
  50631. this._volumetricLightScatteringRTT.dispose();
  50632. _super.prototype.dispose.call(this, camera);
  50633. };
  50634. /**
  50635. * Returns the render target texture used by the post-process
  50636. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  50637. */
  50638. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  50639. return this._volumetricLightScatteringRTT;
  50640. };
  50641. // Private methods
  50642. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  50643. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  50644. return true;
  50645. }
  50646. return false;
  50647. };
  50648. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  50649. var _this = this;
  50650. var engine = scene.getEngine();
  50651. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50652. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50653. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50654. this._volumetricLightScatteringRTT.renderList = null;
  50655. this._volumetricLightScatteringRTT.renderParticles = false;
  50656. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  50657. // Custom render function for submeshes
  50658. var renderSubMesh = function (subMesh) {
  50659. var mesh = subMesh.getRenderingMesh();
  50660. if (_this._meshExcluded(mesh)) {
  50661. return;
  50662. }
  50663. var scene = mesh.getScene();
  50664. var engine = scene.getEngine();
  50665. // Culling
  50666. engine.setState(subMesh.getMaterial().backFaceCulling);
  50667. // Managing instances
  50668. var batch = mesh._getInstancesRenderList(subMesh._id);
  50669. if (batch.mustReturn) {
  50670. return;
  50671. }
  50672. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50673. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50674. var effect = _this._volumetricLightScatteringPass;
  50675. if (mesh === _this.mesh) {
  50676. if (subMesh.effect) {
  50677. effect = subMesh.effect;
  50678. }
  50679. else {
  50680. effect = subMesh.getMaterial().getEffect();
  50681. }
  50682. }
  50683. engine.enableEffect(effect);
  50684. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  50685. if (mesh === _this.mesh) {
  50686. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  50687. }
  50688. else {
  50689. var material = subMesh.getMaterial();
  50690. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  50691. // Alpha test
  50692. if (material && material.needAlphaTesting()) {
  50693. var alphaTexture = material.getAlphaTestTexture();
  50694. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  50695. if (alphaTexture) {
  50696. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50697. }
  50698. }
  50699. // Bones
  50700. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50701. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50702. }
  50703. }
  50704. // Draw
  50705. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  50706. }
  50707. };
  50708. // Render target texture callbacks
  50709. var savedSceneClearColor;
  50710. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  50711. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  50712. savedSceneClearColor = scene.clearColor;
  50713. scene.clearColor = sceneClearColor;
  50714. });
  50715. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  50716. scene.clearColor = savedSceneClearColor;
  50717. });
  50718. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  50719. var engine = scene.getEngine();
  50720. var index;
  50721. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50722. renderSubMesh(opaqueSubMeshes.data[index]);
  50723. }
  50724. engine.setAlphaTesting(true);
  50725. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50726. renderSubMesh(alphaTestSubMeshes.data[index]);
  50727. }
  50728. engine.setAlphaTesting(false);
  50729. if (transparentSubMeshes.length) {
  50730. // Sort sub meshes
  50731. for (index = 0; index < transparentSubMeshes.length; index++) {
  50732. var submesh = transparentSubMeshes.data[index];
  50733. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  50734. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  50735. }
  50736. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  50737. sortedArray.sort(function (a, b) {
  50738. // Alpha index first
  50739. if (a._alphaIndex > b._alphaIndex) {
  50740. return 1;
  50741. }
  50742. if (a._alphaIndex < b._alphaIndex) {
  50743. return -1;
  50744. }
  50745. // Then distance to camera
  50746. if (a._distanceToCamera < b._distanceToCamera) {
  50747. return 1;
  50748. }
  50749. if (a._distanceToCamera > b._distanceToCamera) {
  50750. return -1;
  50751. }
  50752. return 0;
  50753. });
  50754. // Render sub meshes
  50755. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50756. for (index = 0; index < sortedArray.length; index++) {
  50757. renderSubMesh(sortedArray[index]);
  50758. }
  50759. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50760. }
  50761. };
  50762. };
  50763. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  50764. var transform = scene.getTransformMatrix();
  50765. var meshPosition;
  50766. if (this.useCustomMeshPosition) {
  50767. meshPosition = this.customMeshPosition;
  50768. }
  50769. else if (this.attachedNode) {
  50770. meshPosition = this.attachedNode.position;
  50771. }
  50772. else {
  50773. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  50774. }
  50775. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  50776. this._screenCoordinates.x = pos.x / this._viewPort.width;
  50777. this._screenCoordinates.y = pos.y / this._viewPort.height;
  50778. if (this.invert)
  50779. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  50780. };
  50781. // Static methods
  50782. /**
  50783. * Creates a default mesh for the Volumeric Light Scattering post-process
  50784. * @param {string} The mesh name
  50785. * @param {BABYLON.Scene} The scene where to create the mesh
  50786. * @return {BABYLON.Mesh} the default mesh
  50787. */
  50788. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  50789. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  50790. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  50791. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  50792. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  50793. mesh.material = material;
  50794. return mesh;
  50795. };
  50796. return VolumetricLightScatteringPostProcess;
  50797. }(BABYLON.PostProcess));
  50798. __decorate([
  50799. BABYLON.serializeAsVector3()
  50800. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  50801. __decorate([
  50802. BABYLON.serialize()
  50803. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  50804. __decorate([
  50805. BABYLON.serialize()
  50806. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  50807. __decorate([
  50808. BABYLON.serializeAsMeshReference()
  50809. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  50810. __decorate([
  50811. BABYLON.serialize()
  50812. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  50813. __decorate([
  50814. BABYLON.serialize()
  50815. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  50816. __decorate([
  50817. BABYLON.serialize()
  50818. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  50819. __decorate([
  50820. BABYLON.serialize()
  50821. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  50822. __decorate([
  50823. BABYLON.serialize()
  50824. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  50825. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  50826. })(BABYLON || (BABYLON = {}));
  50827. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  50828. //
  50829. // This post-process allows the modification of rendered colors by using
  50830. // a 'look-up table' (LUT). This effect is also called Color Grading.
  50831. //
  50832. // The object needs to be provided an url to a texture containing the color
  50833. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  50834. // Use an image editing software to tweak the LUT to match your needs.
  50835. //
  50836. // For an example of a color LUT, see here:
  50837. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  50838. // For explanations on color grading, see here:
  50839. // http://udn.epicgames.com/Three/ColorGrading.html
  50840. //
  50841. var BABYLON;
  50842. (function (BABYLON) {
  50843. var ColorCorrectionPostProcess = (function (_super) {
  50844. __extends(ColorCorrectionPostProcess, _super);
  50845. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  50846. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  50847. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50848. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  50849. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50850. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50851. _this.onApply = function (effect) {
  50852. effect.setTexture("colorTable", _this._colorTableTexture);
  50853. };
  50854. return _this;
  50855. }
  50856. return ColorCorrectionPostProcess;
  50857. }(BABYLON.PostProcess));
  50858. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  50859. })(BABYLON || (BABYLON = {}));
  50860. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  50861. var BABYLON;
  50862. (function (BABYLON) {
  50863. var TonemappingOperator;
  50864. (function (TonemappingOperator) {
  50865. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  50866. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  50867. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  50868. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  50869. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  50870. ;
  50871. var TonemapPostProcess = (function (_super) {
  50872. __extends(TonemapPostProcess, _super);
  50873. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  50874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50875. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50876. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  50877. _this._operator = _operator;
  50878. _this.exposureAdjustment = exposureAdjustment;
  50879. var defines = "#define ";
  50880. if (_this._operator === TonemappingOperator.Hable)
  50881. defines += "HABLE_TONEMAPPING";
  50882. else if (_this._operator === TonemappingOperator.Reinhard)
  50883. defines += "REINHARD_TONEMAPPING";
  50884. else if (_this._operator === TonemappingOperator.HejiDawson)
  50885. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  50886. else if (_this._operator === TonemappingOperator.Photographic)
  50887. defines += "PHOTOGRAPHIC_TONEMAPPING";
  50888. //sadly a second call to create the effect.
  50889. _this.updateEffect(defines);
  50890. _this.onApply = function (effect) {
  50891. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  50892. };
  50893. return _this;
  50894. }
  50895. return TonemapPostProcess;
  50896. }(BABYLON.PostProcess));
  50897. BABYLON.TonemapPostProcess = TonemapPostProcess;
  50898. })(BABYLON || (BABYLON = {}));
  50899. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  50900. var BABYLON;
  50901. (function (BABYLON) {
  50902. var DisplayPassPostProcess = (function (_super) {
  50903. __extends(DisplayPassPostProcess, _super);
  50904. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50905. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  50906. }
  50907. return DisplayPassPostProcess;
  50908. }(BABYLON.PostProcess));
  50909. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  50910. })(BABYLON || (BABYLON = {}));
  50911. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  50912. var BABYLON;
  50913. (function (BABYLON) {
  50914. var HighlightsPostProcess = (function (_super) {
  50915. __extends(HighlightsPostProcess, _super);
  50916. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50918. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  50919. }
  50920. return HighlightsPostProcess;
  50921. }(BABYLON.PostProcess));
  50922. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  50923. })(BABYLON || (BABYLON = {}));
  50924. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  50925. var BABYLON;
  50926. (function (BABYLON) {
  50927. var ImageProcessingPostProcess = (function (_super) {
  50928. __extends(ImageProcessingPostProcess, _super);
  50929. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50930. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50931. var _this = _super.call(this, name, "imageProcessing", [
  50932. 'contrast',
  50933. 'vignetteSettings1',
  50934. 'vignetteSettings2',
  50935. 'cameraExposureLinear',
  50936. 'vCameraColorCurveNegative',
  50937. 'vCameraColorCurveNeutral',
  50938. 'vCameraColorCurvePositive',
  50939. 'colorTransformSettings'
  50940. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  50941. _this.colorGradingWeight = 1.0;
  50942. _this.colorCurves = new BABYLON.ColorCurves();
  50943. _this.vignetteStretch = 0;
  50944. _this.vignetteCentreX = 0;
  50945. _this.vignetteCentreY = 0;
  50946. _this.vignetteWeight = 1.5;
  50947. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  50948. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  50949. _this.cameraContrast = 1.0;
  50950. _this.cameraExposureValue = 1.5;
  50951. _this._cameraToneMappingEnabled = true;
  50952. _this._updateParameters();
  50953. _this.onApply = function (effect) {
  50954. var aspectRatio = _this.aspectRatio;
  50955. // Color
  50956. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  50957. // Vignette
  50958. var vignetteScaleY = Math.tan(_this.getCamera().fov * 0.5);
  50959. var vignetteScaleX = vignetteScaleY * aspectRatio;
  50960. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  50961. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  50962. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  50963. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  50964. var vignettePower = -2.0 * _this.vignetteWeight;
  50965. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  50966. // Contrast and exposure
  50967. effect.setFloat('contrast', _this.cameraContrast);
  50968. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposureValue) * Math.PI);
  50969. // Color transform settings
  50970. if (_this._colorGradingTexture) {
  50971. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  50972. var textureSize = _this.colorGradingTexture.getSize().height;
  50973. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  50974. 0.5 / textureSize, // textureOffset
  50975. textureSize, // textureSize
  50976. _this.colorGradingWeight // weight
  50977. );
  50978. }
  50979. };
  50980. return _this;
  50981. }
  50982. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  50983. get: function () {
  50984. return this._colorGradingTexture;
  50985. },
  50986. set: function (value) {
  50987. if (this._colorGradingTexture === value) {
  50988. return;
  50989. }
  50990. this._colorGradingTexture = value;
  50991. this._updateParameters();
  50992. },
  50993. enumerable: true,
  50994. configurable: true
  50995. });
  50996. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  50997. get: function () {
  50998. return this._vignetteBlendMode;
  50999. },
  51000. set: function (value) {
  51001. if (this._vignetteBlendMode === value) {
  51002. return;
  51003. }
  51004. this._vignetteBlendMode = value;
  51005. this._updateParameters();
  51006. },
  51007. enumerable: true,
  51008. configurable: true
  51009. });
  51010. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  51011. get: function () {
  51012. return this._cameraToneMappingEnabled;
  51013. },
  51014. set: function (value) {
  51015. if (this._cameraToneMappingEnabled === value) {
  51016. return;
  51017. }
  51018. this._cameraToneMappingEnabled = value;
  51019. this._updateParameters();
  51020. },
  51021. enumerable: true,
  51022. configurable: true
  51023. });
  51024. ImageProcessingPostProcess.prototype._updateParameters = function () {
  51025. var defines = "";
  51026. if (this.colorGradingTexture) {
  51027. defines = "#define COLORGRADING\r\n";
  51028. }
  51029. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  51030. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  51031. }
  51032. else {
  51033. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  51034. }
  51035. if (this.cameraToneMappingEnabled) {
  51036. defines += "#define TONEMAPPING\r\n";
  51037. }
  51038. this.updateEffect(defines);
  51039. };
  51040. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  51041. get: function () {
  51042. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  51043. },
  51044. enumerable: true,
  51045. configurable: true
  51046. });
  51047. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  51048. get: function () {
  51049. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  51050. },
  51051. enumerable: true,
  51052. configurable: true
  51053. });
  51054. return ImageProcessingPostProcess;
  51055. }(BABYLON.PostProcess));
  51056. // Statics
  51057. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  51058. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  51059. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  51060. })(BABYLON || (BABYLON = {}));
  51061. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  51062. var BABYLON;
  51063. (function (BABYLON) {
  51064. var BlurPostProcess = (function (_super) {
  51065. __extends(BlurPostProcess, _super);
  51066. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  51067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51068. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51069. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  51070. _this.direction = direction;
  51071. _this.onApplyObservable.add(function (effect) {
  51072. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  51073. });
  51074. _this.kernel = kernel;
  51075. return _this;
  51076. }
  51077. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  51078. /**
  51079. * Gets the length in pixels of the blur sample region
  51080. */
  51081. get: function () {
  51082. return this._idealKernel;
  51083. },
  51084. /**
  51085. * Sets the length in pixels of the blur sample region
  51086. */
  51087. set: function (v) {
  51088. v = Math.max(v, 1);
  51089. this._idealKernel = v;
  51090. this._kernel = this._nearestBestKernel(v);
  51091. this._updateParameters();
  51092. },
  51093. enumerable: true,
  51094. configurable: true
  51095. });
  51096. BlurPostProcess.prototype._updateParameters = function () {
  51097. // Generate sampling offsets and weights
  51098. var N = this._kernel;
  51099. var centerIndex = (N - 1) / 2;
  51100. // Generate Gaussian sampling weights over kernel
  51101. var offsets = [];
  51102. var weights = [];
  51103. var totalWeight = 0;
  51104. for (var i = 0; i < N; i++) {
  51105. var u = i / (N - 1);
  51106. var w = this._gaussianWeight(u * 2.0 - 1);
  51107. offsets[i] = (i - centerIndex);
  51108. weights[i] = w;
  51109. totalWeight += w;
  51110. }
  51111. // Normalize weights
  51112. for (var i = 0; i < weights.length; i++) {
  51113. weights[i] /= totalWeight;
  51114. }
  51115. // Optimize: combine samples to take advantage of hardware linear sampling
  51116. // Walk from left to center, combining pairs (symmetrically)
  51117. var linearSamplingWeights = [];
  51118. var linearSamplingOffsets = [];
  51119. var linearSamplingMap = [];
  51120. for (var i = 0; i <= centerIndex; i += 2) {
  51121. var j = Math.min(i + 1, Math.floor(centerIndex));
  51122. var singleCenterSample = i === j;
  51123. if (singleCenterSample) {
  51124. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  51125. }
  51126. else {
  51127. var sharedCell = j === centerIndex;
  51128. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  51129. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  51130. if (offsetLinear === 0) {
  51131. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  51132. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  51133. }
  51134. else {
  51135. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  51136. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  51137. }
  51138. }
  51139. }
  51140. for (var i = 0; i < linearSamplingMap.length; i++) {
  51141. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  51142. linearSamplingWeights[i] = linearSamplingMap[i].w;
  51143. }
  51144. // Replace with optimized
  51145. offsets = linearSamplingOffsets;
  51146. weights = linearSamplingWeights;
  51147. // Generate shaders
  51148. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  51149. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  51150. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  51151. var defines = "";
  51152. for (var i = 0; i < varyingCount; i++) {
  51153. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  51154. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  51155. }
  51156. var depCount = 0;
  51157. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  51158. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  51159. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  51160. depCount++;
  51161. }
  51162. this._indexParameters.varyingCount = varyingCount;
  51163. this._indexParameters.depCount = depCount;
  51164. this.updateEffect(defines);
  51165. };
  51166. /**
  51167. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  51168. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  51169. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  51170. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  51171. * The gaps between physical kernels are compensated for in the weighting of the samples
  51172. * @param idealKernel Ideal blur kernel.
  51173. * @return Nearest best kernel.
  51174. */
  51175. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  51176. var v = Math.round(idealKernel);
  51177. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  51178. var k = _a[_i];
  51179. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  51180. return Math.max(k, 3);
  51181. }
  51182. }
  51183. return Math.max(v, 3);
  51184. };
  51185. /**
  51186. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  51187. * @param x The point on the Gaussian distribution to sample.
  51188. * @return the value of the Gaussian function at x.
  51189. */
  51190. BlurPostProcess.prototype._gaussianWeight = function (x) {
  51191. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  51192. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  51193. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  51194. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  51195. // truncated at around 1.3% of peak strength.
  51196. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  51197. var sigma = (1 / 3);
  51198. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  51199. var exponent = -((x * x) / (2.0 * sigma * sigma));
  51200. var weight = (1.0 / denominator) * Math.exp(exponent);
  51201. return weight;
  51202. };
  51203. /**
  51204. * Generates a string that can be used as a floating point number in GLSL.
  51205. * @param x Value to print.
  51206. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  51207. * @return GLSL float string.
  51208. */
  51209. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  51210. if (decimalFigures === void 0) { decimalFigures = 8; }
  51211. return x.toFixed(decimalFigures).replace(/0+$/, '');
  51212. };
  51213. return BlurPostProcess;
  51214. }(BABYLON.PostProcess));
  51215. BABYLON.BlurPostProcess = BlurPostProcess;
  51216. })(BABYLON || (BABYLON = {}));
  51217. //# sourceMappingURL=babylon.blurPostProcess.js.map
  51218. /// <reference path="..\babylon.node.ts" />
  51219. var BABYLON;
  51220. (function (BABYLON) {
  51221. var Bone = (function (_super) {
  51222. __extends(Bone, _super);
  51223. function Bone(name, skeleton, parentBone, matrix, restPose) {
  51224. var _this = _super.call(this, name, skeleton.getScene()) || this;
  51225. _this.name = name;
  51226. _this.children = new Array();
  51227. _this.animations = new Array();
  51228. _this._worldTransform = new BABYLON.Matrix();
  51229. _this._absoluteTransform = new BABYLON.Matrix();
  51230. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  51231. _this._scaleMatrix = BABYLON.Matrix.Identity();
  51232. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  51233. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  51234. _this._scalingDeterminant = 1;
  51235. _this._skeleton = skeleton;
  51236. _this._localMatrix = matrix;
  51237. _this._baseMatrix = matrix.clone();
  51238. _this._restPose = restPose ? restPose : matrix.clone();
  51239. skeleton.bones.push(_this);
  51240. if (parentBone) {
  51241. _this._parent = parentBone;
  51242. parentBone.children.push(_this);
  51243. }
  51244. else {
  51245. _this._parent = null;
  51246. }
  51247. _this._updateDifferenceMatrix();
  51248. if (_this.getAbsoluteTransform().determinant() < 0) {
  51249. _this._scalingDeterminant *= -1;
  51250. }
  51251. return _this;
  51252. }
  51253. Object.defineProperty(Bone.prototype, "_matrix", {
  51254. get: function () {
  51255. return this._localMatrix;
  51256. },
  51257. set: function (val) {
  51258. if (this._localMatrix) {
  51259. this._localMatrix.copyFrom(val);
  51260. }
  51261. else {
  51262. this._localMatrix = val;
  51263. }
  51264. },
  51265. enumerable: true,
  51266. configurable: true
  51267. });
  51268. // Members
  51269. Bone.prototype.getParent = function () {
  51270. return this._parent;
  51271. };
  51272. Bone.prototype.getLocalMatrix = function () {
  51273. return this._localMatrix;
  51274. };
  51275. Bone.prototype.getBaseMatrix = function () {
  51276. return this._baseMatrix;
  51277. };
  51278. Bone.prototype.getRestPose = function () {
  51279. return this._restPose;
  51280. };
  51281. Bone.prototype.returnToRest = function () {
  51282. this.updateMatrix(this._restPose.clone());
  51283. };
  51284. Bone.prototype.getWorldMatrix = function () {
  51285. return this._worldTransform;
  51286. };
  51287. Bone.prototype.getInvertedAbsoluteTransform = function () {
  51288. return this._invertedAbsoluteTransform;
  51289. };
  51290. Bone.prototype.getAbsoluteTransform = function () {
  51291. return this._absoluteTransform;
  51292. };
  51293. Object.defineProperty(Bone.prototype, "position", {
  51294. // Properties (matches AbstractMesh properties)
  51295. get: function () {
  51296. return this.getPosition();
  51297. },
  51298. set: function (newPosition) {
  51299. this.setPosition(newPosition);
  51300. },
  51301. enumerable: true,
  51302. configurable: true
  51303. });
  51304. Object.defineProperty(Bone.prototype, "rotation", {
  51305. get: function () {
  51306. return this.getRotation();
  51307. },
  51308. set: function (newRotation) {
  51309. this.setRotation(newRotation);
  51310. },
  51311. enumerable: true,
  51312. configurable: true
  51313. });
  51314. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  51315. get: function () {
  51316. return this.getRotationQuaternion();
  51317. },
  51318. set: function (newRotation) {
  51319. this.setRotationQuaternion(newRotation);
  51320. },
  51321. enumerable: true,
  51322. configurable: true
  51323. });
  51324. Object.defineProperty(Bone.prototype, "scaling", {
  51325. get: function () {
  51326. return this.getScale();
  51327. },
  51328. set: function (newScaling) {
  51329. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  51330. },
  51331. enumerable: true,
  51332. configurable: true
  51333. });
  51334. // Methods
  51335. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  51336. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  51337. this._baseMatrix = matrix.clone();
  51338. this._localMatrix = matrix.clone();
  51339. this._skeleton._markAsDirty();
  51340. if (updateDifferenceMatrix) {
  51341. this._updateDifferenceMatrix();
  51342. }
  51343. };
  51344. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  51345. if (!rootMatrix) {
  51346. rootMatrix = this._baseMatrix;
  51347. }
  51348. if (this._parent) {
  51349. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  51350. }
  51351. else {
  51352. this._absoluteTransform.copyFrom(rootMatrix);
  51353. }
  51354. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  51355. for (var index = 0; index < this.children.length; index++) {
  51356. this.children[index]._updateDifferenceMatrix();
  51357. }
  51358. };
  51359. Bone.prototype.markAsDirty = function () {
  51360. this._currentRenderId++;
  51361. this._skeleton._markAsDirty();
  51362. };
  51363. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  51364. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  51365. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  51366. // all animation may be coming from a library skeleton, so may need to create animation
  51367. if (this.animations.length === 0) {
  51368. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  51369. this.animations[0].setKeys([]);
  51370. }
  51371. // get animation info / verify there is such a range from the source bone
  51372. var sourceRange = source.animations[0].getRange(rangeName);
  51373. if (!sourceRange) {
  51374. return false;
  51375. }
  51376. var from = sourceRange.from;
  51377. var to = sourceRange.to;
  51378. var sourceKeys = source.animations[0].getKeys();
  51379. // rescaling prep
  51380. var sourceBoneLength = source.length;
  51381. var sourceParent = source.getParent();
  51382. var parent = this.getParent();
  51383. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  51384. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  51385. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  51386. var destKeys = this.animations[0].getKeys();
  51387. // loop vars declaration
  51388. var orig;
  51389. var origTranslation;
  51390. var mat;
  51391. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  51392. orig = sourceKeys[key];
  51393. if (orig.frame >= from && orig.frame <= to) {
  51394. if (rescaleAsRequired) {
  51395. mat = orig.value.clone();
  51396. // scale based on parent ratio, when bone has parent
  51397. if (parentScalingReqd) {
  51398. origTranslation = mat.getTranslation();
  51399. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  51400. // scale based on skeleton dimension ratio when root bone, and value is passed
  51401. }
  51402. else if (dimensionsScalingReqd) {
  51403. origTranslation = mat.getTranslation();
  51404. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  51405. // use original when root bone, and no data for skelDimensionsRatio
  51406. }
  51407. else {
  51408. mat = orig.value;
  51409. }
  51410. }
  51411. else {
  51412. mat = orig.value;
  51413. }
  51414. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  51415. }
  51416. }
  51417. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  51418. return true;
  51419. };
  51420. /**
  51421. * Translate the bone in local or world space.
  51422. * @param vec The amount to translate the bone.
  51423. * @param space The space that the translation is in.
  51424. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51425. */
  51426. Bone.prototype.translate = function (vec, space, mesh) {
  51427. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51428. var lm = this.getLocalMatrix();
  51429. if (space == BABYLON.Space.LOCAL) {
  51430. lm.m[12] += vec.x;
  51431. lm.m[13] += vec.y;
  51432. lm.m[14] += vec.z;
  51433. }
  51434. else {
  51435. var wm;
  51436. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51437. if (mesh) {
  51438. wm = mesh.getWorldMatrix();
  51439. }
  51440. this._skeleton.computeAbsoluteTransforms();
  51441. var tmat = Bone._tmpMats[0];
  51442. var tvec = Bone._tmpVecs[0];
  51443. if (mesh) {
  51444. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51445. tmat.multiplyToRef(wm, tmat);
  51446. }
  51447. else {
  51448. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51449. }
  51450. tmat.m[12] = 0;
  51451. tmat.m[13] = 0;
  51452. tmat.m[14] = 0;
  51453. tmat.invert();
  51454. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  51455. lm.m[12] += tvec.x;
  51456. lm.m[13] += tvec.y;
  51457. lm.m[14] += tvec.z;
  51458. }
  51459. this.markAsDirty();
  51460. };
  51461. /**
  51462. * Set the postion of the bone in local or world space.
  51463. * @param position The position to set the bone.
  51464. * @param space The space that the position is in.
  51465. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51466. */
  51467. Bone.prototype.setPosition = function (position, space, mesh) {
  51468. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51469. var lm = this.getLocalMatrix();
  51470. if (space == BABYLON.Space.LOCAL) {
  51471. lm.m[12] = position.x;
  51472. lm.m[13] = position.y;
  51473. lm.m[14] = position.z;
  51474. }
  51475. else {
  51476. var wm;
  51477. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51478. if (mesh) {
  51479. wm = mesh.getWorldMatrix();
  51480. }
  51481. this._skeleton.computeAbsoluteTransforms();
  51482. var tmat = Bone._tmpMats[0];
  51483. var vec = Bone._tmpVecs[0];
  51484. if (mesh) {
  51485. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51486. tmat.multiplyToRef(wm, tmat);
  51487. }
  51488. else {
  51489. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51490. }
  51491. tmat.invert();
  51492. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  51493. lm.m[12] = vec.x;
  51494. lm.m[13] = vec.y;
  51495. lm.m[14] = vec.z;
  51496. }
  51497. this.markAsDirty();
  51498. };
  51499. /**
  51500. * Set the absolute postion of the bone (world space).
  51501. * @param position The position to set the bone.
  51502. * @param mesh The mesh that this bone is attached to.
  51503. */
  51504. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  51505. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  51506. };
  51507. /**
  51508. * Set the scale of the bone on the x, y and z axes.
  51509. * @param x The scale of the bone on the x axis.
  51510. * @param x The scale of the bone on the y axis.
  51511. * @param z The scale of the bone on the z axis.
  51512. * @param scaleChildren Set this to true if children of the bone should be scaled.
  51513. */
  51514. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  51515. if (scaleChildren === void 0) { scaleChildren = false; }
  51516. if (this.animations[0] && !this.animations[0].isStopped()) {
  51517. if (!scaleChildren) {
  51518. this._negateScaleChildren.x = 1 / x;
  51519. this._negateScaleChildren.y = 1 / y;
  51520. this._negateScaleChildren.z = 1 / z;
  51521. }
  51522. this._syncScaleVector();
  51523. }
  51524. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  51525. };
  51526. /**
  51527. * Scale the bone on the x, y and z axes.
  51528. * @param x The amount to scale the bone on the x axis.
  51529. * @param x The amount to scale the bone on the y axis.
  51530. * @param z The amount to scale the bone on the z axis.
  51531. * @param scaleChildren Set this to true if children of the bone should be scaled.
  51532. */
  51533. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  51534. if (scaleChildren === void 0) { scaleChildren = false; }
  51535. var locMat = this.getLocalMatrix();
  51536. var origLocMat = Bone._tmpMats[0];
  51537. origLocMat.copyFrom(locMat);
  51538. var origLocMatInv = Bone._tmpMats[1];
  51539. origLocMatInv.copyFrom(origLocMat);
  51540. origLocMatInv.invert();
  51541. var scaleMat = Bone._tmpMats[2];
  51542. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  51543. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  51544. this._scaleVector.x *= x;
  51545. this._scaleVector.y *= y;
  51546. this._scaleVector.z *= z;
  51547. locMat.multiplyToRef(origLocMatInv, locMat);
  51548. locMat.multiplyToRef(scaleMat, locMat);
  51549. locMat.multiplyToRef(origLocMat, locMat);
  51550. var parent = this.getParent();
  51551. if (parent) {
  51552. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  51553. }
  51554. else {
  51555. this.getAbsoluteTransform().copyFrom(locMat);
  51556. }
  51557. var len = this.children.length;
  51558. scaleMat.invert();
  51559. for (var i = 0; i < len; i++) {
  51560. var child = this.children[i];
  51561. var cm = child.getLocalMatrix();
  51562. cm.multiplyToRef(scaleMat, cm);
  51563. var lm = child.getLocalMatrix();
  51564. lm.m[12] *= x;
  51565. lm.m[13] *= y;
  51566. lm.m[14] *= z;
  51567. }
  51568. this.computeAbsoluteTransforms();
  51569. if (scaleChildren) {
  51570. for (var i = 0; i < len; i++) {
  51571. this.children[i].scale(x, y, z, scaleChildren);
  51572. }
  51573. }
  51574. this.markAsDirty();
  51575. };
  51576. /**
  51577. * Set the yaw, pitch, and roll of the bone in local or world space.
  51578. * @param yaw The rotation of the bone on the y axis.
  51579. * @param pitch The rotation of the bone on the x axis.
  51580. * @param roll The rotation of the bone on the z axis.
  51581. * @param space The space that the axes of rotation are in.
  51582. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51583. */
  51584. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  51585. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51586. var rotMat = Bone._tmpMats[0];
  51587. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  51588. var rotMatInv = Bone._tmpMats[1];
  51589. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51590. rotMatInv.multiplyToRef(rotMat, rotMat);
  51591. this._rotateWithMatrix(rotMat, space, mesh);
  51592. };
  51593. /**
  51594. * Rotate the bone on an axis in local or world space.
  51595. * @param axis The axis to rotate the bone on.
  51596. * @param amount The amount to rotate the bone.
  51597. * @param space The space that the axis is in.
  51598. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51599. */
  51600. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  51601. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51602. var rmat = Bone._tmpMats[0];
  51603. rmat.m[12] = 0;
  51604. rmat.m[13] = 0;
  51605. rmat.m[14] = 0;
  51606. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  51607. this._rotateWithMatrix(rmat, space, mesh);
  51608. };
  51609. /**
  51610. * Set the rotation of the bone to a particular axis angle in local or world space.
  51611. * @param axis The axis to rotate the bone on.
  51612. * @param angle The angle that the bone should be rotated to.
  51613. * @param space The space that the axis is in.
  51614. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51615. */
  51616. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  51617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51618. var rotMat = Bone._tmpMats[0];
  51619. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  51620. var rotMatInv = Bone._tmpMats[1];
  51621. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51622. rotMatInv.multiplyToRef(rotMat, rotMat);
  51623. this._rotateWithMatrix(rotMat, space, mesh);
  51624. };
  51625. /**
  51626. * Set the euler rotation of the bone in local of world space.
  51627. * @param rotation The euler rotation that the bone should be set to.
  51628. * @param space The space that the rotation is in.
  51629. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51630. */
  51631. Bone.prototype.setRotation = function (rotation, space, mesh) {
  51632. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51633. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  51634. };
  51635. /**
  51636. * Set the quaternion rotation of the bone in local of world space.
  51637. * @param quat The quaternion rotation that the bone should be set to.
  51638. * @param space The space that the rotation is in.
  51639. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51640. */
  51641. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  51642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51643. var rotMatInv = Bone._tmpMats[0];
  51644. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51645. var rotMat = Bone._tmpMats[1];
  51646. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  51647. rotMatInv.multiplyToRef(rotMat, rotMat);
  51648. this._rotateWithMatrix(rotMat, space, mesh);
  51649. };
  51650. /**
  51651. * Set the rotation matrix of the bone in local of world space.
  51652. * @param rotMat The rotation matrix that the bone should be set to.
  51653. * @param space The space that the rotation is in.
  51654. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51655. */
  51656. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  51657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51658. var rotMatInv = Bone._tmpMats[0];
  51659. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51660. var rotMat2 = Bone._tmpMats[1];
  51661. rotMat2.copyFrom(rotMat);
  51662. rotMatInv.multiplyToRef(rotMat, rotMat2);
  51663. this._rotateWithMatrix(rotMat2, space, mesh);
  51664. };
  51665. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  51666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51667. var lmat = this.getLocalMatrix();
  51668. var lx = lmat.m[12];
  51669. var ly = lmat.m[13];
  51670. var lz = lmat.m[14];
  51671. var parent = this.getParent();
  51672. var parentScale = Bone._tmpMats[3];
  51673. var parentScaleInv = Bone._tmpMats[4];
  51674. if (parent) {
  51675. if (space == BABYLON.Space.WORLD) {
  51676. if (mesh) {
  51677. parentScale.copyFrom(mesh.getWorldMatrix());
  51678. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  51679. }
  51680. else {
  51681. parentScale.copyFrom(parent.getAbsoluteTransform());
  51682. }
  51683. }
  51684. else {
  51685. parentScale = parent._scaleMatrix;
  51686. }
  51687. parentScaleInv.copyFrom(parentScale);
  51688. parentScaleInv.invert();
  51689. lmat.multiplyToRef(parentScale, lmat);
  51690. lmat.multiplyToRef(rmat, lmat);
  51691. lmat.multiplyToRef(parentScaleInv, lmat);
  51692. }
  51693. else {
  51694. if (space == BABYLON.Space.WORLD && mesh) {
  51695. parentScale.copyFrom(mesh.getWorldMatrix());
  51696. parentScaleInv.copyFrom(parentScale);
  51697. parentScaleInv.invert();
  51698. lmat.multiplyToRef(parentScale, lmat);
  51699. lmat.multiplyToRef(rmat, lmat);
  51700. lmat.multiplyToRef(parentScaleInv, lmat);
  51701. }
  51702. else {
  51703. lmat.multiplyToRef(rmat, lmat);
  51704. }
  51705. }
  51706. lmat.m[12] = lx;
  51707. lmat.m[13] = ly;
  51708. lmat.m[14] = lz;
  51709. this.computeAbsoluteTransforms();
  51710. this.markAsDirty();
  51711. };
  51712. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  51713. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51714. if (space == BABYLON.Space.WORLD) {
  51715. var scaleMatrix = Bone._tmpMats[2];
  51716. scaleMatrix.copyFrom(this._scaleMatrix);
  51717. rotMatInv.copyFrom(this.getAbsoluteTransform());
  51718. if (mesh) {
  51719. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  51720. var meshScale = Bone._tmpMats[3];
  51721. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  51722. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  51723. }
  51724. rotMatInv.invert();
  51725. scaleMatrix.m[0] *= this._scalingDeterminant;
  51726. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  51727. }
  51728. else {
  51729. rotMatInv.copyFrom(this.getLocalMatrix());
  51730. rotMatInv.invert();
  51731. var scaleMatrix = Bone._tmpMats[2];
  51732. scaleMatrix.copyFrom(this._scaleMatrix);
  51733. if (this._parent) {
  51734. var pscaleMatrix = Bone._tmpMats[3];
  51735. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  51736. pscaleMatrix.invert();
  51737. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  51738. }
  51739. else {
  51740. scaleMatrix.m[0] *= this._scalingDeterminant;
  51741. }
  51742. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  51743. }
  51744. };
  51745. /**
  51746. * Get the scale of the bone
  51747. * @returns the scale of the bone
  51748. */
  51749. Bone.prototype.getScale = function () {
  51750. return this._scaleVector.clone();
  51751. };
  51752. /**
  51753. * Copy the scale of the bone to a vector3.
  51754. * @param result The vector3 to copy the scale to
  51755. */
  51756. Bone.prototype.getScaleToRef = function (result) {
  51757. result.copyFrom(this._scaleVector);
  51758. };
  51759. /**
  51760. * Get the position of the bone in local or world space.
  51761. * @param space The space that the returned position is in.
  51762. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51763. * @returns The position of the bone
  51764. */
  51765. Bone.prototype.getPosition = function (space, mesh) {
  51766. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51767. var pos = BABYLON.Vector3.Zero();
  51768. this.getPositionToRef(space, mesh, pos);
  51769. return pos;
  51770. };
  51771. /**
  51772. * Copy the position of the bone to a vector3 in local or world space.
  51773. * @param space The space that the returned position is in.
  51774. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51775. * @param result The vector3 to copy the position to.
  51776. */
  51777. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  51778. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51779. if (space == BABYLON.Space.LOCAL) {
  51780. var lm = this.getLocalMatrix();
  51781. result.x = lm.m[12];
  51782. result.y = lm.m[13];
  51783. result.z = lm.m[14];
  51784. }
  51785. else {
  51786. var wm;
  51787. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51788. if (mesh) {
  51789. wm = mesh.getWorldMatrix();
  51790. }
  51791. this._skeleton.computeAbsoluteTransforms();
  51792. var tmat = Bone._tmpMats[0];
  51793. if (mesh) {
  51794. tmat.copyFrom(this.getAbsoluteTransform());
  51795. tmat.multiplyToRef(wm, tmat);
  51796. }
  51797. else {
  51798. tmat = this.getAbsoluteTransform();
  51799. }
  51800. result.x = tmat.m[12];
  51801. result.y = tmat.m[13];
  51802. result.z = tmat.m[14];
  51803. }
  51804. };
  51805. /**
  51806. * Get the absolute position of the bone (world space).
  51807. * @param mesh The mesh that this bone is attached to.
  51808. * @returns The absolute position of the bone
  51809. */
  51810. Bone.prototype.getAbsolutePosition = function (mesh) {
  51811. var pos = BABYLON.Vector3.Zero();
  51812. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  51813. return pos;
  51814. };
  51815. /**
  51816. * Copy the absolute position of the bone (world space) to the result param.
  51817. * @param mesh The mesh that this bone is attached to.
  51818. * @param result The vector3 to copy the absolute position to.
  51819. */
  51820. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  51821. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  51822. };
  51823. /**
  51824. * Compute the absolute transforms of this bone and its children.
  51825. */
  51826. Bone.prototype.computeAbsoluteTransforms = function () {
  51827. if (this._parent) {
  51828. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  51829. }
  51830. else {
  51831. this._absoluteTransform.copyFrom(this._localMatrix);
  51832. var poseMatrix = this._skeleton.getPoseMatrix();
  51833. if (poseMatrix) {
  51834. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  51835. }
  51836. }
  51837. var children = this.children;
  51838. var len = children.length;
  51839. for (var i = 0; i < len; i++) {
  51840. children[i].computeAbsoluteTransforms();
  51841. }
  51842. };
  51843. Bone.prototype._syncScaleVector = function () {
  51844. var lm = this.getLocalMatrix();
  51845. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  51846. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  51847. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  51848. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  51849. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  51850. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  51851. this._scaleVector.x = xs * Math.sqrt(xsq);
  51852. this._scaleVector.y = ys * Math.sqrt(ysq);
  51853. this._scaleVector.z = zs * Math.sqrt(zsq);
  51854. if (this._parent) {
  51855. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  51856. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  51857. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  51858. }
  51859. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  51860. };
  51861. /**
  51862. * Get the world direction from an axis that is in the local space of the bone.
  51863. * @param localAxis The local direction that is used to compute the world direction.
  51864. * @param mesh The mesh that this bone is attached to.
  51865. * @returns The world direction
  51866. */
  51867. Bone.prototype.getDirection = function (localAxis, mesh) {
  51868. var result = BABYLON.Vector3.Zero();
  51869. this.getDirectionToRef(localAxis, mesh, result);
  51870. return result;
  51871. };
  51872. /**
  51873. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  51874. * @param localAxis The local direction that is used to compute the world direction.
  51875. * @param mesh The mesh that this bone is attached to.
  51876. * @param result The vector3 that the world direction will be copied to.
  51877. */
  51878. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  51879. var wm;
  51880. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51881. if (mesh) {
  51882. wm = mesh.getWorldMatrix();
  51883. }
  51884. this._skeleton.computeAbsoluteTransforms();
  51885. var mat = Bone._tmpMats[0];
  51886. mat.copyFrom(this.getAbsoluteTransform());
  51887. if (mesh) {
  51888. mat.multiplyToRef(wm, mat);
  51889. }
  51890. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  51891. result.normalize();
  51892. };
  51893. /**
  51894. * Get the euler rotation of the bone in local or world space.
  51895. * @param space The space that the rotation should be in.
  51896. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51897. * @returns The euler rotation
  51898. */
  51899. Bone.prototype.getRotation = function (space, mesh) {
  51900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51901. var result = BABYLON.Vector3.Zero();
  51902. this.getRotationToRef(space, mesh, result);
  51903. return result;
  51904. };
  51905. /**
  51906. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  51907. * @param space The space that the rotation should be in.
  51908. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51909. * @param result The vector3 that the rotation should be copied to.
  51910. */
  51911. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  51912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51913. var quat = Bone._tmpQuat;
  51914. this.getRotationQuaternionToRef(space, mesh, quat);
  51915. quat.toEulerAnglesToRef(result);
  51916. };
  51917. /**
  51918. * Get the quaternion rotation of the bone in either local or world space.
  51919. * @param space The space that the rotation should be in.
  51920. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51921. * @returns The quaternion rotation
  51922. */
  51923. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  51924. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51925. var result = BABYLON.Quaternion.Identity();
  51926. this.getRotationQuaternionToRef(space, mesh, result);
  51927. return result;
  51928. };
  51929. /**
  51930. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  51931. * @param space The space that the rotation should be in.
  51932. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51933. * @param result The quaternion that the rotation should be copied to.
  51934. */
  51935. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  51936. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51937. if (space == BABYLON.Space.LOCAL) {
  51938. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  51939. }
  51940. else {
  51941. var mat = Bone._tmpMats[0];
  51942. var amat = this.getAbsoluteTransform();
  51943. if (mesh) {
  51944. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  51945. }
  51946. else {
  51947. mat.copyFrom(amat);
  51948. }
  51949. mat.m[0] *= this._scalingDeterminant;
  51950. mat.m[1] *= this._scalingDeterminant;
  51951. mat.m[2] *= this._scalingDeterminant;
  51952. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  51953. }
  51954. };
  51955. /**
  51956. * Get the rotation matrix of the bone in local or world space.
  51957. * @param space The space that the rotation should be in.
  51958. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51959. * @returns The rotation matrix
  51960. */
  51961. Bone.prototype.getRotationMatrix = function (space, mesh) {
  51962. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51963. var result = BABYLON.Matrix.Identity();
  51964. this.getRotationMatrixToRef(space, mesh, result);
  51965. return result;
  51966. };
  51967. /**
  51968. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  51969. * @param space The space that the rotation should be in.
  51970. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51971. * @param result The quaternion that the rotation should be copied to.
  51972. */
  51973. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  51974. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51975. if (space == BABYLON.Space.LOCAL) {
  51976. this.getLocalMatrix().getRotationMatrixToRef(result);
  51977. }
  51978. else {
  51979. var mat = Bone._tmpMats[0];
  51980. var amat = this.getAbsoluteTransform();
  51981. if (mesh) {
  51982. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  51983. }
  51984. else {
  51985. mat.copyFrom(amat);
  51986. }
  51987. mat.m[0] *= this._scalingDeterminant;
  51988. mat.m[1] *= this._scalingDeterminant;
  51989. mat.m[2] *= this._scalingDeterminant;
  51990. mat.getRotationMatrixToRef(result);
  51991. }
  51992. };
  51993. /**
  51994. * Get the world position of a point that is in the local space of the bone.
  51995. * @param position The local position
  51996. * @param mesh The mesh that this bone is attached to.
  51997. * @returns The world position
  51998. */
  51999. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  52000. var result = BABYLON.Vector3.Zero();
  52001. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  52002. return result;
  52003. };
  52004. /**
  52005. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  52006. * @param position The local position
  52007. * @param mesh The mesh that this bone is attached to.
  52008. * @param result The vector3 that the world position should be copied to.
  52009. */
  52010. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  52011. var wm;
  52012. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52013. if (mesh) {
  52014. wm = mesh.getWorldMatrix();
  52015. }
  52016. this._skeleton.computeAbsoluteTransforms();
  52017. var tmat = Bone._tmpMats[0];
  52018. if (mesh) {
  52019. tmat.copyFrom(this.getAbsoluteTransform());
  52020. tmat.multiplyToRef(wm, tmat);
  52021. }
  52022. else {
  52023. tmat = this.getAbsoluteTransform();
  52024. }
  52025. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  52026. };
  52027. /**
  52028. * Get the local position of a point that is in world space.
  52029. * @param position The world position
  52030. * @param mesh The mesh that this bone is attached to.
  52031. * @returns The local position
  52032. */
  52033. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  52034. var result = BABYLON.Vector3.Zero();
  52035. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  52036. return result;
  52037. };
  52038. /**
  52039. * Get the local position of a point that is in world space and copy it to the result param.
  52040. * @param position The world position
  52041. * @param mesh The mesh that this bone is attached to.
  52042. * @param result The vector3 that the local position should be copied to.
  52043. */
  52044. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  52045. var wm;
  52046. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52047. if (mesh) {
  52048. wm = mesh.getWorldMatrix();
  52049. }
  52050. this._skeleton.computeAbsoluteTransforms();
  52051. var tmat = Bone._tmpMats[0];
  52052. tmat.copyFrom(this.getAbsoluteTransform());
  52053. if (mesh) {
  52054. tmat.multiplyToRef(wm, tmat);
  52055. }
  52056. tmat.invert();
  52057. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  52058. };
  52059. return Bone;
  52060. }(BABYLON.Node));
  52061. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52062. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  52063. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52064. BABYLON.Bone = Bone;
  52065. })(BABYLON || (BABYLON = {}));
  52066. //# sourceMappingURL=babylon.bone.js.map
  52067. var BABYLON;
  52068. (function (BABYLON) {
  52069. var BoneIKController = (function () {
  52070. function BoneIKController(mesh, bone, options) {
  52071. this.targetPosition = BABYLON.Vector3.Zero();
  52072. this.poleTargetPosition = BABYLON.Vector3.Zero();
  52073. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  52074. this.poleAngle = 0;
  52075. this.slerpAmount = 1;
  52076. this._bone1Quat = BABYLON.Quaternion.Identity();
  52077. this._bone1Mat = BABYLON.Matrix.Identity();
  52078. this._bone2Ang = Math.PI;
  52079. this._maxAngle = Math.PI;
  52080. this._rightHandedSystem = false;
  52081. this._bendAxis = BABYLON.Vector3.Right();
  52082. this._slerping = false;
  52083. this._adjustRoll = 0;
  52084. this._bone2 = bone;
  52085. this._bone1 = bone.getParent();
  52086. this.mesh = mesh;
  52087. var bonePos = bone.getPosition();
  52088. if (bone.getAbsoluteTransform().determinant() > 0) {
  52089. this._rightHandedSystem = true;
  52090. this._bendAxis.x = 0;
  52091. this._bendAxis.y = 0;
  52092. this._bendAxis.z = -1;
  52093. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  52094. this._adjustRoll = Math.PI * .5;
  52095. this._bendAxis.z = 1;
  52096. }
  52097. }
  52098. if (this._bone1.length) {
  52099. var boneScale1 = this._bone1.getScale();
  52100. var boneScale2 = this._bone2.getScale();
  52101. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  52102. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  52103. }
  52104. else if (this._bone1.children[0]) {
  52105. mesh.computeWorldMatrix(true);
  52106. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  52107. var pos2 = this._bone2.getAbsolutePosition(mesh);
  52108. var pos3 = this._bone1.getAbsolutePosition(mesh);
  52109. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  52110. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  52111. }
  52112. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  52113. this.maxAngle = Math.PI;
  52114. if (options) {
  52115. if (options.targetMesh) {
  52116. this.targetMesh = options.targetMesh;
  52117. this.targetMesh.computeWorldMatrix(true);
  52118. }
  52119. if (options.poleTargetMesh) {
  52120. this.poleTargetMesh = options.poleTargetMesh;
  52121. this.poleTargetMesh.computeWorldMatrix(true);
  52122. }
  52123. else if (options.poleTargetBone) {
  52124. this.poleTargetBone = options.poleTargetBone;
  52125. }
  52126. else if (this._bone1.getParent()) {
  52127. this.poleTargetBone = this._bone1.getParent();
  52128. }
  52129. if (options.poleTargetLocalOffset) {
  52130. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  52131. }
  52132. if (options.poleAngle) {
  52133. this.poleAngle = options.poleAngle;
  52134. }
  52135. if (options.bendAxis) {
  52136. this._bendAxis.copyFrom(options.bendAxis);
  52137. }
  52138. if (options.maxAngle) {
  52139. this.maxAngle = options.maxAngle;
  52140. }
  52141. if (options.slerpAmount) {
  52142. this.slerpAmount = options.slerpAmount;
  52143. }
  52144. }
  52145. }
  52146. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  52147. get: function () {
  52148. return this._maxAngle;
  52149. },
  52150. set: function (value) {
  52151. this._setMaxAngle(value);
  52152. },
  52153. enumerable: true,
  52154. configurable: true
  52155. });
  52156. BoneIKController.prototype._setMaxAngle = function (ang) {
  52157. if (ang < 0) {
  52158. ang = 0;
  52159. }
  52160. if (ang > Math.PI || ang == undefined) {
  52161. ang = Math.PI;
  52162. }
  52163. this._maxAngle = ang;
  52164. var a = this._bone1Length;
  52165. var b = this._bone2Length;
  52166. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  52167. };
  52168. BoneIKController.prototype.update = function () {
  52169. var bone1 = this._bone1;
  52170. var target = this.targetPosition;
  52171. var poleTarget = this.poleTargetPosition;
  52172. var mat1 = BoneIKController._tmpMats[0];
  52173. var mat2 = BoneIKController._tmpMats[1];
  52174. if (this.targetMesh) {
  52175. target.copyFrom(this.targetMesh.getAbsolutePosition());
  52176. }
  52177. if (this.poleTargetBone) {
  52178. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  52179. }
  52180. else if (this.poleTargetMesh) {
  52181. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  52182. }
  52183. var bonePos = BoneIKController._tmpVecs[0];
  52184. var zaxis = BoneIKController._tmpVecs[1];
  52185. var xaxis = BoneIKController._tmpVecs[2];
  52186. var yaxis = BoneIKController._tmpVecs[3];
  52187. var upAxis = BoneIKController._tmpVecs[4];
  52188. var _tmpQuat = BoneIKController._tmpQuat;
  52189. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  52190. poleTarget.subtractToRef(bonePos, upAxis);
  52191. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  52192. upAxis.y = 1;
  52193. }
  52194. else {
  52195. upAxis.normalize();
  52196. }
  52197. target.subtractToRef(bonePos, yaxis);
  52198. yaxis.normalize();
  52199. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  52200. zaxis.normalize();
  52201. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  52202. xaxis.normalize();
  52203. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  52204. var a = this._bone1Length;
  52205. var b = this._bone2Length;
  52206. var c = BABYLON.Vector3.Distance(bonePos, target);
  52207. if (this._maxReach > 0) {
  52208. c = Math.min(this._maxReach, c);
  52209. }
  52210. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  52211. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  52212. if (acosa > 1) {
  52213. acosa = 1;
  52214. }
  52215. if (acosb > 1) {
  52216. acosb = 1;
  52217. }
  52218. if (acosa < -1) {
  52219. acosa = -1;
  52220. }
  52221. if (acosb < -1) {
  52222. acosb = -1;
  52223. }
  52224. var angA = Math.acos(acosa);
  52225. var angB = Math.acos(acosb);
  52226. var angC = -angA - angB;
  52227. if (this._rightHandedSystem) {
  52228. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  52229. mat2.multiplyToRef(mat1, mat1);
  52230. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  52231. mat2.multiplyToRef(mat1, mat1);
  52232. }
  52233. else {
  52234. var _tmpVec = BoneIKController._tmpVecs[5];
  52235. _tmpVec.copyFrom(this._bendAxis);
  52236. _tmpVec.x *= -1;
  52237. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  52238. mat2.multiplyToRef(mat1, mat1);
  52239. }
  52240. if (this.poleAngle) {
  52241. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  52242. mat1.multiplyToRef(mat2, mat1);
  52243. }
  52244. if (this.slerpAmount < 1) {
  52245. if (!this._slerping) {
  52246. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  52247. }
  52248. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  52249. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  52250. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  52251. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  52252. this._slerping = true;
  52253. }
  52254. else {
  52255. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  52256. this._bone1Mat.copyFrom(mat1);
  52257. this._slerping = false;
  52258. }
  52259. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  52260. this._bone2Ang = angC;
  52261. };
  52262. return BoneIKController;
  52263. }());
  52264. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52265. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  52266. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52267. BABYLON.BoneIKController = BoneIKController;
  52268. })(BABYLON || (BABYLON = {}));
  52269. //# sourceMappingURL=babylon.boneIKController.js.map
  52270. var BABYLON;
  52271. (function (BABYLON) {
  52272. var BoneLookController = (function () {
  52273. /**
  52274. * Create a BoneLookController
  52275. * @param mesh the mesh that the bone belongs to
  52276. * @param bone the bone that will be looking to the target
  52277. * @param target the target Vector3 to look at
  52278. * @param settings optional settings:
  52279. * - maxYaw: the maximum angle the bone will yaw to
  52280. * - minYaw: the minimum angle the bone will yaw to
  52281. * - maxPitch: the maximum angle the bone will pitch to
  52282. * - minPitch: the minimum angle the bone will yaw to
  52283. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  52284. * - upAxis: the up axis of the coordinate system
  52285. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52286. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  52287. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  52288. * - adjustYaw: used to make an adjustment to the yaw of the bone
  52289. * - adjustPitch: used to make an adjustment to the pitch of the bone
  52290. * - adjustRoll: used to make an adjustment to the roll of the bone
  52291. **/
  52292. function BoneLookController(mesh, bone, target, options) {
  52293. /**
  52294. * The up axis of the coordinate system that is used when the bone is rotated.
  52295. */
  52296. this.upAxis = BABYLON.Vector3.Up();
  52297. /**
  52298. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52299. */
  52300. this.upAxisSpace = BABYLON.Space.LOCAL;
  52301. /**
  52302. * Used to make an adjustment to the yaw of the bone.
  52303. */
  52304. this.adjustYaw = 0;
  52305. /**
  52306. * Used to make an adjustment to the pitch of the bone.
  52307. */
  52308. this.adjustPitch = 0;
  52309. /**
  52310. * Used to make an adjustment to the roll of the bone.
  52311. */
  52312. this.adjustRoll = 0;
  52313. /**
  52314. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  52315. */
  52316. this.slerpAmount = 1;
  52317. this._boneQuat = BABYLON.Quaternion.Identity();
  52318. this._slerping = false;
  52319. this._firstFrameSkipped = false;
  52320. this._fowardAxis = BABYLON.Vector3.Forward();
  52321. this.mesh = mesh;
  52322. this.bone = bone;
  52323. this.target = target;
  52324. if (options) {
  52325. if (options.adjustYaw) {
  52326. this.adjustYaw = options.adjustYaw;
  52327. }
  52328. if (options.adjustPitch) {
  52329. this.adjustPitch = options.adjustPitch;
  52330. }
  52331. if (options.adjustRoll) {
  52332. this.adjustRoll = options.adjustRoll;
  52333. }
  52334. if (options.maxYaw != null) {
  52335. this.maxYaw = options.maxYaw;
  52336. }
  52337. else {
  52338. this.maxYaw = Math.PI;
  52339. }
  52340. if (options.minYaw != null) {
  52341. this.minYaw = options.minYaw;
  52342. }
  52343. else {
  52344. this.minYaw = -Math.PI;
  52345. }
  52346. if (options.maxPitch != null) {
  52347. this.maxPitch = options.maxPitch;
  52348. }
  52349. else {
  52350. this.maxPitch = Math.PI;
  52351. }
  52352. if (options.minPitch != null) {
  52353. this.minPitch = options.minPitch;
  52354. }
  52355. else {
  52356. this.minPitch = -Math.PI;
  52357. }
  52358. if (options.slerpAmount != null) {
  52359. this.slerpAmount = options.slerpAmount;
  52360. }
  52361. if (options.upAxis != null) {
  52362. this.upAxis = options.upAxis;
  52363. }
  52364. if (options.upAxisSpace != null) {
  52365. this.upAxisSpace = options.upAxisSpace;
  52366. }
  52367. if (options.yawAxis != null || options.pitchAxis != null) {
  52368. var newYawAxis = BABYLON.Axis.Y;
  52369. var newPitchAxis = BABYLON.Axis.X;
  52370. if (options.yawAxis != null) {
  52371. newYawAxis = options.yawAxis.clone();
  52372. newYawAxis.normalize();
  52373. }
  52374. if (options.pitchAxis != null) {
  52375. newPitchAxis = options.pitchAxis.clone();
  52376. newPitchAxis.normalize();
  52377. }
  52378. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  52379. this._transformYawPitch = BABYLON.Matrix.Identity();
  52380. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  52381. this._transformYawPitchInv = this._transformYawPitch.clone();
  52382. this._transformYawPitch.invert();
  52383. }
  52384. }
  52385. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  52386. this.upAxisSpace = BABYLON.Space.LOCAL;
  52387. }
  52388. }
  52389. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  52390. /**
  52391. * Get/set the minimum yaw angle that the bone can look to.
  52392. */
  52393. get: function () {
  52394. return this._minYaw;
  52395. },
  52396. set: function (value) {
  52397. this._minYaw = value;
  52398. this._minYawSin = Math.sin(value);
  52399. this._minYawCos = Math.cos(value);
  52400. if (this._maxYaw != null) {
  52401. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  52402. this._yawRange = this._maxYaw - this._minYaw;
  52403. }
  52404. },
  52405. enumerable: true,
  52406. configurable: true
  52407. });
  52408. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  52409. /**
  52410. * Get/set the maximum yaw angle that the bone can look to.
  52411. */
  52412. get: function () {
  52413. return this._maxYaw;
  52414. },
  52415. set: function (value) {
  52416. this._maxYaw = value;
  52417. this._maxYawSin = Math.sin(value);
  52418. this._maxYawCos = Math.cos(value);
  52419. if (this._minYaw != null) {
  52420. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  52421. this._yawRange = this._maxYaw - this._minYaw;
  52422. }
  52423. },
  52424. enumerable: true,
  52425. configurable: true
  52426. });
  52427. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  52428. /**
  52429. * Get/set the minimum pitch angle that the bone can look to.
  52430. */
  52431. get: function () {
  52432. return this._minPitch;
  52433. },
  52434. set: function (value) {
  52435. this._minPitch = value;
  52436. this._minPitchTan = Math.tan(value);
  52437. },
  52438. enumerable: true,
  52439. configurable: true
  52440. });
  52441. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  52442. /**
  52443. * Get/set the maximum pitch angle that the bone can look to.
  52444. */
  52445. get: function () {
  52446. return this._maxPitch;
  52447. },
  52448. set: function (value) {
  52449. this._maxPitch = value;
  52450. this._maxPitchTan = Math.tan(value);
  52451. },
  52452. enumerable: true,
  52453. configurable: true
  52454. });
  52455. /**
  52456. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  52457. */
  52458. BoneLookController.prototype.update = function () {
  52459. //skip the first frame when slerping so that the mesh rotation is correct
  52460. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  52461. this._firstFrameSkipped = true;
  52462. return;
  52463. }
  52464. var bone = this.bone;
  52465. var bonePos = BoneLookController._tmpVecs[0];
  52466. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  52467. var target = this.target;
  52468. var _tmpMat1 = BoneLookController._tmpMats[0];
  52469. var _tmpMat2 = BoneLookController._tmpMats[1];
  52470. var mesh = this.mesh;
  52471. var parentBone = bone.getParent();
  52472. var upAxis = BoneLookController._tmpVecs[1];
  52473. upAxis.copyFrom(this.upAxis);
  52474. if (this.upAxisSpace == BABYLON.Space.BONE) {
  52475. if (this._transformYawPitch) {
  52476. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  52477. }
  52478. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  52479. }
  52480. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  52481. mesh.getDirectionToRef(upAxis, upAxis);
  52482. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  52483. upAxis.normalize();
  52484. }
  52485. }
  52486. var checkYaw = false;
  52487. var checkPitch = false;
  52488. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  52489. checkYaw = true;
  52490. }
  52491. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  52492. checkPitch = true;
  52493. }
  52494. if (checkYaw || checkPitch) {
  52495. var spaceMat = BoneLookController._tmpMats[2];
  52496. var spaceMatInv = BoneLookController._tmpMats[3];
  52497. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  52498. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  52499. }
  52500. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  52501. spaceMat.copyFrom(mesh.getWorldMatrix());
  52502. }
  52503. else {
  52504. var forwardAxis = BoneLookController._tmpVecs[2];
  52505. forwardAxis.copyFrom(this._fowardAxis);
  52506. if (this._transformYawPitch) {
  52507. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  52508. }
  52509. if (parentBone) {
  52510. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  52511. }
  52512. else {
  52513. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  52514. }
  52515. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  52516. rightAxis.normalize();
  52517. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  52518. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  52519. }
  52520. spaceMat.invertToRef(spaceMatInv);
  52521. var xzlen;
  52522. if (checkPitch) {
  52523. var localTarget = BoneLookController._tmpVecs[3];
  52524. target.subtractToRef(bonePos, localTarget);
  52525. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  52526. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  52527. var pitch = Math.atan2(localTarget.y, xzlen);
  52528. var newPitch = pitch;
  52529. if (pitch > this._maxPitch) {
  52530. localTarget.y = this._maxPitchTan * xzlen;
  52531. newPitch = this._maxPitch;
  52532. }
  52533. else if (pitch < this._minPitch) {
  52534. localTarget.y = this._minPitchTan * xzlen;
  52535. newPitch = this._minPitch;
  52536. }
  52537. if (pitch != newPitch) {
  52538. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  52539. localTarget.addInPlace(bonePos);
  52540. target = localTarget;
  52541. }
  52542. }
  52543. if (checkYaw) {
  52544. var localTarget = BoneLookController._tmpVecs[4];
  52545. target.subtractToRef(bonePos, localTarget);
  52546. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  52547. var yaw = Math.atan2(localTarget.x, localTarget.z);
  52548. var newYaw = yaw;
  52549. if (yaw > this._maxYaw || yaw < this._minYaw) {
  52550. if (xzlen == null) {
  52551. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  52552. }
  52553. if (this._yawRange > Math.PI) {
  52554. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  52555. localTarget.z = this._maxYawCos * xzlen;
  52556. localTarget.x = this._maxYawSin * xzlen;
  52557. newYaw = this._maxYaw;
  52558. }
  52559. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  52560. localTarget.z = this._minYawCos * xzlen;
  52561. localTarget.x = this._minYawSin * xzlen;
  52562. newYaw = this._minYaw;
  52563. }
  52564. }
  52565. else {
  52566. if (yaw > this._maxYaw) {
  52567. localTarget.z = this._maxYawCos * xzlen;
  52568. localTarget.x = this._maxYawSin * xzlen;
  52569. newYaw = this._maxYaw;
  52570. }
  52571. else if (yaw < this._minYaw) {
  52572. localTarget.z = this._minYawCos * xzlen;
  52573. localTarget.x = this._minYawSin * xzlen;
  52574. newYaw = this._minYaw;
  52575. }
  52576. }
  52577. }
  52578. if (this._slerping && this._yawRange > Math.PI) {
  52579. //are we going to be crossing into the min/max region?
  52580. var boneFwd = BoneLookController._tmpVecs[8];
  52581. boneFwd.copyFrom(BABYLON.Axis.Z);
  52582. if (this._transformYawPitch) {
  52583. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  52584. }
  52585. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  52586. this._boneQuat.toRotationMatrix(boneRotMat);
  52587. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  52588. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  52589. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  52590. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  52591. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  52592. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  52593. if (angBtwTar > angBtwMidYaw) {
  52594. if (xzlen == null) {
  52595. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  52596. }
  52597. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  52598. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  52599. if (angBtwMin < angBtwMax) {
  52600. newYaw = boneYaw + Math.PI * .75;
  52601. localTarget.z = Math.cos(newYaw) * xzlen;
  52602. localTarget.x = Math.sin(newYaw) * xzlen;
  52603. }
  52604. else {
  52605. newYaw = boneYaw - Math.PI * .75;
  52606. localTarget.z = Math.cos(newYaw) * xzlen;
  52607. localTarget.x = Math.sin(newYaw) * xzlen;
  52608. }
  52609. }
  52610. }
  52611. if (yaw != newYaw) {
  52612. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  52613. localTarget.addInPlace(bonePos);
  52614. target = localTarget;
  52615. }
  52616. }
  52617. }
  52618. var zaxis = BoneLookController._tmpVecs[5];
  52619. var xaxis = BoneLookController._tmpVecs[6];
  52620. var yaxis = BoneLookController._tmpVecs[7];
  52621. var _tmpQuat = BoneLookController._tmpQuat;
  52622. target.subtractToRef(bonePos, zaxis);
  52623. zaxis.normalize();
  52624. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  52625. xaxis.normalize();
  52626. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  52627. yaxis.normalize();
  52628. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  52629. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  52630. return;
  52631. }
  52632. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  52633. return;
  52634. }
  52635. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  52636. return;
  52637. }
  52638. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  52639. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  52640. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  52641. }
  52642. if (this.slerpAmount < 1) {
  52643. if (!this._slerping) {
  52644. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  52645. }
  52646. if (this._transformYawPitch) {
  52647. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  52648. }
  52649. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  52650. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  52651. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  52652. this._slerping = true;
  52653. }
  52654. else {
  52655. if (this._transformYawPitch) {
  52656. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  52657. }
  52658. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  52659. this._slerping = false;
  52660. }
  52661. };
  52662. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  52663. var angDiff = ang2 - ang1;
  52664. angDiff %= Math.PI * 2;
  52665. if (angDiff > Math.PI) {
  52666. angDiff -= Math.PI * 2;
  52667. }
  52668. else if (angDiff < -Math.PI) {
  52669. angDiff += Math.PI * 2;
  52670. }
  52671. return angDiff;
  52672. };
  52673. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  52674. ang1 %= (2 * Math.PI);
  52675. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  52676. ang2 %= (2 * Math.PI);
  52677. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  52678. var ab = 0;
  52679. if (ang1 < ang2) {
  52680. ab = ang2 - ang1;
  52681. }
  52682. else {
  52683. ab = ang1 - ang2;
  52684. }
  52685. if (ab > Math.PI) {
  52686. ab = Math.PI * 2 - ab;
  52687. }
  52688. return ab;
  52689. };
  52690. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  52691. ang %= (2 * Math.PI);
  52692. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  52693. ang1 %= (2 * Math.PI);
  52694. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  52695. ang2 %= (2 * Math.PI);
  52696. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  52697. if (ang1 < ang2) {
  52698. if (ang > ang1 && ang < ang2) {
  52699. return true;
  52700. }
  52701. }
  52702. else {
  52703. if (ang > ang2 && ang < ang1) {
  52704. return true;
  52705. }
  52706. }
  52707. return false;
  52708. };
  52709. return BoneLookController;
  52710. }());
  52711. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52712. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  52713. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52714. BABYLON.BoneLookController = BoneLookController;
  52715. })(BABYLON || (BABYLON = {}));
  52716. //# sourceMappingURL=babylon.boneLookController.js.map
  52717. var BABYLON;
  52718. (function (BABYLON) {
  52719. var Skeleton = (function () {
  52720. function Skeleton(name, id, scene) {
  52721. this.name = name;
  52722. this.id = id;
  52723. this.bones = new Array();
  52724. this.needInitialSkinMatrix = false;
  52725. this._isDirty = true;
  52726. this._meshesWithPoseMatrix = new Array();
  52727. this._identity = BABYLON.Matrix.Identity();
  52728. this._ranges = {};
  52729. this._lastAbsoluteTransformsUpdateId = -1;
  52730. // Events
  52731. /**
  52732. * An event triggered before computing the skeleton's matrices
  52733. * @type {BABYLON.Observable}
  52734. */
  52735. this.onBeforeComputeObservable = new BABYLON.Observable();
  52736. this.bones = [];
  52737. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52738. scene.skeletons.push(this);
  52739. //make sure it will recalculate the matrix next time prepare is called.
  52740. this._isDirty = true;
  52741. }
  52742. // Members
  52743. Skeleton.prototype.getTransformMatrices = function (mesh) {
  52744. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  52745. return mesh._bonesTransformMatrices;
  52746. }
  52747. if (!this._transformMatrices) {
  52748. this.prepare();
  52749. }
  52750. return this._transformMatrices;
  52751. };
  52752. Skeleton.prototype.getScene = function () {
  52753. return this._scene;
  52754. };
  52755. // Methods
  52756. /**
  52757. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  52758. */
  52759. Skeleton.prototype.toString = function (fullDetails) {
  52760. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  52761. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52762. if (fullDetails) {
  52763. ret += ", Ranges: {";
  52764. var first = true;
  52765. for (var name_1 in this._ranges) {
  52766. if (first) {
  52767. ret += ", ";
  52768. first = false;
  52769. }
  52770. ret += name_1;
  52771. }
  52772. ret += "}";
  52773. }
  52774. return ret;
  52775. };
  52776. /**
  52777. * Get bone's index searching by name
  52778. * @param {string} name is bone's name to search for
  52779. * @return {number} Indice of the bone. Returns -1 if not found
  52780. */
  52781. Skeleton.prototype.getBoneIndexByName = function (name) {
  52782. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  52783. if (this.bones[boneIndex].name === name) {
  52784. return boneIndex;
  52785. }
  52786. }
  52787. return -1;
  52788. };
  52789. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  52790. // check name not already in use
  52791. if (!this._ranges[name]) {
  52792. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  52793. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  52794. if (this.bones[i].animations[0]) {
  52795. this.bones[i].animations[0].createRange(name, from, to);
  52796. }
  52797. }
  52798. }
  52799. };
  52800. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  52801. if (deleteFrames === void 0) { deleteFrames = true; }
  52802. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  52803. if (this.bones[i].animations[0]) {
  52804. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  52805. }
  52806. }
  52807. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  52808. };
  52809. Skeleton.prototype.getAnimationRange = function (name) {
  52810. return this._ranges[name];
  52811. };
  52812. /**
  52813. * Returns as an Array, all AnimationRanges defined on this skeleton
  52814. */
  52815. Skeleton.prototype.getAnimationRanges = function () {
  52816. var animationRanges = [];
  52817. var name;
  52818. var i = 0;
  52819. for (name in this._ranges) {
  52820. animationRanges[i] = this._ranges[name];
  52821. i++;
  52822. }
  52823. return animationRanges;
  52824. };
  52825. /**
  52826. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  52827. */
  52828. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  52829. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  52830. if (this._ranges[name] || !source.getAnimationRange(name)) {
  52831. return false;
  52832. }
  52833. var ret = true;
  52834. var frameOffset = this._getHighestAnimationFrame() + 1;
  52835. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  52836. var boneDict = {};
  52837. var sourceBones = source.bones;
  52838. var nBones;
  52839. var i;
  52840. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  52841. boneDict[sourceBones[i].name] = sourceBones[i];
  52842. }
  52843. if (this.bones.length !== sourceBones.length) {
  52844. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  52845. ret = false;
  52846. }
  52847. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  52848. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  52849. var boneName = this.bones[i].name;
  52850. var sourceBone = boneDict[boneName];
  52851. if (sourceBone) {
  52852. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  52853. }
  52854. else {
  52855. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  52856. ret = false;
  52857. }
  52858. }
  52859. // do not call createAnimationRange(), since it also is done to bones, which was already done
  52860. var range = source.getAnimationRange(name);
  52861. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  52862. return ret;
  52863. };
  52864. Skeleton.prototype.returnToRest = function () {
  52865. for (var index = 0; index < this.bones.length; index++) {
  52866. this.bones[index].returnToRest();
  52867. }
  52868. };
  52869. Skeleton.prototype._getHighestAnimationFrame = function () {
  52870. var ret = 0;
  52871. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  52872. if (this.bones[i].animations[0]) {
  52873. var highest = this.bones[i].animations[0].getHighestFrame();
  52874. if (ret < highest) {
  52875. ret = highest;
  52876. }
  52877. }
  52878. }
  52879. return ret;
  52880. };
  52881. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  52882. var range = this.getAnimationRange(name);
  52883. if (!range) {
  52884. return null;
  52885. }
  52886. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  52887. };
  52888. Skeleton.prototype._markAsDirty = function () {
  52889. this._isDirty = true;
  52890. };
  52891. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  52892. this._meshesWithPoseMatrix.push(mesh);
  52893. };
  52894. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  52895. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  52896. if (index > -1) {
  52897. this._meshesWithPoseMatrix.splice(index, 1);
  52898. }
  52899. };
  52900. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  52901. this.onBeforeComputeObservable.notifyObservers(this);
  52902. for (var index = 0; index < this.bones.length; index++) {
  52903. var bone = this.bones[index];
  52904. var parentBone = bone.getParent();
  52905. if (parentBone) {
  52906. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  52907. }
  52908. else {
  52909. if (initialSkinMatrix) {
  52910. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  52911. }
  52912. else {
  52913. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  52914. }
  52915. }
  52916. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  52917. }
  52918. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  52919. };
  52920. Skeleton.prototype.prepare = function () {
  52921. if (!this._isDirty) {
  52922. return;
  52923. }
  52924. if (this.needInitialSkinMatrix) {
  52925. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  52926. var mesh = this._meshesWithPoseMatrix[index];
  52927. var poseMatrix = mesh.getPoseMatrix();
  52928. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  52929. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  52930. }
  52931. if (this._synchronizedWithMesh !== mesh) {
  52932. this._synchronizedWithMesh = mesh;
  52933. // Prepare bones
  52934. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  52935. var bone = this.bones[boneIndex];
  52936. if (!bone.getParent()) {
  52937. var matrix = bone.getBaseMatrix();
  52938. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  52939. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  52940. }
  52941. }
  52942. }
  52943. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  52944. }
  52945. }
  52946. else {
  52947. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  52948. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  52949. }
  52950. this._computeTransformMatrices(this._transformMatrices, null);
  52951. }
  52952. this._isDirty = false;
  52953. this._scene._activeBones.addCount(this.bones.length, false);
  52954. };
  52955. Skeleton.prototype.getAnimatables = function () {
  52956. if (!this._animatables || this._animatables.length !== this.bones.length) {
  52957. this._animatables = [];
  52958. for (var index = 0; index < this.bones.length; index++) {
  52959. this._animatables.push(this.bones[index]);
  52960. }
  52961. }
  52962. return this._animatables;
  52963. };
  52964. Skeleton.prototype.clone = function (name, id) {
  52965. var result = new Skeleton(name, id || name, this._scene);
  52966. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  52967. for (var index = 0; index < this.bones.length; index++) {
  52968. var source = this.bones[index];
  52969. var parentBone = null;
  52970. if (source.getParent()) {
  52971. var parentIndex = this.bones.indexOf(source.getParent());
  52972. parentBone = result.bones[parentIndex];
  52973. }
  52974. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  52975. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  52976. }
  52977. if (this._ranges) {
  52978. result._ranges = {};
  52979. for (var rangeName in this._ranges) {
  52980. result._ranges[rangeName] = this._ranges[rangeName].clone();
  52981. }
  52982. }
  52983. this._isDirty = true;
  52984. return result;
  52985. };
  52986. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  52987. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  52988. this.bones.forEach(function (bone) {
  52989. bone.animations.forEach(function (animation) {
  52990. animation.enableBlending = true;
  52991. animation.blendingSpeed = blendingSpeed;
  52992. });
  52993. });
  52994. };
  52995. Skeleton.prototype.dispose = function () {
  52996. this._meshesWithPoseMatrix = [];
  52997. // Animations
  52998. this.getScene().stopAnimation(this);
  52999. // Remove from scene
  53000. this.getScene().removeSkeleton(this);
  53001. };
  53002. Skeleton.prototype.serialize = function () {
  53003. var serializationObject = {};
  53004. serializationObject.name = this.name;
  53005. serializationObject.id = this.id;
  53006. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  53007. serializationObject.bones = [];
  53008. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  53009. for (var index = 0; index < this.bones.length; index++) {
  53010. var bone = this.bones[index];
  53011. var serializedBone = {
  53012. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  53013. name: bone.name,
  53014. matrix: bone.getBaseMatrix().toArray(),
  53015. rest: bone.getRestPose().toArray()
  53016. };
  53017. serializationObject.bones.push(serializedBone);
  53018. if (bone.length) {
  53019. serializedBone.length = bone.length;
  53020. }
  53021. if (bone.animations && bone.animations.length > 0) {
  53022. serializedBone.animation = bone.animations[0].serialize();
  53023. }
  53024. serializationObject.ranges = [];
  53025. for (var name in this._ranges) {
  53026. var range = {};
  53027. range.name = name;
  53028. range.from = this._ranges[name].from;
  53029. range.to = this._ranges[name].to;
  53030. serializationObject.ranges.push(range);
  53031. }
  53032. }
  53033. return serializationObject;
  53034. };
  53035. Skeleton.Parse = function (parsedSkeleton, scene) {
  53036. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  53037. if (parsedSkeleton.dimensionsAtRest) {
  53038. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  53039. }
  53040. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  53041. var index;
  53042. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  53043. var parsedBone = parsedSkeleton.bones[index];
  53044. var parentBone = null;
  53045. if (parsedBone.parentBoneIndex > -1) {
  53046. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  53047. }
  53048. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  53049. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  53050. if (parsedBone.length) {
  53051. bone.length = parsedBone.length;
  53052. }
  53053. if (parsedBone.animation) {
  53054. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  53055. }
  53056. }
  53057. // placed after bones, so createAnimationRange can cascade down
  53058. if (parsedSkeleton.ranges) {
  53059. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  53060. var data = parsedSkeleton.ranges[index];
  53061. skeleton.createAnimationRange(data.name, data.from, data.to);
  53062. }
  53063. }
  53064. return skeleton;
  53065. };
  53066. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  53067. if (forceUpdate === void 0) { forceUpdate = false; }
  53068. var renderId = this._scene.getRenderId();
  53069. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  53070. this.bones[0].computeAbsoluteTransforms();
  53071. this._lastAbsoluteTransformsUpdateId = renderId;
  53072. }
  53073. };
  53074. Skeleton.prototype.getPoseMatrix = function () {
  53075. var poseMatrix;
  53076. if (this._meshesWithPoseMatrix.length > 0) {
  53077. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  53078. }
  53079. return poseMatrix;
  53080. };
  53081. return Skeleton;
  53082. }());
  53083. BABYLON.Skeleton = Skeleton;
  53084. })(BABYLON || (BABYLON = {}));
  53085. //# sourceMappingURL=babylon.skeleton.js.map
  53086. var BABYLON;
  53087. (function (BABYLON) {
  53088. var Internals;
  53089. (function (Internals) {
  53090. var FileFaceOrientation = (function () {
  53091. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  53092. this.name = name;
  53093. this.worldAxisForNormal = worldAxisForNormal;
  53094. this.worldAxisForFileX = worldAxisForFileX;
  53095. this.worldAxisForFileY = worldAxisForFileY;
  53096. }
  53097. return FileFaceOrientation;
  53098. }());
  53099. ;
  53100. /**
  53101. * Helper class dealing with the extraction of spherical polynomial dataArray
  53102. * from a cube map.
  53103. */
  53104. var CubeMapToSphericalPolynomialTools = (function () {
  53105. function CubeMapToSphericalPolynomialTools() {
  53106. }
  53107. /**
  53108. * Converts a cubemap to the according Spherical Polynomial data.
  53109. * This extracts the first 3 orders only as they are the only one used in the lighting.
  53110. *
  53111. * @param cubeInfo The Cube map to extract the information from.
  53112. * @return The Spherical Polynomial data.
  53113. */
  53114. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  53115. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  53116. var totalSolidAngle = 0.0;
  53117. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  53118. var du = 2.0 / cubeInfo.size;
  53119. var dv = du;
  53120. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  53121. var minUV = du * 0.5 - 1.0;
  53122. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53123. var fileFace = this.FileFaces[faceIndex];
  53124. var dataArray = cubeInfo[fileFace.name];
  53125. var v = minUV;
  53126. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  53127. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  53128. // Because SP is still linear, so summation is fine in that basis.
  53129. for (var y = 0; y < cubeInfo.size; y++) {
  53130. var u = minUV;
  53131. for (var x = 0; x < cubeInfo.size; x++) {
  53132. // World direction (not normalised)
  53133. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  53134. worldDirection.normalize();
  53135. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  53136. if (1) {
  53137. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  53138. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  53139. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  53140. var color = new BABYLON.Color3(r, g, b);
  53141. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53142. }
  53143. else {
  53144. if (faceIndex == 0) {
  53145. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53146. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53147. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53148. }
  53149. else if (faceIndex == 1) {
  53150. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53151. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53152. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53153. }
  53154. else if (faceIndex == 2) {
  53155. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53156. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53157. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53158. }
  53159. else if (faceIndex == 3) {
  53160. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53161. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53162. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53163. }
  53164. else if (faceIndex == 4) {
  53165. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53166. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53167. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53168. }
  53169. else if (faceIndex == 5) {
  53170. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53171. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53172. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53173. }
  53174. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  53175. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53176. }
  53177. totalSolidAngle += deltaSolidAngle;
  53178. u += du;
  53179. }
  53180. v += dv;
  53181. }
  53182. }
  53183. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  53184. var correction = correctSolidAngle / totalSolidAngle;
  53185. sphericalHarmonics.scale(correction);
  53186. // Additionally scale by pi -- audit needed
  53187. sphericalHarmonics.scale(1.0 / Math.PI);
  53188. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  53189. };
  53190. return CubeMapToSphericalPolynomialTools;
  53191. }());
  53192. CubeMapToSphericalPolynomialTools.FileFaces = [
  53193. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  53194. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  53195. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  53196. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  53197. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  53198. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  53199. ];
  53200. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  53201. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53202. })(BABYLON || (BABYLON = {}));
  53203. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  53204. var BABYLON;
  53205. (function (BABYLON) {
  53206. var Internals;
  53207. (function (Internals) {
  53208. /**
  53209. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  53210. */
  53211. var PanoramaToCubeMapTools = (function () {
  53212. function PanoramaToCubeMapTools() {
  53213. }
  53214. /**
  53215. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  53216. *
  53217. * @param float32Array The source data.
  53218. * @param inputWidth The width of the input panorama.
  53219. * @param inputhHeight The height of the input panorama.
  53220. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  53221. * @return The cubemap data
  53222. */
  53223. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  53224. if (!float32Array) {
  53225. throw "ConvertPanoramaToCubemap: input cannot be null";
  53226. }
  53227. if (float32Array.length != inputWidth * inputHeight * 3) {
  53228. throw "ConvertPanoramaToCubemap: input size is wrong";
  53229. }
  53230. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  53231. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  53232. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  53233. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  53234. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  53235. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  53236. return {
  53237. front: textureFront,
  53238. back: textureBack,
  53239. left: textureLeft,
  53240. right: textureRight,
  53241. up: textureUp,
  53242. down: textureDown,
  53243. size: size
  53244. };
  53245. };
  53246. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  53247. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  53248. var textureArray = new Float32Array(buffer);
  53249. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  53250. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  53251. var dy = 1 / texSize;
  53252. var fy = 0;
  53253. for (var y = 0; y < texSize; y++) {
  53254. var xv1 = faceData[0];
  53255. var xv2 = faceData[2];
  53256. for (var x = 0; x < texSize; x++) {
  53257. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  53258. v.normalize();
  53259. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  53260. // 3 channels per pixels
  53261. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  53262. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  53263. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  53264. xv1 = xv1.add(rotDX1);
  53265. xv2 = xv2.add(rotDX2);
  53266. }
  53267. fy += dy;
  53268. }
  53269. return textureArray;
  53270. };
  53271. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  53272. var theta = Math.atan2(vDir.z, vDir.x);
  53273. var phi = Math.acos(vDir.y);
  53274. while (theta < -Math.PI)
  53275. theta += 2 * Math.PI;
  53276. while (theta > Math.PI)
  53277. theta -= 2 * Math.PI;
  53278. var dx = theta / Math.PI;
  53279. var dy = phi / Math.PI;
  53280. // recenter.
  53281. dx = dx * 0.5 + 0.5;
  53282. var px = Math.round(dx * inputWidth);
  53283. if (px < 0)
  53284. px = 0;
  53285. else if (px >= inputWidth)
  53286. px = inputWidth - 1;
  53287. var py = Math.round(dy * inputHeight);
  53288. if (py < 0)
  53289. py = 0;
  53290. else if (py >= inputHeight)
  53291. py = inputHeight - 1;
  53292. var inputY = (inputHeight - py - 1);
  53293. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  53294. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  53295. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  53296. return {
  53297. r: r,
  53298. g: g,
  53299. b: b
  53300. };
  53301. };
  53302. return PanoramaToCubeMapTools;
  53303. }());
  53304. PanoramaToCubeMapTools.FACE_FRONT = [
  53305. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53306. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53307. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53308. new BABYLON.Vector3(1.0, 1.0, -1.0)
  53309. ];
  53310. PanoramaToCubeMapTools.FACE_BACK = [
  53311. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53312. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53313. new BABYLON.Vector3(1.0, 1.0, 1.0),
  53314. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  53315. ];
  53316. PanoramaToCubeMapTools.FACE_RIGHT = [
  53317. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53318. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53319. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53320. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53321. ];
  53322. PanoramaToCubeMapTools.FACE_LEFT = [
  53323. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53324. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53325. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53326. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  53327. ];
  53328. PanoramaToCubeMapTools.FACE_DOWN = [
  53329. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53330. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53331. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53332. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53333. ];
  53334. PanoramaToCubeMapTools.FACE_UP = [
  53335. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53336. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53337. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53338. new BABYLON.Vector3(1.0, -1.0, -1.0)
  53339. ];
  53340. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  53341. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53342. })(BABYLON || (BABYLON = {}));
  53343. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  53344. var BABYLON;
  53345. (function (BABYLON) {
  53346. var Internals;
  53347. (function (Internals) {
  53348. ;
  53349. /**
  53350. * This groups tools to convert HDR texture to native colors array.
  53351. */
  53352. var HDRTools = (function () {
  53353. function HDRTools() {
  53354. }
  53355. HDRTools.Ldexp = function (mantissa, exponent) {
  53356. if (exponent > 1023) {
  53357. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  53358. }
  53359. if (exponent < -1074) {
  53360. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  53361. }
  53362. return mantissa * Math.pow(2, exponent);
  53363. };
  53364. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  53365. if (exponent > 0) {
  53366. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  53367. float32array[index + 0] = red * exponent;
  53368. float32array[index + 1] = green * exponent;
  53369. float32array[index + 2] = blue * exponent;
  53370. }
  53371. else {
  53372. float32array[index + 0] = 0;
  53373. float32array[index + 1] = 0;
  53374. float32array[index + 2] = 0;
  53375. }
  53376. };
  53377. HDRTools.readStringLine = function (uint8array, startIndex) {
  53378. var line = "";
  53379. var character = "";
  53380. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  53381. character = String.fromCharCode(uint8array[i]);
  53382. if (character == "\n") {
  53383. break;
  53384. }
  53385. line += character;
  53386. }
  53387. return line;
  53388. };
  53389. /**
  53390. * Reads header information from an RGBE texture stored in a native array.
  53391. * More information on this format are available here:
  53392. * https://en.wikipedia.org/wiki/RGBE_image_format
  53393. *
  53394. * @param uint8array The binary file stored in native array.
  53395. * @return The header information.
  53396. */
  53397. HDRTools.RGBE_ReadHeader = function (uint8array) {
  53398. var height = 0;
  53399. var width = 0;
  53400. var line = this.readStringLine(uint8array, 0);
  53401. if (line[0] != '#' || line[1] != '?') {
  53402. throw "Bad HDR Format.";
  53403. }
  53404. var endOfHeader = false;
  53405. var findFormat = false;
  53406. var lineIndex = 0;
  53407. do {
  53408. lineIndex += (line.length + 1);
  53409. line = this.readStringLine(uint8array, lineIndex);
  53410. if (line == "FORMAT=32-bit_rle_rgbe") {
  53411. findFormat = true;
  53412. }
  53413. else if (line.length == 0) {
  53414. endOfHeader = true;
  53415. }
  53416. } while (!endOfHeader);
  53417. if (!findFormat) {
  53418. throw "HDR Bad header format, unsupported FORMAT";
  53419. }
  53420. lineIndex += (line.length + 1);
  53421. line = this.readStringLine(uint8array, lineIndex);
  53422. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  53423. var match = sizeRegexp.exec(line);
  53424. // TODO. Support +Y and -X if needed.
  53425. if (match.length < 3) {
  53426. throw "HDR Bad header format, no size";
  53427. }
  53428. width = parseInt(match[2]);
  53429. height = parseInt(match[1]);
  53430. if (width < 8 || width > 0x7fff) {
  53431. throw "HDR Bad header format, unsupported size";
  53432. }
  53433. lineIndex += (line.length + 1);
  53434. return {
  53435. height: height,
  53436. width: width,
  53437. dataPosition: lineIndex
  53438. };
  53439. };
  53440. /**
  53441. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  53442. * This RGBE texture needs to store the information as a panorama.
  53443. *
  53444. * More information on this format are available here:
  53445. * https://en.wikipedia.org/wiki/RGBE_image_format
  53446. *
  53447. * @param buffer The binary file stored in an array buffer.
  53448. * @param size The expected size of the extracted cubemap.
  53449. * @return The Cube Map information.
  53450. */
  53451. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  53452. var uint8array = new Uint8Array(buffer);
  53453. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  53454. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53455. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  53456. return cubeMapData;
  53457. };
  53458. /**
  53459. * Returns the pixels data extracted from an RGBE texture.
  53460. * This pixels will be stored left to right up to down in the R G B order in one array.
  53461. *
  53462. * More information on this format are available here:
  53463. * https://en.wikipedia.org/wiki/RGBE_image_format
  53464. *
  53465. * @param uint8array The binary file stored in an array buffer.
  53466. * @param hdrInfo The header information of the file.
  53467. * @return The pixels data in RGB right to left up to down order.
  53468. */
  53469. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  53470. // Keep for multi format supports.
  53471. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53472. };
  53473. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  53474. var num_scanlines = hdrInfo.height;
  53475. var scanline_width = hdrInfo.width;
  53476. var a, b, c, d, count;
  53477. var dataIndex = hdrInfo.dataPosition;
  53478. var index = 0, endIndex = 0, i = 0;
  53479. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  53480. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  53481. // 3 channels of 4 bytes per pixel in float.
  53482. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  53483. var resultArray = new Float32Array(resultBuffer);
  53484. // read in each successive scanline
  53485. while (num_scanlines > 0) {
  53486. a = uint8array[dataIndex++];
  53487. b = uint8array[dataIndex++];
  53488. c = uint8array[dataIndex++];
  53489. d = uint8array[dataIndex++];
  53490. if (a != 2 || b != 2 || (c & 0x80)) {
  53491. // this file is not run length encoded
  53492. throw "HDR Bad header format, not RLE";
  53493. }
  53494. if (((c << 8) | d) != scanline_width) {
  53495. throw "HDR Bad header format, wrong scan line width";
  53496. }
  53497. index = 0;
  53498. // read each of the four channels for the scanline into the buffer
  53499. for (i = 0; i < 4; i++) {
  53500. endIndex = (i + 1) * scanline_width;
  53501. while (index < endIndex) {
  53502. a = uint8array[dataIndex++];
  53503. b = uint8array[dataIndex++];
  53504. if (a > 128) {
  53505. // a run of the same value
  53506. count = a - 128;
  53507. if ((count == 0) || (count > endIndex - index)) {
  53508. throw "HDR Bad Format, bad scanline data (run)";
  53509. }
  53510. while (count-- > 0) {
  53511. scanLineArray[index++] = b;
  53512. }
  53513. }
  53514. else {
  53515. // a non-run
  53516. count = a;
  53517. if ((count == 0) || (count > endIndex - index)) {
  53518. throw "HDR Bad Format, bad scanline data (non-run)";
  53519. }
  53520. scanLineArray[index++] = b;
  53521. if (--count > 0) {
  53522. for (var j = 0; j < count; j++) {
  53523. scanLineArray[index++] = uint8array[dataIndex++];
  53524. }
  53525. }
  53526. }
  53527. }
  53528. }
  53529. // now convert data from buffer into floats
  53530. for (i = 0; i < scanline_width; i++) {
  53531. a = scanLineArray[i];
  53532. b = scanLineArray[i + scanline_width];
  53533. c = scanLineArray[i + 2 * scanline_width];
  53534. d = scanLineArray[i + 3 * scanline_width];
  53535. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  53536. }
  53537. num_scanlines--;
  53538. }
  53539. return resultArray;
  53540. };
  53541. return HDRTools;
  53542. }());
  53543. Internals.HDRTools = HDRTools;
  53544. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53545. })(BABYLON || (BABYLON = {}));
  53546. //# sourceMappingURL=babylon.hdr.js.map
  53547. //_______________________________________________________________
  53548. // Extracted from CubeMapGen:
  53549. // https://code.google.com/archive/p/cubemapgen/
  53550. //
  53551. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53552. //_______________________________________________________________
  53553. var BABYLON;
  53554. (function (BABYLON) {
  53555. var Internals;
  53556. (function (Internals) {
  53557. /**
  53558. * The bounding box information used during the conversion process.
  53559. */
  53560. var CMGBoundinBox = (function () {
  53561. function CMGBoundinBox() {
  53562. this.min = new BABYLON.Vector3(0, 0, 0);
  53563. this.max = new BABYLON.Vector3(0, 0, 0);
  53564. this.clear();
  53565. }
  53566. CMGBoundinBox.prototype.clear = function () {
  53567. this.min.x = CMGBoundinBox.MAX;
  53568. this.min.y = CMGBoundinBox.MAX;
  53569. this.min.z = CMGBoundinBox.MAX;
  53570. this.max.x = CMGBoundinBox.MIN;
  53571. this.max.y = CMGBoundinBox.MIN;
  53572. this.max.z = CMGBoundinBox.MIN;
  53573. };
  53574. CMGBoundinBox.prototype.augment = function (x, y, z) {
  53575. this.min.x = Math.min(this.min.x, x);
  53576. this.min.y = Math.min(this.min.y, y);
  53577. this.min.z = Math.min(this.min.z, z);
  53578. this.max.x = Math.max(this.max.x, x);
  53579. this.max.y = Math.max(this.max.y, y);
  53580. this.max.z = Math.max(this.max.z, z);
  53581. };
  53582. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  53583. this.min.x = Math.max(this.min.x, x);
  53584. this.min.y = Math.max(this.min.y, y);
  53585. this.min.z = Math.max(this.min.z, z);
  53586. };
  53587. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  53588. this.max.x = Math.min(this.max.x, x);
  53589. this.max.y = Math.min(this.max.y, y);
  53590. this.max.z = Math.min(this.max.z, z);
  53591. };
  53592. CMGBoundinBox.prototype.empty = function () {
  53593. if ((this.min.x > this.max.y) ||
  53594. (this.min.y > this.max.y) ||
  53595. (this.min.z > this.max.y)) {
  53596. return true;
  53597. }
  53598. else {
  53599. return false;
  53600. }
  53601. };
  53602. return CMGBoundinBox;
  53603. }());
  53604. CMGBoundinBox.MAX = Number.MAX_VALUE;
  53605. CMGBoundinBox.MIN = Number.MIN_VALUE;
  53606. /**
  53607. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  53608. * required by the glossinees of a material.
  53609. *
  53610. * This only supports the cosine drop power as well as Warp fixup generation method.
  53611. *
  53612. * This is using the process from CubeMapGen described here:
  53613. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53614. */
  53615. var PMREMGenerator = (function () {
  53616. /**
  53617. * Constructor of the generator.
  53618. *
  53619. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  53620. * @param inputSize The size of the cubemap faces
  53621. * @param outputSize The size of the output cubemap faces
  53622. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  53623. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  53624. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  53625. * @param specularPower The max specular level of the desired cubemap
  53626. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  53627. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  53628. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  53629. */
  53630. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  53631. this.input = input;
  53632. this.inputSize = inputSize;
  53633. this.outputSize = outputSize;
  53634. this.maxNumMipLevels = maxNumMipLevels;
  53635. this.numChannels = numChannels;
  53636. this.isFloat = isFloat;
  53637. this.specularPower = specularPower;
  53638. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  53639. this.excludeBase = excludeBase;
  53640. this.fixup = fixup;
  53641. this._outputSurface = [];
  53642. this._numMipLevels = 0;
  53643. }
  53644. /**
  53645. * Launches the filter process and return the result.
  53646. *
  53647. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  53648. */
  53649. PMREMGenerator.prototype.filterCubeMap = function () {
  53650. // Init cubemap processor
  53651. this.init();
  53652. // Filters the cubemap
  53653. this.filterCubeMapMipChain();
  53654. // Returns the filtered mips.
  53655. return this._outputSurface;
  53656. };
  53657. PMREMGenerator.prototype.init = function () {
  53658. var i;
  53659. var j;
  53660. var mipLevelSize;
  53661. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  53662. if (this.maxNumMipLevels == 0) {
  53663. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  53664. }
  53665. //first miplevel size
  53666. mipLevelSize = this.outputSize;
  53667. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  53668. for (j = 0; j < this.maxNumMipLevels; j++) {
  53669. this._outputSurface.length++;
  53670. this._outputSurface[j] = [];
  53671. //Iterate over faces for output images
  53672. for (i = 0; i < 6; i++) {
  53673. this._outputSurface[j].length++;
  53674. // Initializes a new array for the output.
  53675. if (this.isFloat) {
  53676. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53677. }
  53678. else {
  53679. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53680. }
  53681. }
  53682. //next mip level is half size
  53683. mipLevelSize >>= 1;
  53684. this._numMipLevels++;
  53685. //terminate if mip chain becomes too small
  53686. if (mipLevelSize == 0) {
  53687. this.maxNumMipLevels = j;
  53688. return;
  53689. }
  53690. }
  53691. };
  53692. //--------------------------------------------------------------------------------------
  53693. //Cube map filtering and mip chain generation.
  53694. // the cube map filtereing is specified using a number of parameters:
  53695. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  53696. // indicates the region of the hemisphere to filter over for each tap.
  53697. //
  53698. // Note that the top mip level is also a filtered version of the original input images
  53699. // as well in order to create mip chains for diffuse environment illumination.
  53700. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  53701. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  53702. //
  53703. // Then the mip angle used to genreate the next level of the mip chain from the first level
  53704. // is a_InitialMipAngle
  53705. //
  53706. // The angle for the subsequent levels of the mip chain are specified by their parents
  53707. // filtering angle and a per-level scale and bias
  53708. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  53709. //
  53710. //--------------------------------------------------------------------------------------
  53711. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  53712. // First, take count of the lighting model to modify SpecularPower
  53713. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  53714. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  53715. //Cone angle start (for generating subsequent mip levels)
  53716. var currentSpecularPower = this.specularPower;
  53717. //Build filter lookup tables based on the source miplevel size
  53718. this.precomputeFilterLookupTables(this.inputSize);
  53719. // Note that we need to filter the first level before generating mipmap
  53720. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  53721. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  53722. // TODO : Write a function to copy and scale the base mipmap in output
  53723. // I am just lazy here and just put a high specular power value, and do some if.
  53724. if (this.excludeBase && (levelIndex == 0)) {
  53725. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  53726. currentSpecularPower = 100000.0;
  53727. }
  53728. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  53729. var srcCubeImage = this.input;
  53730. var dstCubeImage = this._outputSurface[levelIndex];
  53731. var dstSize = this.outputSize >> levelIndex;
  53732. // Compute required angle.
  53733. var angle = this.getBaseFilterAngle(currentSpecularPower);
  53734. // filter cube surfaces
  53735. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  53736. // fix seams
  53737. if (this.fixup) {
  53738. this.fixupCubeEdges(dstCubeImage, dstSize);
  53739. }
  53740. // Decrease the specular power to generate the mipmap chain
  53741. // TODO : Use another method for Exclude (see first comment at start of the function
  53742. if (this.excludeBase && (levelIndex == 0)) {
  53743. currentSpecularPower = this.specularPower;
  53744. }
  53745. currentSpecularPower *= this.cosinePowerDropPerMip;
  53746. }
  53747. };
  53748. //--------------------------------------------------------------------------------------
  53749. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  53750. // It allow to optimize the texel to access base on the specular power.
  53751. //--------------------------------------------------------------------------------------
  53752. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  53753. // We want to find the alpha such that:
  53754. // cos(alpha)^cosinePower = epsilon
  53755. // That's: acos(epsilon^(1/cosinePower))
  53756. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  53757. var angle = 180.0;
  53758. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  53759. angle *= 180.0 / Math.PI; // Convert to degree
  53760. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  53761. return angle;
  53762. };
  53763. //--------------------------------------------------------------------------------------
  53764. //Builds the following lookup tables prior to filtering:
  53765. // -normalizer cube map
  53766. // -tap weight lookup table
  53767. //
  53768. //--------------------------------------------------------------------------------------
  53769. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  53770. var srcTexelAngle;
  53771. var iCubeFace;
  53772. //clear pre-existing normalizer cube map
  53773. this._normCubeMap = [];
  53774. //Normalized vectors per cubeface and per-texel solid angle
  53775. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  53776. };
  53777. //--------------------------------------------------------------------------------------
  53778. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  53779. //
  53780. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  53781. //
  53782. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  53783. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  53784. // below
  53785. //--------------------------------------------------------------------------------------
  53786. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  53787. var iCubeFace;
  53788. var u;
  53789. var v;
  53790. //iterate over cube faces
  53791. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53792. //First three channels for norm cube, and last channel for solid angle
  53793. this._normCubeMap.push(new Float32Array(size * size * 4));
  53794. //fast texture walk, build normalizer cube map
  53795. var facesData = this.input[iCubeFace];
  53796. for (v = 0; v < size; v++) {
  53797. for (u = 0; u < size; u++) {
  53798. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  53799. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  53800. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  53801. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  53802. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  53803. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  53804. }
  53805. }
  53806. }
  53807. };
  53808. //--------------------------------------------------------------------------------------
  53809. // Convert cubemap face texel coordinates and face idx to 3D vector
  53810. // note the U and V coords are integer coords and range from 0 to size-1
  53811. // this routine can be used to generate a normalizer cube map
  53812. //--------------------------------------------------------------------------------------
  53813. // SL BEGIN
  53814. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  53815. var nvcU;
  53816. var nvcV;
  53817. var tempVec;
  53818. // Change from original AMD code
  53819. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53820. // + 0.5f is for texel center addressing
  53821. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  53822. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  53823. // warp fixup
  53824. if (fixup && size > 1) {
  53825. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  53826. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  53827. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  53828. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  53829. }
  53830. // Get current vector
  53831. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  53832. // U contribution
  53833. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53834. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  53835. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  53836. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  53837. // V contribution and Sum
  53838. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53839. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  53840. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  53841. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  53842. //add face axis
  53843. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  53844. PMREMGenerator._vectorTemp.x += faceAxis[0];
  53845. PMREMGenerator._vectorTemp.y += faceAxis[1];
  53846. PMREMGenerator._vectorTemp.z += faceAxis[2];
  53847. //normalize vector
  53848. PMREMGenerator._vectorTemp.normalize();
  53849. return PMREMGenerator._vectorTemp;
  53850. };
  53851. //--------------------------------------------------------------------------------------
  53852. // Convert 3D vector to cubemap face texel coordinates and face idx
  53853. // note the U and V coords are integer coords and range from 0 to size-1
  53854. // this routine can be used to generate a normalizer cube map
  53855. //
  53856. // returns face IDX and texel coords
  53857. //--------------------------------------------------------------------------------------
  53858. // SL BEGIN
  53859. /*
  53860. Mapping Texture Coordinates to Cube Map Faces
  53861. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  53862. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  53863. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  53864. map arrangement in Pixar's RenderMan package.
  53865. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  53866. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  53867. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  53868. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  53869. the major axis direction). The target column in the table below explains how the major axis direction
  53870. maps to the 2D image of a particular cube map target.
  53871. major axis
  53872. direction target sc tc ma
  53873. ---------- --------------------------------- --- --- ---
  53874. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  53875. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  53876. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  53877. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  53878. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  53879. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  53880. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  53881. an updated (s,t) is calculated as follows
  53882. s = ( sc/|ma| + 1 ) / 2
  53883. t = ( tc/|ma| + 1 ) / 2
  53884. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  53885. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  53886. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  53887. */
  53888. // Note this method return U and V in range from 0 to size-1
  53889. // SL END
  53890. // Store the information in vector3 for convenience (faceindex, u, v)
  53891. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  53892. var maxCoord;
  53893. var faceIdx;
  53894. //absolute value 3
  53895. var absX = Math.abs(x);
  53896. var absY = Math.abs(y);
  53897. var absZ = Math.abs(z);
  53898. if (absX >= absY && absX >= absZ) {
  53899. maxCoord = absX;
  53900. if (x >= 0) {
  53901. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  53902. }
  53903. else {
  53904. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  53905. }
  53906. }
  53907. else if (absY >= absX && absY >= absZ) {
  53908. maxCoord = absY;
  53909. if (y >= 0) {
  53910. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  53911. }
  53912. else {
  53913. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  53914. }
  53915. }
  53916. else {
  53917. maxCoord = absZ;
  53918. if (z >= 0) {
  53919. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  53920. }
  53921. else {
  53922. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  53923. }
  53924. }
  53925. //divide through by max coord so face vector lies on cube face
  53926. var scale = 1 / maxCoord;
  53927. x *= scale;
  53928. y *= scale;
  53929. z *= scale;
  53930. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53931. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  53932. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53933. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  53934. // Modify original AMD code to return value from 0 to Size - 1
  53935. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  53936. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  53937. PMREMGenerator._vectorTemp.x = faceIdx;
  53938. PMREMGenerator._vectorTemp.y = u;
  53939. PMREMGenerator._vectorTemp.z = v;
  53940. return PMREMGenerator._vectorTemp;
  53941. };
  53942. //--------------------------------------------------------------------------------------
  53943. //Original code from Ignacio CastaÒo
  53944. // This formula is from Manne ÷hrstrˆm's thesis.
  53945. // Take two coordiantes in the range [-1, 1] that define a portion of a
  53946. // cube face and return the area of the projection of that portion on the
  53947. // surface of the sphere.
  53948. //--------------------------------------------------------------------------------------
  53949. PMREMGenerator.prototype.areaElement = function (x, y) {
  53950. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  53951. };
  53952. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  53953. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53954. // (+ 0.5f is for texel center addressing)
  53955. u = (2.0 * (u + 0.5) / size) - 1.0;
  53956. v = (2.0 * (v + 0.5) / size) - 1.0;
  53957. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  53958. var invResolution = 1.0 / size;
  53959. // U and V are the -1..1 texture coordinate on the current face.
  53960. // Get projected area for this texel
  53961. var x0 = u - invResolution;
  53962. var y0 = v - invResolution;
  53963. var x1 = u + invResolution;
  53964. var y1 = v + invResolution;
  53965. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  53966. return solidAngle;
  53967. };
  53968. //--------------------------------------------------------------------------------------
  53969. //The key to the speed of these filtering routines is to quickly define a per-face
  53970. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  53971. // Later these pixels are selectively processed based on their dot products to see if
  53972. // they reside within the filtering cone.
  53973. //
  53974. //This is done by computing the smallest per-texel angle to get a conservative estimate
  53975. // of the number of texels needed to be covered in width and height order to filter the
  53976. // region. the bounding box for the center taps face is defined first, and if the
  53977. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  53978. // defined next
  53979. //--------------------------------------------------------------------------------------
  53980. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  53981. // note that pixels within these regions may be rejected
  53982. // based on the anlge
  53983. var iCubeFace;
  53984. var u;
  53985. var v;
  53986. // bounding box per face to specify region to process
  53987. var filterExtents = [];
  53988. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53989. filterExtents.push(new CMGBoundinBox());
  53990. }
  53991. // min angle a src texel can cover (in degrees)
  53992. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  53993. // angle about center tap to define filter cone
  53994. // filter angle is 1/2 the cone angle
  53995. var filterAngle = filterConeAngle / 2.0;
  53996. //ensure filter angle is larger than a texel
  53997. if (filterAngle < srcTexelAngle) {
  53998. filterAngle = srcTexelAngle;
  53999. }
  54000. //ensure filter cone is always smaller than the hemisphere
  54001. if (filterAngle > 90.0) {
  54002. filterAngle = 90.0;
  54003. }
  54004. // the maximum number of texels in 1D the filter cone angle will cover
  54005. // used to determine bounding box size for filter extents
  54006. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  54007. // ensure conservative region always covers at least one texel
  54008. if (filterSize < 1) {
  54009. filterSize = 1;
  54010. }
  54011. // dotProdThresh threshold based on cone angle to determine whether or not taps
  54012. // reside within the cone angle
  54013. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  54014. // process required faces
  54015. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54016. //iterate over dst cube map face texel
  54017. for (v = 0; v < dstSize; v++) {
  54018. for (u = 0; u < dstSize; u++) {
  54019. //get center tap direction
  54020. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  54021. //clear old per-face filter extents
  54022. this.clearFilterExtents(filterExtents);
  54023. //define per-face filter extents
  54024. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  54025. //perform filtering of src faces using filter extents
  54026. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  54027. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  54028. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  54029. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  54030. }
  54031. }
  54032. }
  54033. };
  54034. //--------------------------------------------------------------------------------------
  54035. //Clear filter extents for the 6 cube map faces
  54036. //--------------------------------------------------------------------------------------
  54037. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  54038. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  54039. filterExtents[iCubeFaces].clear();
  54040. }
  54041. };
  54042. //--------------------------------------------------------------------------------------
  54043. //Define per-face bounding box filter extents
  54044. //
  54045. // These define conservative texel regions in each of the faces the filter can possibly
  54046. // process. When the pixels in the regions are actually processed, the dot product
  54047. // between the tap vector and the center tap vector is used to determine the weight of
  54048. // the tap and whether or not the tap is within the cone.
  54049. //
  54050. //--------------------------------------------------------------------------------------
  54051. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  54052. //neighboring face and bleed over amount, and width of BBOX for
  54053. // left, right, top, and bottom edges of this face
  54054. var bleedOverAmount = [0, 0, 0, 0];
  54055. var bleedOverBBoxMin = [0, 0, 0, 0];
  54056. var bleedOverBBoxMax = [0, 0, 0, 0];
  54057. var neighborFace;
  54058. var neighborEdge;
  54059. var oppositeFaceIdx;
  54060. //get face idx, and u, v info from center tap dir
  54061. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  54062. var faceIdx = result.x;
  54063. var u = result.y;
  54064. var v = result.z;
  54065. //define bbox size within face
  54066. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  54067. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  54068. filterExtents[faceIdx].clampMin(0, 0, 0);
  54069. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  54070. //u and v extent in face corresponding to center tap
  54071. var minU = filterExtents[faceIdx].min.x;
  54072. var minV = filterExtents[faceIdx].min.y;
  54073. var maxU = filterExtents[faceIdx].max.x;
  54074. var maxV = filterExtents[faceIdx].max.y;
  54075. //bleed over amounts for face across u=0 edge (left)
  54076. bleedOverAmount[0] = (bboxSize - u);
  54077. bleedOverBBoxMin[0] = minV;
  54078. bleedOverBBoxMax[0] = maxV;
  54079. //bleed over amounts for face across u=1 edge (right)
  54080. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  54081. bleedOverBBoxMin[1] = minV;
  54082. bleedOverBBoxMax[1] = maxV;
  54083. //bleed over to face across v=0 edge (up)
  54084. bleedOverAmount[2] = (bboxSize - v);
  54085. bleedOverBBoxMin[2] = minU;
  54086. bleedOverBBoxMax[2] = maxU;
  54087. //bleed over to face across v=1 edge (down)
  54088. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  54089. bleedOverBBoxMin[3] = minU;
  54090. bleedOverBBoxMax[3] = maxU;
  54091. //compute bleed over regions in neighboring faces
  54092. for (var i = 0; i < 4; i++) {
  54093. if (bleedOverAmount[i] > 0) {
  54094. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  54095. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  54096. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  54097. // be flipped: the cases are
  54098. // if a left edge mates with a left or bottom edge on the neighbor
  54099. // if a top edge mates with a top or right edge on the neighbor
  54100. // if a right edge mates with a right or top edge on the neighbor
  54101. // if a bottom edge mates with a bottom or left edge on the neighbor
  54102. //Seeing as the edges are enumerated as follows
  54103. // left =0
  54104. // right =1
  54105. // top =2
  54106. // bottom =3
  54107. //
  54108. // so if the edge enums are the same, or the sum of the enums == 3,
  54109. // the bbox needs to be flipped
  54110. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  54111. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  54112. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  54113. }
  54114. //The way the bounding box is extended onto the neighboring face
  54115. // depends on which edge of neighboring face abuts with this one
  54116. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  54117. case PMREMGenerator.CP_EDGE_LEFT:
  54118. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  54119. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54120. break;
  54121. case PMREMGenerator.CP_EDGE_RIGHT:
  54122. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  54123. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54124. break;
  54125. case PMREMGenerator.CP_EDGE_TOP:
  54126. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  54127. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  54128. break;
  54129. case PMREMGenerator.CP_EDGE_BOTTOM:
  54130. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  54131. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  54132. break;
  54133. }
  54134. //clamp filter extents in non-center tap faces to remain within surface
  54135. filterExtents[neighborFace].clampMin(0, 0, 0);
  54136. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  54137. }
  54138. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  54139. // from the center tap face, then process the opposite face entirely for now.
  54140. //Note that the cases in which this happens, what usually happens is that
  54141. // more than one edge bleeds onto the opposite face, and the bounding box
  54142. // encompasses the entire cube map face.
  54143. if (bleedOverAmount[i] > srcSize) {
  54144. //determine opposite face
  54145. switch (faceIdx) {
  54146. case PMREMGenerator.CP_FACE_X_POS:
  54147. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54148. break;
  54149. case PMREMGenerator.CP_FACE_X_NEG:
  54150. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  54151. break;
  54152. case PMREMGenerator.CP_FACE_Y_POS:
  54153. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54154. break;
  54155. case PMREMGenerator.CP_FACE_Y_NEG:
  54156. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54157. break;
  54158. case PMREMGenerator.CP_FACE_Z_POS:
  54159. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54160. break;
  54161. case PMREMGenerator.CP_FACE_Z_NEG:
  54162. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54163. break;
  54164. default:
  54165. break;
  54166. }
  54167. //just encompass entire face for now
  54168. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  54169. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  54170. }
  54171. }
  54172. };
  54173. //--------------------------------------------------------------------------------------
  54174. //ProcessFilterExtents
  54175. // Process bounding box in each cube face
  54176. //
  54177. //--------------------------------------------------------------------------------------
  54178. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  54179. //accumulators are 64-bit floats in order to have the precision needed
  54180. // over a summation of a large number of pixels
  54181. var dstAccum = [0, 0, 0, 0];
  54182. var weightAccum = 0;
  54183. var k = 0;
  54184. var nSrcChannels = this.numChannels;
  54185. // norm cube map and srcCubeMap have same face width
  54186. var faceWidth = srcSize;
  54187. //amount to add to pointer to move to next scanline in images
  54188. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  54189. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  54190. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  54191. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  54192. // iterate over cubefaces
  54193. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  54194. //if bbox is non empty
  54195. if (!filterExtents[iFaceIdx].empty()) {
  54196. var uStart = filterExtents[iFaceIdx].min.x;
  54197. var vStart = filterExtents[iFaceIdx].min.y;
  54198. var uEnd = filterExtents[iFaceIdx].max.x;
  54199. var vEnd = filterExtents[iFaceIdx].max.y;
  54200. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  54201. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  54202. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  54203. for (var v = vStart; v <= vEnd; v++) {
  54204. var normCubeRowWalk = 0;
  54205. var srcCubeRowWalk = 0;
  54206. for (var u = uStart; u <= uEnd; u++) {
  54207. //pointer to direction in cube map associated with texel
  54208. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  54209. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  54210. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  54211. //check dot product to see if texel is within cone
  54212. var tapDotProd = texelVectX * centerTapDir.x +
  54213. texelVectY * centerTapDir.y +
  54214. texelVectZ * centerTapDir.z;
  54215. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  54216. //solid angle stored in 4th channel of normalizer/solid angle cube map
  54217. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  54218. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  54219. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  54220. // so just adding one to specularpower do the trick.
  54221. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  54222. //iterate over channels
  54223. for (k = 0; k < nSrcChannels; k++) {
  54224. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  54225. srcCubeRowWalk++;
  54226. }
  54227. weightAccum += weight; //accumulate weight
  54228. }
  54229. else {
  54230. //step across source pixel
  54231. srcCubeRowWalk += nSrcChannels;
  54232. }
  54233. normCubeRowWalk += 4; // 4 channels per norm cube map.
  54234. }
  54235. startIndexNormCubeMap += normCubePitch;
  54236. startIndexSrcCubeMap += srcCubePitch;
  54237. }
  54238. }
  54239. }
  54240. //divide through by weights if weight is non zero
  54241. if (weightAccum != 0.0) {
  54242. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  54243. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  54244. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  54245. if (this.numChannels > 3) {
  54246. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  54247. }
  54248. }
  54249. else {
  54250. // otherwise sample nearest
  54251. // get face idx and u, v texel coordinate in face
  54252. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  54253. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  54254. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  54255. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  54256. if (this.numChannels > 3) {
  54257. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  54258. }
  54259. }
  54260. return PMREMGenerator._vectorTemp;
  54261. };
  54262. //--------------------------------------------------------------------------------------
  54263. // Fixup cube edges
  54264. //
  54265. // average texels on cube map faces across the edges
  54266. // WARP/BENT Method Only.
  54267. //--------------------------------------------------------------------------------------
  54268. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  54269. var k;
  54270. var j;
  54271. var i;
  54272. var iFace;
  54273. var iCorner = 0;
  54274. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  54275. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  54276. // note that if functionality to filter across the three texels for each corner, then
  54277. //indexed by corner and face idx. the array contains the face the start points belongs to.
  54278. var cornerPtr = [
  54279. [[], [], []],
  54280. [[], [], []],
  54281. [[], [], []],
  54282. [[], [], []],
  54283. [[], [], []],
  54284. [[], [], []],
  54285. [[], [], []],
  54286. [[], [], []]
  54287. ];
  54288. //if there is no fixup, or fixup width = 0, do nothing
  54289. if (cubeMapSize < 1) {
  54290. return;
  54291. }
  54292. //special case 1x1 cubemap, average face colors
  54293. if (cubeMapSize == 1) {
  54294. //iterate over channels
  54295. for (k = 0; k < this.numChannels; k++) {
  54296. var accum = 0.0;
  54297. //iterate over faces to accumulate face colors
  54298. for (iFace = 0; iFace < 6; iFace++) {
  54299. accum += cubeMap[iFace][k];
  54300. }
  54301. //compute average over 6 face colors
  54302. accum /= 6.0;
  54303. //iterate over faces to distribute face colors
  54304. for (iFace = 0; iFace < 6; iFace++) {
  54305. cubeMap[iFace][k] = accum;
  54306. }
  54307. }
  54308. return;
  54309. }
  54310. //iterate over faces to collect list of corner texel pointers
  54311. for (iFace = 0; iFace < 6; iFace++) {
  54312. //the 4 corner pointers for this face
  54313. faceCornerStartIndicies[0] = [iFace, 0];
  54314. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  54315. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  54316. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  54317. //iterate over face corners to collect cube corner pointers
  54318. for (iCorner = 0; iCorner < 4; iCorner++) {
  54319. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  54320. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  54321. cornerNumPtrs[corner]++;
  54322. }
  54323. }
  54324. //iterate over corners to average across corner tap values
  54325. for (iCorner = 0; iCorner < 8; iCorner++) {
  54326. for (k = 0; k < this.numChannels; k++) {
  54327. var cornerTapAccum = 0.0;
  54328. //iterate over corner texels and average results
  54329. for (i = 0; i < 3; i++) {
  54330. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  54331. }
  54332. //divide by 3 to compute average of corner tap values
  54333. cornerTapAccum *= (1.0 / 3.0);
  54334. //iterate over corner texels and average results
  54335. for (i = 0; i < 3; i++) {
  54336. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  54337. }
  54338. }
  54339. }
  54340. //iterate over the twelve edges of the cube to average across edges
  54341. for (i = 0; i < 12; i++) {
  54342. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  54343. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  54344. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  54345. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  54346. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  54347. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  54348. var edgeWalk = 0;
  54349. var neighborEdgeWalk = 0;
  54350. //Determine walking pointers based on edge type
  54351. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  54352. switch (edge) {
  54353. case PMREMGenerator.CP_EDGE_LEFT:
  54354. // no change to faceEdgeStartPtr
  54355. edgeWalk = this.numChannels * cubeMapSize;
  54356. break;
  54357. case PMREMGenerator.CP_EDGE_RIGHT:
  54358. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54359. edgeWalk = this.numChannels * cubeMapSize;
  54360. break;
  54361. case PMREMGenerator.CP_EDGE_TOP:
  54362. // no change to faceEdgeStartPtr
  54363. edgeWalk = this.numChannels;
  54364. break;
  54365. case PMREMGenerator.CP_EDGE_BOTTOM:
  54366. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54367. edgeWalk = this.numChannels;
  54368. break;
  54369. }
  54370. //For certain types of edge abutments, the neighbor edge walk needs to
  54371. // be flipped: the cases are
  54372. // if a left edge mates with a left or bottom edge on the neighbor
  54373. // if a top edge mates with a top or right edge on the neighbor
  54374. // if a right edge mates with a right or top edge on the neighbor
  54375. // if a bottom edge mates with a bottom or left edge on the neighbor
  54376. //Seeing as the edges are enumerated as follows
  54377. // left =0
  54378. // right =1
  54379. // top =2
  54380. // bottom =3
  54381. //
  54382. //If the edge enums are the same, or the sum of the enums == 3,
  54383. // the neighbor edge walk needs to be flipped
  54384. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  54385. switch (neighborEdge) {
  54386. case PMREMGenerator.CP_EDGE_LEFT:
  54387. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  54388. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54389. break;
  54390. case PMREMGenerator.CP_EDGE_RIGHT:
  54391. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54392. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54393. break;
  54394. case PMREMGenerator.CP_EDGE_TOP:
  54395. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54396. neighborEdgeWalk = -this.numChannels;
  54397. break;
  54398. case PMREMGenerator.CP_EDGE_BOTTOM:
  54399. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54400. neighborEdgeWalk = -this.numChannels;
  54401. break;
  54402. }
  54403. }
  54404. else {
  54405. //swapped direction neighbor edge walk
  54406. switch (neighborEdge) {
  54407. case PMREMGenerator.CP_EDGE_LEFT:
  54408. //no change to neighborEdgeStartPtr for this case since it points
  54409. // to the upper left corner already
  54410. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54411. break;
  54412. case PMREMGenerator.CP_EDGE_RIGHT:
  54413. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54414. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54415. break;
  54416. case PMREMGenerator.CP_EDGE_TOP:
  54417. //no change to neighborEdgeStartPtr for this case since it points
  54418. // to the upper left corner already
  54419. neighborEdgeWalk = this.numChannels;
  54420. break;
  54421. case PMREMGenerator.CP_EDGE_BOTTOM:
  54422. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54423. neighborEdgeWalk = this.numChannels;
  54424. break;
  54425. }
  54426. }
  54427. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  54428. //nearby neighborhood
  54429. //step ahead one texel on edge
  54430. edgeStartIndex += edgeWalk;
  54431. neighborEdgeStartIndex += neighborEdgeWalk;
  54432. // note that this loop does not process the corner texels, since they have already been
  54433. // averaged across faces across earlier
  54434. for (j = 1; j < (cubeMapSize - 1); j++) {
  54435. //for each set of taps along edge, average them
  54436. // and rewrite the results into the edges
  54437. for (k = 0; k < this.numChannels; k++) {
  54438. var edgeTap = cubeMap[face][edgeStartIndex + k];
  54439. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  54440. //compute average of tap intensity values
  54441. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  54442. //propagate average of taps to edge taps
  54443. cubeMap[face][edgeStartIndex + k] = avgTap;
  54444. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  54445. }
  54446. edgeStartIndex += edgeWalk;
  54447. neighborEdgeStartIndex += neighborEdgeWalk;
  54448. }
  54449. }
  54450. };
  54451. return PMREMGenerator;
  54452. }());
  54453. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  54454. PMREMGenerator.CP_UDIR = 0;
  54455. PMREMGenerator.CP_VDIR = 1;
  54456. PMREMGenerator.CP_FACEAXIS = 2;
  54457. //used to index cube faces
  54458. PMREMGenerator.CP_FACE_X_POS = 0;
  54459. PMREMGenerator.CP_FACE_X_NEG = 1;
  54460. PMREMGenerator.CP_FACE_Y_POS = 2;
  54461. PMREMGenerator.CP_FACE_Y_NEG = 3;
  54462. PMREMGenerator.CP_FACE_Z_POS = 4;
  54463. PMREMGenerator.CP_FACE_Z_NEG = 5;
  54464. //used to index image edges
  54465. // NOTE.. the actual number corresponding to the edge is important
  54466. // do not change these, or the code will break
  54467. //
  54468. // CP_EDGE_LEFT is u = 0
  54469. // CP_EDGE_RIGHT is u = width-1
  54470. // CP_EDGE_TOP is v = 0
  54471. // CP_EDGE_BOTTOM is v = height-1
  54472. PMREMGenerator.CP_EDGE_LEFT = 0;
  54473. PMREMGenerator.CP_EDGE_RIGHT = 1;
  54474. PMREMGenerator.CP_EDGE_TOP = 2;
  54475. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  54476. //corners of CUBE map (P or N specifys if it corresponds to the
  54477. // positive or negative direction each of X, Y, and Z
  54478. PMREMGenerator.CP_CORNER_NNN = 0;
  54479. PMREMGenerator.CP_CORNER_NNP = 1;
  54480. PMREMGenerator.CP_CORNER_NPN = 2;
  54481. PMREMGenerator.CP_CORNER_NPP = 3;
  54482. PMREMGenerator.CP_CORNER_PNN = 4;
  54483. PMREMGenerator.CP_CORNER_PNP = 5;
  54484. PMREMGenerator.CP_CORNER_PPN = 6;
  54485. PMREMGenerator.CP_CORNER_PPP = 7;
  54486. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  54487. //3x2 matrices that map cube map indexing vectors in 3d
  54488. // (after face selection and divide through by the
  54489. // _ABSOLUTE VALUE_ of the max coord)
  54490. // into NVC space
  54491. //Note this currently assumes the D3D cube face ordering and orientation
  54492. PMREMGenerator._sgFace2DMapping = [
  54493. //XPOS face
  54494. [[0, 0, -1],
  54495. [0, -1, 0],
  54496. [1, 0, 0]],
  54497. //XNEG face
  54498. [[0, 0, 1],
  54499. [0, -1, 0],
  54500. [-1, 0, 0]],
  54501. //YPOS face
  54502. [[1, 0, 0],
  54503. [0, 0, 1],
  54504. [0, 1, 0]],
  54505. //YNEG face
  54506. [[1, 0, 0],
  54507. [0, 0, -1],
  54508. [0, -1, 0]],
  54509. //ZPOS face
  54510. [[1, 0, 0],
  54511. [0, -1, 0],
  54512. [0, 0, 1]],
  54513. //ZNEG face
  54514. [[-1, 0, 0],
  54515. [0, -1, 0],
  54516. [0, 0, -1]],
  54517. ];
  54518. //------------------------------------------------------------------------------
  54519. // D3D cube map face specification
  54520. // mapping from 3D x,y,z cube map lookup coordinates
  54521. // to 2D within face u,v coordinates
  54522. //
  54523. // --------------------> U direction
  54524. // | (within-face texture space)
  54525. // | _____
  54526. // | | |
  54527. // | | +Y |
  54528. // | _____|_____|_____ _____
  54529. // | | | | | |
  54530. // | | -X | +Z | +X | -Z |
  54531. // | |_____|_____|_____|_____|
  54532. // | | |
  54533. // | | -Y |
  54534. // | |_____|
  54535. // |
  54536. // v V direction
  54537. // (within-face texture space)
  54538. //------------------------------------------------------------------------------
  54539. //Information about neighbors and how texture coorrdinates change across faces
  54540. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  54541. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  54542. //Note this currently assumes the D3D cube face ordering and orientation
  54543. PMREMGenerator._sgCubeNgh = [
  54544. //XPOS face
  54545. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54546. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54547. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54548. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  54549. //XNEG face
  54550. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54551. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  54552. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  54553. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  54554. //YPOS face
  54555. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54556. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54557. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54558. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  54559. //YNEG face
  54560. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54561. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54562. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54563. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  54564. //ZPOS face
  54565. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54566. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54567. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54568. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  54569. //ZNEG face
  54570. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54571. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54572. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  54573. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  54574. ];
  54575. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  54576. // this table is used to average over the edges.
  54577. PMREMGenerator._sgCubeEdgeList = [
  54578. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54579. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54580. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54581. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54582. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54583. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54584. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54585. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54586. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  54587. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54588. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54589. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  54590. ];
  54591. //Information about which of the 8 cube corners are correspond to the
  54592. // the 4 corners in each cube face
  54593. // the order is upper left, upper right, lower left, lower right
  54594. PMREMGenerator._sgCubeCornerList = [
  54595. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  54596. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  54597. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  54598. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  54599. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  54600. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  54601. ];
  54602. Internals.PMREMGenerator = PMREMGenerator;
  54603. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54604. })(BABYLON || (BABYLON = {}));
  54605. //# sourceMappingURL=babylon.pmremgenerator.js.map
  54606. var BABYLON;
  54607. (function (BABYLON) {
  54608. /**
  54609. * This represents a texture coming from an HDR input.
  54610. *
  54611. * The only supported format is currently panorama picture stored in RGBE format.
  54612. * Example of such files can be found on HDRLib: http://hdrlib.com/
  54613. */
  54614. var HDRCubeTexture = (function (_super) {
  54615. __extends(HDRCubeTexture, _super);
  54616. /**
  54617. * Instantiates an HDRTexture from the following parameters.
  54618. *
  54619. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  54620. * @param scene The scene the texture will be used in
  54621. * @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.
  54622. * @param noMipmap Forces to not generate the mipmap if true
  54623. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  54624. * @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)
  54625. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  54626. */
  54627. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  54628. if (noMipmap === void 0) { noMipmap = false; }
  54629. if (generateHarmonics === void 0) { generateHarmonics = true; }
  54630. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  54631. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  54632. if (onLoad === void 0) { onLoad = null; }
  54633. if (onError === void 0) { onError = null; }
  54634. var _this = _super.call(this, scene) || this;
  54635. _this._useInGammaSpace = false;
  54636. _this._generateHarmonics = true;
  54637. _this._isBABYLONPreprocessed = false;
  54638. _this._onLoad = null;
  54639. _this._onError = null;
  54640. /**
  54641. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  54642. */
  54643. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54644. /**
  54645. * The spherical polynomial data extracted from the texture.
  54646. */
  54647. _this.sphericalPolynomial = null;
  54648. /**
  54649. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  54650. * This is usefull at run time to apply the good shader.
  54651. */
  54652. _this.isPMREM = false;
  54653. _this._isBlocking = true;
  54654. if (!url) {
  54655. return _this;
  54656. }
  54657. _this.name = url;
  54658. _this.url = url;
  54659. _this.hasAlpha = false;
  54660. _this.isCube = true;
  54661. _this._textureMatrix = BABYLON.Matrix.Identity();
  54662. _this._onLoad = onLoad;
  54663. _this._onError = onError;
  54664. if (size) {
  54665. _this._isBABYLONPreprocessed = false;
  54666. _this._noMipmap = noMipmap;
  54667. _this._size = size;
  54668. _this._useInGammaSpace = useInGammaSpace;
  54669. _this._usePMREMGenerator = usePMREMGenerator &&
  54670. scene.getEngine().getCaps().textureLOD &&
  54671. _this.getScene().getEngine().getCaps().textureFloat &&
  54672. !_this._useInGammaSpace;
  54673. }
  54674. else {
  54675. _this._isBABYLONPreprocessed = true;
  54676. _this._noMipmap = false;
  54677. _this._useInGammaSpace = false;
  54678. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  54679. _this.getScene().getEngine().getCaps().textureFloat &&
  54680. !_this._useInGammaSpace;
  54681. }
  54682. _this.isPMREM = _this._usePMREMGenerator;
  54683. _this._texture = _this._getFromCache(url, _this._noMipmap);
  54684. if (!_this._texture) {
  54685. if (!scene.useDelayedTextureLoading) {
  54686. _this.loadTexture();
  54687. }
  54688. else {
  54689. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54690. }
  54691. }
  54692. return _this;
  54693. }
  54694. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  54695. /**
  54696. * Gets wether or not the texture is blocking during loading.
  54697. */
  54698. get: function () {
  54699. return this._isBlocking;
  54700. },
  54701. /**
  54702. * Sets wether or not the texture is blocking during loading.
  54703. */
  54704. set: function (value) {
  54705. this._isBlocking = value;
  54706. },
  54707. enumerable: true,
  54708. configurable: true
  54709. });
  54710. /**
  54711. * Occurs when the file is a preprocessed .babylon.hdr file.
  54712. */
  54713. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  54714. var _this = this;
  54715. var mipLevels = 0;
  54716. var floatArrayView = null;
  54717. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  54718. var mips = [];
  54719. var startIndex = 30;
  54720. for (var level = 0; level < mipLevels; level++) {
  54721. mips.push([]);
  54722. // Fill each pixel of the mip level.
  54723. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  54724. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54725. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  54726. mips[level].push(faceData);
  54727. startIndex += faceSize;
  54728. }
  54729. }
  54730. return mips;
  54731. } : null;
  54732. var callback = function (buffer) {
  54733. // Create Native Array Views
  54734. var intArrayView = new Int32Array(buffer);
  54735. floatArrayView = new Float32Array(buffer);
  54736. // Fill header.
  54737. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  54738. _this._size = intArrayView[1]; // CubeMap max mip face size.
  54739. // Update Texture Information.
  54740. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  54741. // Fill polynomial information.
  54742. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  54743. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  54744. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  54745. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  54746. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  54747. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  54748. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  54749. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  54750. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  54751. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  54752. // Fill pixel data.
  54753. mipLevels = intArrayView[29]; // Number of mip levels.
  54754. var startIndex = 30;
  54755. var data = [];
  54756. var faceSize = Math.pow(_this._size, 2) * 3;
  54757. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54758. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  54759. startIndex += faceSize;
  54760. }
  54761. var results = [];
  54762. var byteArray = null;
  54763. // Push each faces.
  54764. for (var k = 0; k < 6; k++) {
  54765. var dataFace = null;
  54766. // If special cases.
  54767. if (!mipmapGenerator) {
  54768. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  54769. dataFace = data[j];
  54770. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54771. // 3 channels of 1 bytes per pixel in bytes.
  54772. var byteBuffer = new ArrayBuffer(faceSize);
  54773. byteArray = new Uint8Array(byteBuffer);
  54774. }
  54775. for (var i = 0; i < _this._size * _this._size; i++) {
  54776. // Put in gamma space if requested.
  54777. if (_this._useInGammaSpace) {
  54778. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54779. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54780. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54781. }
  54782. // Convert to int texture for fallback.
  54783. if (byteArray) {
  54784. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54785. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54786. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54787. // May use luminance instead if the result is not accurate.
  54788. var max = Math.max(Math.max(r, g), b);
  54789. if (max > 255) {
  54790. var scale = 255 / max;
  54791. r *= scale;
  54792. g *= scale;
  54793. b *= scale;
  54794. }
  54795. byteArray[(i * 3) + 0] = r;
  54796. byteArray[(i * 3) + 1] = g;
  54797. byteArray[(i * 3) + 2] = b;
  54798. }
  54799. }
  54800. }
  54801. else {
  54802. dataFace = data[k];
  54803. }
  54804. // Fill the array accordingly.
  54805. if (byteArray) {
  54806. results.push(byteArray);
  54807. }
  54808. else {
  54809. results.push(dataFace);
  54810. }
  54811. }
  54812. return results;
  54813. };
  54814. 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);
  54815. };
  54816. /**
  54817. * Occurs when the file is raw .hdr file.
  54818. */
  54819. HDRCubeTexture.prototype.loadHDRTexture = function () {
  54820. var _this = this;
  54821. var callback = function (buffer) {
  54822. // Extract the raw linear data.
  54823. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  54824. // Generate harmonics if needed.
  54825. if (_this._generateHarmonics) {
  54826. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  54827. }
  54828. var results = [];
  54829. var byteArray = null;
  54830. // Push each faces.
  54831. for (var j = 0; j < 6; j++) {
  54832. // Create uintarray fallback.
  54833. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54834. // 3 channels of 1 bytes per pixel in bytes.
  54835. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  54836. byteArray = new Uint8Array(byteBuffer);
  54837. }
  54838. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  54839. // If special cases.
  54840. if (_this._useInGammaSpace || byteArray) {
  54841. for (var i = 0; i < _this._size * _this._size; i++) {
  54842. // Put in gamma space if requested.
  54843. if (_this._useInGammaSpace) {
  54844. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54845. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54846. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54847. }
  54848. // Convert to int texture for fallback.
  54849. if (byteArray) {
  54850. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54851. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54852. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54853. // May use luminance instead if the result is not accurate.
  54854. var max = Math.max(Math.max(r, g), b);
  54855. if (max > 255) {
  54856. var scale = 255 / max;
  54857. r *= scale;
  54858. g *= scale;
  54859. b *= scale;
  54860. }
  54861. byteArray[(i * 3) + 0] = r;
  54862. byteArray[(i * 3) + 1] = g;
  54863. byteArray[(i * 3) + 2] = b;
  54864. }
  54865. }
  54866. }
  54867. if (byteArray) {
  54868. results.push(byteArray);
  54869. }
  54870. else {
  54871. results.push(dataFace);
  54872. }
  54873. }
  54874. return results;
  54875. };
  54876. var mipmapGenerator = null;
  54877. if (!this._noMipmap &&
  54878. this._usePMREMGenerator) {
  54879. mipmapGenerator = function (data) {
  54880. // Custom setup of the generator matching with the PBR shader values.
  54881. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  54882. return generator.filterCubeMap();
  54883. };
  54884. }
  54885. 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);
  54886. };
  54887. /**
  54888. * Starts the loading process of the texture.
  54889. */
  54890. HDRCubeTexture.prototype.loadTexture = function () {
  54891. if (this._isBABYLONPreprocessed) {
  54892. this.loadBabylonTexture();
  54893. }
  54894. else {
  54895. this.loadHDRTexture();
  54896. }
  54897. };
  54898. HDRCubeTexture.prototype.clone = function () {
  54899. var size = this._isBABYLONPreprocessed ? null : this._size;
  54900. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  54901. // Base texture
  54902. newTexture.level = this.level;
  54903. newTexture.wrapU = this.wrapU;
  54904. newTexture.wrapV = this.wrapV;
  54905. newTexture.coordinatesIndex = this.coordinatesIndex;
  54906. newTexture.coordinatesMode = this.coordinatesMode;
  54907. return newTexture;
  54908. };
  54909. // Methods
  54910. HDRCubeTexture.prototype.delayLoad = function () {
  54911. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54912. return;
  54913. }
  54914. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54915. this._texture = this._getFromCache(this.url, this._noMipmap);
  54916. if (!this._texture) {
  54917. this.loadTexture();
  54918. }
  54919. };
  54920. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  54921. return this._textureMatrix;
  54922. };
  54923. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54924. var texture = null;
  54925. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  54926. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  54927. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  54928. texture.name = parsedTexture.name;
  54929. texture.hasAlpha = parsedTexture.hasAlpha;
  54930. texture.level = parsedTexture.level;
  54931. texture.coordinatesMode = parsedTexture.coordinatesMode;
  54932. texture.isBlocking = parsedTexture.isBlocking;
  54933. }
  54934. return texture;
  54935. };
  54936. HDRCubeTexture.prototype.serialize = function () {
  54937. if (!this.name) {
  54938. return null;
  54939. }
  54940. var serializationObject = {};
  54941. serializationObject.name = this.name;
  54942. serializationObject.hasAlpha = this.hasAlpha;
  54943. serializationObject.isCube = true;
  54944. serializationObject.level = this.level;
  54945. serializationObject.size = this._size;
  54946. serializationObject.coordinatesMode = this.coordinatesMode;
  54947. serializationObject.useInGammaSpace = this._useInGammaSpace;
  54948. serializationObject.generateHarmonics = this._generateHarmonics;
  54949. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  54950. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  54951. serializationObject.customType = "BABYLON.HDRCubeTexture";
  54952. serializationObject.noMipmap = this._noMipmap;
  54953. serializationObject.isBlocking = this._isBlocking;
  54954. return serializationObject;
  54955. };
  54956. /**
  54957. * Saves as a file the data contained in the texture in a binary format.
  54958. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  54959. * as the spherical used in the lighting.
  54960. * @param url The HDR file url.
  54961. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  54962. * @param onError Method called if any error happens during download.
  54963. * @return The packed binary data.
  54964. */
  54965. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  54966. if (onError === void 0) { onError = null; }
  54967. var callback = function (buffer) {
  54968. var data = new Blob([buffer], { type: 'application/octet-stream' });
  54969. // Returns a URL you can use as a href.
  54970. var objUrl = window.URL.createObjectURL(data);
  54971. // Simulates a link to it and click to dowload.
  54972. var a = document.createElement("a");
  54973. document.body.appendChild(a);
  54974. a.style.display = "none";
  54975. a.href = objUrl;
  54976. a.download = "envmap.babylon.hdr";
  54977. a.click();
  54978. };
  54979. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  54980. };
  54981. /**
  54982. * Serializes the data contained in the texture in a binary format.
  54983. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  54984. * as the spherical used in the lighting.
  54985. * @param url The HDR file url.
  54986. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  54987. * @param onError Method called if any error happens during download.
  54988. * @return The packed binary data.
  54989. */
  54990. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  54991. if (onError === void 0) { onError = null; }
  54992. // Needs the url tho create the texture.
  54993. if (!url) {
  54994. return null;
  54995. }
  54996. // Check Power of two size.
  54997. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  54998. return null;
  54999. }
  55000. var getDataCallback = function (dataBuffer) {
  55001. // Extract the raw linear data.
  55002. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  55003. // Generate harmonics if needed.
  55004. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  55005. // Generate seamless faces
  55006. var mipGeneratorArray = [];
  55007. // Data are known to be in +X +Y +Z -X -Y -Z
  55008. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  55009. mipGeneratorArray.push(cubeData.right); // +X
  55010. mipGeneratorArray.push(cubeData.left); // -X
  55011. mipGeneratorArray.push(cubeData.up); // +Y
  55012. mipGeneratorArray.push(cubeData.down); // -Y
  55013. mipGeneratorArray.push(cubeData.front); // +Z
  55014. mipGeneratorArray.push(cubeData.back); // -Z
  55015. // Custom setup of the generator matching with the PBR shader values.
  55016. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  55017. var mippedData = generator.filterCubeMap();
  55018. // Compute required byte length.
  55019. var byteLength = 1 * 4; // Raw Data Version int32.
  55020. byteLength += 4; // CubeMap max mip face size int32.
  55021. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  55022. // Add data size.
  55023. byteLength += 4; // Number of mip levels int32.
  55024. for (var level = 0; level < mippedData.length; level++) {
  55025. var mipSize = size >> level;
  55026. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  55027. }
  55028. // Prepare binary structure.
  55029. var buffer = new ArrayBuffer(byteLength);
  55030. var intArrayView = new Int32Array(buffer);
  55031. var floatArrayView = new Float32Array(buffer);
  55032. // Fill header.
  55033. intArrayView[0] = 1; // Version 1.
  55034. intArrayView[1] = size; // CubeMap max mip face size.
  55035. // Fill polynomial information.
  55036. sphericalPolynomial.x.toArray(floatArrayView, 2);
  55037. sphericalPolynomial.y.toArray(floatArrayView, 5);
  55038. sphericalPolynomial.z.toArray(floatArrayView, 8);
  55039. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  55040. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  55041. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  55042. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  55043. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  55044. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  55045. // Fill pixel data.
  55046. intArrayView[29] = mippedData.length; // Number of mip levels.
  55047. var startIndex = 30;
  55048. for (var level = 0; level < mippedData.length; level++) {
  55049. // Fill each pixel of the mip level.
  55050. var faceSize = Math.pow(size >> level, 2) * 3;
  55051. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55052. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  55053. startIndex += faceSize;
  55054. }
  55055. }
  55056. // Callback.
  55057. callback(buffer);
  55058. };
  55059. // Download and process.
  55060. BABYLON.Tools.LoadFile(url, function (data) {
  55061. getDataCallback(data);
  55062. }, null, null, true, onError);
  55063. };
  55064. return HDRCubeTexture;
  55065. }(BABYLON.BaseTexture));
  55066. HDRCubeTexture._facesMapping = [
  55067. "right",
  55068. "up",
  55069. "front",
  55070. "left",
  55071. "down",
  55072. "back"
  55073. ];
  55074. BABYLON.HDRCubeTexture = HDRCubeTexture;
  55075. })(BABYLON || (BABYLON = {}));
  55076. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  55077. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  55078. // Huge respect for a such great lib.
  55079. // Earcut license:
  55080. // Copyright (c) 2016, Mapbox
  55081. //
  55082. // Permission to use, copy, modify, and/or distribute this software for any purpose
  55083. // with or without fee is hereby granted, provided that the above copyright notice
  55084. // and this permission notice appear in all copies.
  55085. //
  55086. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  55087. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  55088. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  55089. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  55090. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  55091. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  55092. // THIS SOFTWARE.
  55093. var Earcut;
  55094. (function (Earcut) {
  55095. /**
  55096. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  55097. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  55098. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  55099. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  55100. */
  55101. function earcut(data, holeIndices, dim) {
  55102. dim = dim || 2;
  55103. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  55104. if (!outerNode)
  55105. return triangles;
  55106. var minX, minY, maxX, maxY, x, y, size;
  55107. if (hasHoles)
  55108. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  55109. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  55110. if (data.length > 80 * dim) {
  55111. minX = maxX = data[0];
  55112. minY = maxY = data[1];
  55113. for (var i = dim; i < outerLen; i += dim) {
  55114. x = data[i];
  55115. y = data[i + 1];
  55116. if (x < minX)
  55117. minX = x;
  55118. if (y < minY)
  55119. minY = y;
  55120. if (x > maxX)
  55121. maxX = x;
  55122. if (y > maxY)
  55123. maxY = y;
  55124. }
  55125. // minX, minY and size are later used to transform coords into integers for z-order calculation
  55126. size = Math.max(maxX - minX, maxY - minY);
  55127. }
  55128. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  55129. return triangles;
  55130. }
  55131. Earcut.earcut = earcut;
  55132. // create a circular doubly linked list from polygon points in the specified winding order
  55133. function linkedList(data, start, end, dim, clockwise) {
  55134. var i, last;
  55135. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  55136. for (i = start; i < end; i += dim)
  55137. last = insertNode(i, data[i], data[i + 1], last);
  55138. }
  55139. else {
  55140. for (i = end - dim; i >= start; i -= dim)
  55141. last = insertNode(i, data[i], data[i + 1], last);
  55142. }
  55143. if (last && equals(last, last.next)) {
  55144. removeNode(last);
  55145. last = last.next;
  55146. }
  55147. return last;
  55148. }
  55149. // eliminate colinear or duplicate points
  55150. function filterPoints(start, end) {
  55151. if (!start)
  55152. return start;
  55153. if (!end)
  55154. end = start;
  55155. var p = start, again;
  55156. do {
  55157. again = false;
  55158. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  55159. removeNode(p);
  55160. p = end = p.prev;
  55161. if (p === p.next)
  55162. return null;
  55163. again = true;
  55164. }
  55165. else {
  55166. p = p.next;
  55167. }
  55168. } while (again || p !== end);
  55169. return end;
  55170. }
  55171. // main ear slicing loop which triangulates a polygon (given as a linked list)
  55172. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  55173. if (!ear)
  55174. return;
  55175. // interlink polygon nodes in z-order
  55176. if (!pass && size)
  55177. indexCurve(ear, minX, minY, size);
  55178. var stop = ear, prev, next;
  55179. // iterate through ears, slicing them one by one
  55180. while (ear.prev !== ear.next) {
  55181. prev = ear.prev;
  55182. next = ear.next;
  55183. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  55184. // cut off the triangle
  55185. triangles.push(prev.i / dim);
  55186. triangles.push(ear.i / dim);
  55187. triangles.push(next.i / dim);
  55188. removeNode(ear);
  55189. // skipping the next vertice leads to less sliver triangles
  55190. ear = next.next;
  55191. stop = next.next;
  55192. continue;
  55193. }
  55194. ear = next;
  55195. // if we looped through the whole remaining polygon and can't find any more ears
  55196. if (ear === stop) {
  55197. // try filtering points and slicing again
  55198. if (!pass) {
  55199. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  55200. // if this didn't work, try curing all small self-intersections locally
  55201. }
  55202. else if (pass === 1) {
  55203. ear = cureLocalIntersections(ear, triangles, dim);
  55204. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  55205. // as a last resort, try splitting the remaining polygon into two
  55206. }
  55207. else if (pass === 2) {
  55208. splitEarcut(ear, triangles, dim, minX, minY, size);
  55209. }
  55210. break;
  55211. }
  55212. }
  55213. }
  55214. // check whether a polygon node forms a valid ear with adjacent nodes
  55215. function isEar(ear) {
  55216. var a = ear.prev, b = ear, c = ear.next;
  55217. if (area(a, b, c) >= 0)
  55218. return false; // reflex, can't be an ear
  55219. // now make sure we don't have other points inside the potential ear
  55220. var p = ear.next.next;
  55221. while (p !== ear.prev) {
  55222. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55223. area(p.prev, p, p.next) >= 0)
  55224. return false;
  55225. p = p.next;
  55226. }
  55227. return true;
  55228. }
  55229. function isEarHashed(ear, minX, minY, size) {
  55230. var a = ear.prev, b = ear, c = ear.next;
  55231. if (area(a, b, c) >= 0)
  55232. return false; // reflex, can't be an ear
  55233. // triangle bbox; min & max are calculated like this for speed
  55234. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  55235. // z-order range for the current triangle bbox;
  55236. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  55237. // first look for points inside the triangle in increasing z-order
  55238. var p = ear.nextZ;
  55239. while (p && p.z <= maxZ) {
  55240. if (p !== ear.prev &&
  55241. p !== ear.next &&
  55242. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55243. area(p.prev, p, p.next) >= 0)
  55244. return false;
  55245. p = p.nextZ;
  55246. }
  55247. // then look for points in decreasing z-order
  55248. p = ear.prevZ;
  55249. while (p && p.z >= minZ) {
  55250. if (p !== ear.prev &&
  55251. p !== ear.next &&
  55252. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55253. area(p.prev, p, p.next) >= 0)
  55254. return false;
  55255. p = p.prevZ;
  55256. }
  55257. return true;
  55258. }
  55259. // go through all polygon nodes and cure small local self-intersections
  55260. function cureLocalIntersections(start, triangles, dim) {
  55261. var p = start;
  55262. do {
  55263. var a = p.prev, b = p.next.next;
  55264. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  55265. triangles.push(a.i / dim);
  55266. triangles.push(p.i / dim);
  55267. triangles.push(b.i / dim);
  55268. // remove two nodes involved
  55269. removeNode(p);
  55270. removeNode(p.next);
  55271. p = start = b;
  55272. }
  55273. p = p.next;
  55274. } while (p !== start);
  55275. return p;
  55276. }
  55277. // try splitting polygon into two and triangulate them independently
  55278. function splitEarcut(start, triangles, dim, minX, minY, size) {
  55279. // look for a valid diagonal that divides the polygon into two
  55280. var a = start;
  55281. do {
  55282. var b = a.next.next;
  55283. while (b !== a.prev) {
  55284. if (a.i !== b.i && isValidDiagonal(a, b)) {
  55285. // split the polygon in two by the diagonal
  55286. var c = splitPolygon(a, b);
  55287. // filter colinear points around the cuts
  55288. a = filterPoints(a, a.next);
  55289. c = filterPoints(c, c.next);
  55290. // run earcut on each half
  55291. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  55292. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  55293. return;
  55294. }
  55295. b = b.next;
  55296. }
  55297. a = a.next;
  55298. } while (a !== start);
  55299. }
  55300. // link every hole into the outer loop, producing a single-ring polygon without holes
  55301. function eliminateHoles(data, holeIndices, outerNode, dim) {
  55302. var queue = [], i, len, start, end, list;
  55303. for (i = 0, len = holeIndices.length; i < len; i++) {
  55304. start = holeIndices[i] * dim;
  55305. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  55306. list = linkedList(data, start, end, dim, false);
  55307. if (list === list.next)
  55308. list.steiner = true;
  55309. queue.push(getLeftmost(list));
  55310. }
  55311. queue.sort(compareX);
  55312. // process holes from left to right
  55313. for (i = 0; i < queue.length; i++) {
  55314. eliminateHole(queue[i], outerNode);
  55315. outerNode = filterPoints(outerNode, outerNode.next);
  55316. }
  55317. return outerNode;
  55318. }
  55319. function compareX(a, b) {
  55320. return a.x - b.x;
  55321. }
  55322. // find a bridge between vertices that connects hole with an outer ring and and link it
  55323. function eliminateHole(hole, outerNode) {
  55324. outerNode = findHoleBridge(hole, outerNode);
  55325. if (outerNode) {
  55326. var b = splitPolygon(outerNode, hole);
  55327. filterPoints(b, b.next);
  55328. }
  55329. }
  55330. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  55331. function findHoleBridge(hole, outerNode) {
  55332. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  55333. // find a segment intersected by a ray from the hole's leftmost point to the left;
  55334. // segment's endpoint with lesser x will be potential connection point
  55335. do {
  55336. if (hy <= p.y && hy >= p.next.y) {
  55337. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  55338. if (x <= hx && x > qx) {
  55339. qx = x;
  55340. if (x === hx) {
  55341. if (hy === p.y)
  55342. return p;
  55343. if (hy === p.next.y)
  55344. return p.next;
  55345. }
  55346. m = p.x < p.next.x ? p : p.next;
  55347. }
  55348. }
  55349. p = p.next;
  55350. } while (p !== outerNode);
  55351. if (!m)
  55352. return null;
  55353. if (hx === qx)
  55354. return m.prev; // hole touches outer segment; pick lower endpoint
  55355. // look for points inside the triangle of hole point, segment intersection and endpoint;
  55356. // if there are no points found, we have a valid connection;
  55357. // otherwise choose the point of the minimum angle with the ray as connection point
  55358. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  55359. p = m.next;
  55360. while (p !== stop) {
  55361. if (hx >= p.x &&
  55362. p.x >= mx &&
  55363. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  55364. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  55365. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  55366. m = p;
  55367. tanMin = tan;
  55368. }
  55369. }
  55370. p = p.next;
  55371. }
  55372. return m;
  55373. }
  55374. // interlink polygon nodes in z-order
  55375. function indexCurve(start, minX, minY, size) {
  55376. var p = start;
  55377. do {
  55378. if (p.z === null)
  55379. p.z = zOrder(p.x, p.y, minX, minY, size);
  55380. p.prevZ = p.prev;
  55381. p.nextZ = p.next;
  55382. p = p.next;
  55383. } while (p !== start);
  55384. p.prevZ.nextZ = null;
  55385. p.prevZ = null;
  55386. sortLinked(p);
  55387. }
  55388. // Simon Tatham's linked list merge sort algorithm
  55389. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  55390. function sortLinked(list) {
  55391. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  55392. do {
  55393. p = list;
  55394. list = null;
  55395. tail = null;
  55396. numMerges = 0;
  55397. while (p) {
  55398. numMerges++;
  55399. q = p;
  55400. pSize = 0;
  55401. for (i = 0; i < inSize; i++) {
  55402. pSize++;
  55403. q = q.nextZ;
  55404. if (!q)
  55405. break;
  55406. }
  55407. qSize = inSize;
  55408. while (pSize > 0 || (qSize > 0 && q)) {
  55409. if (pSize === 0) {
  55410. e = q;
  55411. q = q.nextZ;
  55412. qSize--;
  55413. }
  55414. else if (qSize === 0 || !q) {
  55415. e = p;
  55416. p = p.nextZ;
  55417. pSize--;
  55418. }
  55419. else if (p.z <= q.z) {
  55420. e = p;
  55421. p = p.nextZ;
  55422. pSize--;
  55423. }
  55424. else {
  55425. e = q;
  55426. q = q.nextZ;
  55427. qSize--;
  55428. }
  55429. if (tail)
  55430. tail.nextZ = e;
  55431. else
  55432. list = e;
  55433. e.prevZ = tail;
  55434. tail = e;
  55435. }
  55436. p = q;
  55437. }
  55438. tail.nextZ = null;
  55439. inSize *= 2;
  55440. } while (numMerges > 1);
  55441. return list;
  55442. }
  55443. // z-order of a point given coords and size of the data bounding box
  55444. function zOrder(x, y, minX, minY, size) {
  55445. // coords are transformed into non-negative 15-bit integer range
  55446. x = 32767 * (x - minX) / size;
  55447. y = 32767 * (y - minY) / size;
  55448. x = (x | (x << 8)) & 0x00FF00FF;
  55449. x = (x | (x << 4)) & 0x0F0F0F0F;
  55450. x = (x | (x << 2)) & 0x33333333;
  55451. x = (x | (x << 1)) & 0x55555555;
  55452. y = (y | (y << 8)) & 0x00FF00FF;
  55453. y = (y | (y << 4)) & 0x0F0F0F0F;
  55454. y = (y | (y << 2)) & 0x33333333;
  55455. y = (y | (y << 1)) & 0x55555555;
  55456. return x | (y << 1);
  55457. }
  55458. // find the leftmost node of a polygon ring
  55459. function getLeftmost(start) {
  55460. var p = start, leftmost = start;
  55461. do {
  55462. if (p.x < leftmost.x)
  55463. leftmost = p;
  55464. p = p.next;
  55465. } while (p !== start);
  55466. return leftmost;
  55467. }
  55468. // check if a point lies within a convex triangle
  55469. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  55470. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  55471. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  55472. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  55473. }
  55474. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  55475. function isValidDiagonal(a, b) {
  55476. return a.next.i !== b.i &&
  55477. a.prev.i !== b.i &&
  55478. !intersectsPolygon(a, b) &&
  55479. locallyInside(a, b) &&
  55480. locallyInside(b, a) &&
  55481. middleInside(a, b);
  55482. }
  55483. // signed area of a triangle
  55484. function area(p, q, r) {
  55485. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  55486. }
  55487. // check if two points are equal
  55488. function equals(p1, p2) {
  55489. return p1.x === p2.x && p1.y === p2.y;
  55490. }
  55491. // check if two segments intersect
  55492. function intersects(p1, q1, p2, q2) {
  55493. if ((equals(p1, q1) && equals(p2, q2)) ||
  55494. (equals(p1, q2) && equals(p2, q1)))
  55495. return true;
  55496. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  55497. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  55498. }
  55499. // check if a polygon diagonal intersects any polygon segments
  55500. function intersectsPolygon(a, b) {
  55501. var p = a;
  55502. do {
  55503. if (p.i !== a.i &&
  55504. p.next.i !== a.i &&
  55505. p.i !== b.i &&
  55506. p.next.i !== b.i &&
  55507. intersects(p, p.next, a, b))
  55508. return true;
  55509. p = p.next;
  55510. } while (p !== a);
  55511. return false;
  55512. }
  55513. // check if a polygon diagonal is locally inside the polygon
  55514. function locallyInside(a, b) {
  55515. return area(a.prev, a, a.next) < 0
  55516. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  55517. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  55518. }
  55519. // check if the middle point of a polygon diagonal is inside the polygon
  55520. function middleInside(a, b) {
  55521. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  55522. do {
  55523. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  55524. inside = !inside;
  55525. p = p.next;
  55526. } while (p !== a);
  55527. return inside;
  55528. }
  55529. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  55530. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  55531. function splitPolygon(a, b) {
  55532. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  55533. a.next = b;
  55534. b.prev = a;
  55535. a2.next = an;
  55536. an.prev = a2;
  55537. b2.next = a2;
  55538. a2.prev = b2;
  55539. bp.next = b2;
  55540. b2.prev = bp;
  55541. return b2;
  55542. }
  55543. // create a node and optionally link it with previous one (in a circular doubly linked list)
  55544. function insertNode(i, x, y, last) {
  55545. var p = new Node(i, x, y);
  55546. if (!last) {
  55547. p.prev = p;
  55548. p.next = p;
  55549. }
  55550. else {
  55551. p.next = last.next;
  55552. p.prev = last;
  55553. last.next.prev = p;
  55554. last.next = p;
  55555. }
  55556. return p;
  55557. }
  55558. function removeNode(p) {
  55559. p.next.prev = p.prev;
  55560. p.prev.next = p.next;
  55561. if (p.prevZ)
  55562. p.prevZ.nextZ = p.nextZ;
  55563. if (p.nextZ)
  55564. p.nextZ.prevZ = p.prevZ;
  55565. }
  55566. function Node(i, x, y) {
  55567. // vertice index in coordinates array
  55568. this.i = i;
  55569. // vertex coordinates
  55570. this.x = x;
  55571. this.y = y;
  55572. // previous and next vertice nodes in a polygon ring
  55573. this.prev = null;
  55574. this.next = null;
  55575. // z-order curve value
  55576. this.z = null;
  55577. // previous and next nodes in z-order
  55578. this.prevZ = null;
  55579. this.nextZ = null;
  55580. // indicates whether this is a steiner point
  55581. this.steiner = false;
  55582. }
  55583. /**
  55584. * return a percentage difference between the polygon area and its triangulation area;
  55585. * used to verify correctness of triangulation
  55586. */
  55587. function deviation(data, holeIndices, dim, triangles) {
  55588. var hasHoles = holeIndices && holeIndices.length;
  55589. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  55590. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  55591. if (hasHoles) {
  55592. for (var i = 0, len = holeIndices.length; i < len; i++) {
  55593. var start = holeIndices[i] * dim;
  55594. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  55595. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  55596. }
  55597. }
  55598. var trianglesArea = 0;
  55599. for (i = 0; i < triangles.length; i += 3) {
  55600. var a = triangles[i] * dim;
  55601. var b = triangles[i + 1] * dim;
  55602. var c = triangles[i + 2] * dim;
  55603. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  55604. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  55605. }
  55606. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  55607. }
  55608. Earcut.deviation = deviation;
  55609. ;
  55610. function signedArea(data, start, end, dim) {
  55611. var sum = 0;
  55612. for (var i = start, j = end - dim; i < end; i += dim) {
  55613. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  55614. j = i;
  55615. }
  55616. return sum;
  55617. }
  55618. /**
  55619. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  55620. */
  55621. function flatten(data) {
  55622. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  55623. for (var i = 0; i < data.length; i++) {
  55624. for (var j = 0; j < data[i].length; j++) {
  55625. for (var d = 0; d < dim; d++)
  55626. result.vertices.push(data[i][j][d]);
  55627. }
  55628. if (i > 0) {
  55629. holeIndex += data[i - 1].length;
  55630. result.holes.push(holeIndex);
  55631. }
  55632. }
  55633. return result;
  55634. }
  55635. Earcut.flatten = flatten;
  55636. ;
  55637. })(Earcut || (Earcut = {}));
  55638. //# sourceMappingURL=babylon.earcut.js.map
  55639. /// <reference path="..\Math\babylon.math.ts" />
  55640. var BABYLON;
  55641. (function (BABYLON) {
  55642. var IndexedVector2 = (function (_super) {
  55643. __extends(IndexedVector2, _super);
  55644. function IndexedVector2(original, index) {
  55645. var _this = _super.call(this, original.x, original.y) || this;
  55646. _this.index = index;
  55647. return _this;
  55648. }
  55649. return IndexedVector2;
  55650. }(BABYLON.Vector2));
  55651. var PolygonPoints = (function () {
  55652. function PolygonPoints() {
  55653. this.elements = new Array();
  55654. }
  55655. PolygonPoints.prototype.add = function (originalPoints) {
  55656. var _this = this;
  55657. var result = new Array();
  55658. originalPoints.forEach(function (point) {
  55659. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  55660. var newPoint = new IndexedVector2(point, _this.elements.length);
  55661. result.push(newPoint);
  55662. _this.elements.push(newPoint);
  55663. }
  55664. });
  55665. return result;
  55666. };
  55667. PolygonPoints.prototype.computeBounds = function () {
  55668. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  55669. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  55670. this.elements.forEach(function (point) {
  55671. // x
  55672. if (point.x < lmin.x) {
  55673. lmin.x = point.x;
  55674. }
  55675. else if (point.x > lmax.x) {
  55676. lmax.x = point.x;
  55677. }
  55678. // y
  55679. if (point.y < lmin.y) {
  55680. lmin.y = point.y;
  55681. }
  55682. else if (point.y > lmax.y) {
  55683. lmax.y = point.y;
  55684. }
  55685. });
  55686. return {
  55687. min: lmin,
  55688. max: lmax,
  55689. width: lmax.x - lmin.x,
  55690. height: lmax.y - lmin.y
  55691. };
  55692. };
  55693. return PolygonPoints;
  55694. }());
  55695. var Polygon = (function () {
  55696. function Polygon() {
  55697. }
  55698. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  55699. return [
  55700. new BABYLON.Vector2(xmin, ymin),
  55701. new BABYLON.Vector2(xmax, ymin),
  55702. new BABYLON.Vector2(xmax, ymax),
  55703. new BABYLON.Vector2(xmin, ymax)
  55704. ];
  55705. };
  55706. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  55707. if (cx === void 0) { cx = 0; }
  55708. if (cy === void 0) { cy = 0; }
  55709. if (numberOfSides === void 0) { numberOfSides = 32; }
  55710. var result = new Array();
  55711. var angle = 0;
  55712. var increment = (Math.PI * 2) / numberOfSides;
  55713. for (var i = 0; i < numberOfSides; i++) {
  55714. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  55715. angle -= increment;
  55716. }
  55717. return result;
  55718. };
  55719. Polygon.Parse = function (input) {
  55720. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  55721. var i, result = [];
  55722. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  55723. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  55724. }
  55725. return result;
  55726. };
  55727. Polygon.StartingAt = function (x, y) {
  55728. return BABYLON.Path2.StartingAt(x, y);
  55729. };
  55730. return Polygon;
  55731. }());
  55732. BABYLON.Polygon = Polygon;
  55733. var PolygonMeshBuilder = (function () {
  55734. function PolygonMeshBuilder(name, contours, scene) {
  55735. this._points = new PolygonPoints();
  55736. this._outlinepoints = new PolygonPoints();
  55737. this._holes = [];
  55738. this._epoints = new Array();
  55739. this._eholes = new Array();
  55740. this._name = name;
  55741. this._scene = scene;
  55742. var points;
  55743. if (contours instanceof BABYLON.Path2) {
  55744. points = contours.getPoints();
  55745. }
  55746. else {
  55747. points = contours;
  55748. }
  55749. this._addToepoint(points);
  55750. this._points.add(points);
  55751. this._outlinepoints.add(points);
  55752. }
  55753. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  55754. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  55755. var p = points_1[_i];
  55756. this._epoints.push(p.x, p.y);
  55757. }
  55758. };
  55759. PolygonMeshBuilder.prototype.addHole = function (hole) {
  55760. this._points.add(hole);
  55761. var holepoints = new PolygonPoints();
  55762. holepoints.add(hole);
  55763. this._holes.push(holepoints);
  55764. this._eholes.push(this._epoints.length / 2);
  55765. this._addToepoint(hole);
  55766. return this;
  55767. };
  55768. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  55769. var _this = this;
  55770. if (updatable === void 0) { updatable = false; }
  55771. var result = new BABYLON.Mesh(this._name, this._scene);
  55772. var normals = [];
  55773. var positions = [];
  55774. var uvs = [];
  55775. var bounds = this._points.computeBounds();
  55776. this._points.elements.forEach(function (p) {
  55777. normals.push(0, 1.0, 0);
  55778. positions.push(p.x, 0, p.y);
  55779. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  55780. });
  55781. var indices = [];
  55782. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  55783. for (var i = 0; i < res.length; i++) {
  55784. indices.push(res[i]);
  55785. }
  55786. if (depth > 0) {
  55787. var positionscount = (positions.length / 3); //get the current pointcount
  55788. this._points.elements.forEach(function (p) {
  55789. normals.push(0, -1.0, 0);
  55790. positions.push(p.x, -depth, p.y);
  55791. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  55792. });
  55793. var totalCount = indices.length;
  55794. for (var i = 0; i < totalCount; i += 3) {
  55795. var i0 = indices[i + 0];
  55796. var i1 = indices[i + 1];
  55797. var i2 = indices[i + 2];
  55798. indices.push(i2 + positionscount);
  55799. indices.push(i1 + positionscount);
  55800. indices.push(i0 + positionscount);
  55801. }
  55802. //Add the sides
  55803. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  55804. this._holes.forEach(function (hole) {
  55805. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  55806. });
  55807. }
  55808. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  55809. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  55810. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  55811. result.setIndices(indices);
  55812. return result;
  55813. };
  55814. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  55815. var StartIndex = positions.length / 3;
  55816. var ulength = 0;
  55817. for (var i = 0; i < points.elements.length; i++) {
  55818. var p = points.elements[i];
  55819. var p1;
  55820. if ((i + 1) > points.elements.length - 1) {
  55821. p1 = points.elements[0];
  55822. }
  55823. else {
  55824. p1 = points.elements[i + 1];
  55825. }
  55826. positions.push(p.x, 0, p.y);
  55827. positions.push(p.x, -depth, p.y);
  55828. positions.push(p1.x, 0, p1.y);
  55829. positions.push(p1.x, -depth, p1.y);
  55830. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  55831. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  55832. var v3 = v2.subtract(v1);
  55833. var v4 = new BABYLON.Vector3(0, 1, 0);
  55834. var vn = BABYLON.Vector3.Cross(v3, v4);
  55835. vn = vn.normalize();
  55836. uvs.push(ulength / bounds.width, 0);
  55837. uvs.push(ulength / bounds.width, 1);
  55838. ulength += v3.length();
  55839. uvs.push((ulength / bounds.width), 0);
  55840. uvs.push((ulength / bounds.width), 1);
  55841. if (!flip) {
  55842. normals.push(-vn.x, -vn.y, -vn.z);
  55843. normals.push(-vn.x, -vn.y, -vn.z);
  55844. normals.push(-vn.x, -vn.y, -vn.z);
  55845. normals.push(-vn.x, -vn.y, -vn.z);
  55846. indices.push(StartIndex);
  55847. indices.push(StartIndex + 1);
  55848. indices.push(StartIndex + 2);
  55849. indices.push(StartIndex + 1);
  55850. indices.push(StartIndex + 3);
  55851. indices.push(StartIndex + 2);
  55852. }
  55853. else {
  55854. normals.push(vn.x, vn.y, vn.z);
  55855. normals.push(vn.x, vn.y, vn.z);
  55856. normals.push(vn.x, vn.y, vn.z);
  55857. normals.push(vn.x, vn.y, vn.z);
  55858. indices.push(StartIndex);
  55859. indices.push(StartIndex + 2);
  55860. indices.push(StartIndex + 1);
  55861. indices.push(StartIndex + 1);
  55862. indices.push(StartIndex + 2);
  55863. indices.push(StartIndex + 3);
  55864. }
  55865. StartIndex += 4;
  55866. }
  55867. ;
  55868. };
  55869. return PolygonMeshBuilder;
  55870. }());
  55871. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  55872. })(BABYLON || (BABYLON = {}));
  55873. //# sourceMappingURL=babylon.polygonMesh.js.map
  55874. var BABYLON;
  55875. (function (BABYLON) {
  55876. // Unique ID when we import meshes from Babylon to CSG
  55877. var currentCSGMeshId = 0;
  55878. // # class Vertex
  55879. // Represents a vertex of a polygon. Use your own vertex class instead of this
  55880. // one to provide additional features like texture coordinates and vertex
  55881. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  55882. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  55883. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  55884. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  55885. // is not used anywhere else.
  55886. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  55887. var Vertex = (function () {
  55888. function Vertex(pos, normal, uv) {
  55889. this.pos = pos;
  55890. this.normal = normal;
  55891. this.uv = uv;
  55892. }
  55893. Vertex.prototype.clone = function () {
  55894. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  55895. };
  55896. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  55897. // orientation of a polygon is flipped.
  55898. Vertex.prototype.flip = function () {
  55899. this.normal = this.normal.scale(-1);
  55900. };
  55901. // Create a new vertex between this vertex and `other` by linearly
  55902. // interpolating all properties using a parameter of `t`. Subclasses should
  55903. // override this to interpolate additional properties.
  55904. Vertex.prototype.interpolate = function (other, t) {
  55905. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  55906. };
  55907. return Vertex;
  55908. }());
  55909. // # class Plane
  55910. // Represents a plane in 3D space.
  55911. var Plane = (function () {
  55912. function Plane(normal, w) {
  55913. this.normal = normal;
  55914. this.w = w;
  55915. }
  55916. Plane.FromPoints = function (a, b, c) {
  55917. var v0 = c.subtract(a);
  55918. var v1 = b.subtract(a);
  55919. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  55920. return null;
  55921. }
  55922. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  55923. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  55924. };
  55925. Plane.prototype.clone = function () {
  55926. return new Plane(this.normal.clone(), this.w);
  55927. };
  55928. Plane.prototype.flip = function () {
  55929. this.normal.scaleInPlace(-1);
  55930. this.w = -this.w;
  55931. };
  55932. // Split `polygon` by this plane if needed, then put the polygon or polygon
  55933. // fragments in the appropriate lists. Coplanar polygons go into either
  55934. // `coplanarFront` or `coplanarBack` depending on their orientation with
  55935. // respect to this plane. Polygons in front or in back of this plane go into
  55936. // either `front` or `back`.
  55937. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  55938. var COPLANAR = 0;
  55939. var FRONT = 1;
  55940. var BACK = 2;
  55941. var SPANNING = 3;
  55942. // Classify each point as well as the entire polygon into one of the above
  55943. // four classes.
  55944. var polygonType = 0;
  55945. var types = [];
  55946. var i;
  55947. var t;
  55948. for (i = 0; i < polygon.vertices.length; i++) {
  55949. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  55950. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  55951. polygonType |= type;
  55952. types.push(type);
  55953. }
  55954. // Put the polygon in the correct list, splitting it when necessary.
  55955. switch (polygonType) {
  55956. case COPLANAR:
  55957. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  55958. break;
  55959. case FRONT:
  55960. front.push(polygon);
  55961. break;
  55962. case BACK:
  55963. back.push(polygon);
  55964. break;
  55965. case SPANNING:
  55966. var f = [], b = [];
  55967. for (i = 0; i < polygon.vertices.length; i++) {
  55968. var j = (i + 1) % polygon.vertices.length;
  55969. var ti = types[i], tj = types[j];
  55970. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  55971. if (ti !== BACK)
  55972. f.push(vi);
  55973. if (ti !== FRONT)
  55974. b.push(ti !== BACK ? vi.clone() : vi);
  55975. if ((ti | tj) === SPANNING) {
  55976. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  55977. var v = vi.interpolate(vj, t);
  55978. f.push(v);
  55979. b.push(v.clone());
  55980. }
  55981. }
  55982. var poly;
  55983. if (f.length >= 3) {
  55984. poly = new Polygon(f, polygon.shared);
  55985. if (poly.plane)
  55986. front.push(poly);
  55987. }
  55988. if (b.length >= 3) {
  55989. poly = new Polygon(b, polygon.shared);
  55990. if (poly.plane)
  55991. back.push(poly);
  55992. }
  55993. break;
  55994. }
  55995. };
  55996. return Plane;
  55997. }());
  55998. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  55999. // point is on the plane.
  56000. Plane.EPSILON = 1e-5;
  56001. // # class Polygon
  56002. // Represents a convex polygon. The vertices used to initialize a polygon must
  56003. // be coplanar and form a convex loop.
  56004. //
  56005. // Each convex polygon has a `shared` property, which is shared between all
  56006. // polygons that are clones of each other or were split from the same polygon.
  56007. // This can be used to define per-polygon properties (such as surface color).
  56008. var Polygon = (function () {
  56009. function Polygon(vertices, shared) {
  56010. this.vertices = vertices;
  56011. this.shared = shared;
  56012. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  56013. }
  56014. Polygon.prototype.clone = function () {
  56015. var vertices = this.vertices.map(function (v) { return v.clone(); });
  56016. return new Polygon(vertices, this.shared);
  56017. };
  56018. Polygon.prototype.flip = function () {
  56019. this.vertices.reverse().map(function (v) { v.flip(); });
  56020. this.plane.flip();
  56021. };
  56022. return Polygon;
  56023. }());
  56024. // # class Node
  56025. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  56026. // by picking a polygon to split along. That polygon (and all other coplanar
  56027. // polygons) are added directly to that node and the other polygons are added to
  56028. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  56029. // no distinction between internal and leaf nodes.
  56030. var Node = (function () {
  56031. function Node(polygons) {
  56032. this.plane = null;
  56033. this.front = null;
  56034. this.back = null;
  56035. this.polygons = [];
  56036. if (polygons) {
  56037. this.build(polygons);
  56038. }
  56039. }
  56040. Node.prototype.clone = function () {
  56041. var node = new Node();
  56042. node.plane = this.plane && this.plane.clone();
  56043. node.front = this.front && this.front.clone();
  56044. node.back = this.back && this.back.clone();
  56045. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  56046. return node;
  56047. };
  56048. // Convert solid space to empty space and empty space to solid space.
  56049. Node.prototype.invert = function () {
  56050. for (var i = 0; i < this.polygons.length; i++) {
  56051. this.polygons[i].flip();
  56052. }
  56053. if (this.plane) {
  56054. this.plane.flip();
  56055. }
  56056. if (this.front) {
  56057. this.front.invert();
  56058. }
  56059. if (this.back) {
  56060. this.back.invert();
  56061. }
  56062. var temp = this.front;
  56063. this.front = this.back;
  56064. this.back = temp;
  56065. };
  56066. // Recursively remove all polygons in `polygons` that are inside this BSP
  56067. // tree.
  56068. Node.prototype.clipPolygons = function (polygons) {
  56069. if (!this.plane)
  56070. return polygons.slice();
  56071. var front = [], back = [];
  56072. for (var i = 0; i < polygons.length; i++) {
  56073. this.plane.splitPolygon(polygons[i], front, back, front, back);
  56074. }
  56075. if (this.front) {
  56076. front = this.front.clipPolygons(front);
  56077. }
  56078. if (this.back) {
  56079. back = this.back.clipPolygons(back);
  56080. }
  56081. else {
  56082. back = [];
  56083. }
  56084. return front.concat(back);
  56085. };
  56086. // Remove all polygons in this BSP tree that are inside the other BSP tree
  56087. // `bsp`.
  56088. Node.prototype.clipTo = function (bsp) {
  56089. this.polygons = bsp.clipPolygons(this.polygons);
  56090. if (this.front)
  56091. this.front.clipTo(bsp);
  56092. if (this.back)
  56093. this.back.clipTo(bsp);
  56094. };
  56095. // Return a list of all polygons in this BSP tree.
  56096. Node.prototype.allPolygons = function () {
  56097. var polygons = this.polygons.slice();
  56098. if (this.front)
  56099. polygons = polygons.concat(this.front.allPolygons());
  56100. if (this.back)
  56101. polygons = polygons.concat(this.back.allPolygons());
  56102. return polygons;
  56103. };
  56104. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  56105. // new polygons are filtered down to the bottom of the tree and become new
  56106. // nodes there. Each set of polygons is partitioned using the first polygon
  56107. // (no heuristic is used to pick a good split).
  56108. Node.prototype.build = function (polygons) {
  56109. if (!polygons.length)
  56110. return;
  56111. if (!this.plane)
  56112. this.plane = polygons[0].plane.clone();
  56113. var front = [], back = [];
  56114. for (var i = 0; i < polygons.length; i++) {
  56115. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  56116. }
  56117. if (front.length) {
  56118. if (!this.front)
  56119. this.front = new Node();
  56120. this.front.build(front);
  56121. }
  56122. if (back.length) {
  56123. if (!this.back)
  56124. this.back = new Node();
  56125. this.back.build(back);
  56126. }
  56127. };
  56128. return Node;
  56129. }());
  56130. var CSG = (function () {
  56131. function CSG() {
  56132. this.polygons = new Array();
  56133. }
  56134. // Convert BABYLON.Mesh to BABYLON.CSG
  56135. CSG.FromMesh = function (mesh) {
  56136. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  56137. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  56138. if (mesh instanceof BABYLON.Mesh) {
  56139. mesh.computeWorldMatrix(true);
  56140. matrix = mesh.getWorldMatrix();
  56141. meshPosition = mesh.position.clone();
  56142. meshRotation = mesh.rotation.clone();
  56143. if (mesh.rotationQuaternion) {
  56144. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  56145. }
  56146. meshScaling = mesh.scaling.clone();
  56147. }
  56148. else {
  56149. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  56150. }
  56151. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56152. var subMeshes = mesh.subMeshes;
  56153. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  56154. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  56155. vertices = [];
  56156. for (var j = 0; j < 3; j++) {
  56157. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  56158. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  56159. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  56160. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  56161. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  56162. vertex = new Vertex(position, normal, uv);
  56163. vertices.push(vertex);
  56164. }
  56165. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  56166. // To handle the case of degenerated triangle
  56167. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  56168. if (polygon.plane)
  56169. polygons.push(polygon);
  56170. }
  56171. }
  56172. var csg = CSG.FromPolygons(polygons);
  56173. csg.matrix = matrix;
  56174. csg.position = meshPosition;
  56175. csg.rotation = meshRotation;
  56176. csg.scaling = meshScaling;
  56177. csg.rotationQuaternion = meshRotationQuaternion;
  56178. currentCSGMeshId++;
  56179. return csg;
  56180. };
  56181. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  56182. CSG.FromPolygons = function (polygons) {
  56183. var csg = new CSG();
  56184. csg.polygons = polygons;
  56185. return csg;
  56186. };
  56187. CSG.prototype.clone = function () {
  56188. var csg = new CSG();
  56189. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  56190. csg.copyTransformAttributes(this);
  56191. return csg;
  56192. };
  56193. CSG.prototype.toPolygons = function () {
  56194. return this.polygons;
  56195. };
  56196. CSG.prototype.union = function (csg) {
  56197. var a = new Node(this.clone().polygons);
  56198. var b = new Node(csg.clone().polygons);
  56199. a.clipTo(b);
  56200. b.clipTo(a);
  56201. b.invert();
  56202. b.clipTo(a);
  56203. b.invert();
  56204. a.build(b.allPolygons());
  56205. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56206. };
  56207. CSG.prototype.unionInPlace = function (csg) {
  56208. var a = new Node(this.polygons);
  56209. var b = new Node(csg.polygons);
  56210. a.clipTo(b);
  56211. b.clipTo(a);
  56212. b.invert();
  56213. b.clipTo(a);
  56214. b.invert();
  56215. a.build(b.allPolygons());
  56216. this.polygons = a.allPolygons();
  56217. };
  56218. CSG.prototype.subtract = function (csg) {
  56219. var a = new Node(this.clone().polygons);
  56220. var b = new Node(csg.clone().polygons);
  56221. a.invert();
  56222. a.clipTo(b);
  56223. b.clipTo(a);
  56224. b.invert();
  56225. b.clipTo(a);
  56226. b.invert();
  56227. a.build(b.allPolygons());
  56228. a.invert();
  56229. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56230. };
  56231. CSG.prototype.subtractInPlace = function (csg) {
  56232. var a = new Node(this.polygons);
  56233. var b = new Node(csg.polygons);
  56234. a.invert();
  56235. a.clipTo(b);
  56236. b.clipTo(a);
  56237. b.invert();
  56238. b.clipTo(a);
  56239. b.invert();
  56240. a.build(b.allPolygons());
  56241. a.invert();
  56242. this.polygons = a.allPolygons();
  56243. };
  56244. CSG.prototype.intersect = function (csg) {
  56245. var a = new Node(this.clone().polygons);
  56246. var b = new Node(csg.clone().polygons);
  56247. a.invert();
  56248. b.clipTo(a);
  56249. b.invert();
  56250. a.clipTo(b);
  56251. b.clipTo(a);
  56252. a.build(b.allPolygons());
  56253. a.invert();
  56254. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56255. };
  56256. CSG.prototype.intersectInPlace = function (csg) {
  56257. var a = new Node(this.polygons);
  56258. var b = new Node(csg.polygons);
  56259. a.invert();
  56260. b.clipTo(a);
  56261. b.invert();
  56262. a.clipTo(b);
  56263. b.clipTo(a);
  56264. a.build(b.allPolygons());
  56265. a.invert();
  56266. this.polygons = a.allPolygons();
  56267. };
  56268. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  56269. // not modified.
  56270. CSG.prototype.inverse = function () {
  56271. var csg = this.clone();
  56272. csg.inverseInPlace();
  56273. return csg;
  56274. };
  56275. CSG.prototype.inverseInPlace = function () {
  56276. this.polygons.map(function (p) { p.flip(); });
  56277. };
  56278. // This is used to keep meshes transformations so they can be restored
  56279. // when we build back a Babylon Mesh
  56280. // NB : All CSG operations are performed in world coordinates
  56281. CSG.prototype.copyTransformAttributes = function (csg) {
  56282. this.matrix = csg.matrix;
  56283. this.position = csg.position;
  56284. this.rotation = csg.rotation;
  56285. this.scaling = csg.scaling;
  56286. this.rotationQuaternion = csg.rotationQuaternion;
  56287. return this;
  56288. };
  56289. // Build Raw mesh from CSG
  56290. // Coordinates here are in world space
  56291. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  56292. var matrix = this.matrix.clone();
  56293. matrix.invert();
  56294. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  56295. if (keepSubMeshes) {
  56296. // Sort Polygons, since subMeshes are indices range
  56297. polygons.sort(function (a, b) {
  56298. if (a.shared.meshId === b.shared.meshId) {
  56299. return a.shared.subMeshId - b.shared.subMeshId;
  56300. }
  56301. else {
  56302. return a.shared.meshId - b.shared.meshId;
  56303. }
  56304. });
  56305. }
  56306. for (var i = 0, il = polygons.length; i < il; i++) {
  56307. polygon = polygons[i];
  56308. // Building SubMeshes
  56309. if (!subMesh_dict[polygon.shared.meshId]) {
  56310. subMesh_dict[polygon.shared.meshId] = {};
  56311. }
  56312. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  56313. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  56314. indexStart: +Infinity,
  56315. indexEnd: -Infinity,
  56316. materialIndex: polygon.shared.materialIndex
  56317. };
  56318. }
  56319. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  56320. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  56321. polygonIndices[0] = 0;
  56322. polygonIndices[1] = j - 1;
  56323. polygonIndices[2] = j;
  56324. for (var k = 0; k < 3; k++) {
  56325. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  56326. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  56327. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  56328. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  56329. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  56330. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  56331. // Check if 2 points can be merged
  56332. if (!(typeof vertex_idx !== 'undefined' &&
  56333. normals[vertex_idx * 3] === localNormal.x &&
  56334. normals[vertex_idx * 3 + 1] === localNormal.y &&
  56335. normals[vertex_idx * 3 + 2] === localNormal.z &&
  56336. uvs[vertex_idx * 2] === uv.x &&
  56337. uvs[vertex_idx * 2 + 1] === uv.y)) {
  56338. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  56339. uvs.push(uv.x, uv.y);
  56340. normals.push(normal.x, normal.y, normal.z);
  56341. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  56342. }
  56343. indices.push(vertex_idx);
  56344. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  56345. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  56346. currentIndex++;
  56347. }
  56348. }
  56349. }
  56350. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  56351. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  56352. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  56353. mesh.setIndices(indices);
  56354. if (keepSubMeshes) {
  56355. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  56356. var materialIndexOffset = 0, materialMaxIndex;
  56357. mesh.subMeshes = new Array();
  56358. for (var m in subMesh_dict) {
  56359. materialMaxIndex = -1;
  56360. for (var sm in subMesh_dict[m]) {
  56361. subMesh_obj = subMesh_dict[m][sm];
  56362. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  56363. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  56364. }
  56365. materialIndexOffset += ++materialMaxIndex;
  56366. }
  56367. }
  56368. return mesh;
  56369. };
  56370. // Build Mesh from CSG taking material and transforms into account
  56371. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  56372. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  56373. mesh.material = material;
  56374. mesh.position.copyFrom(this.position);
  56375. mesh.rotation.copyFrom(this.rotation);
  56376. if (this.rotationQuaternion) {
  56377. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  56378. }
  56379. mesh.scaling.copyFrom(this.scaling);
  56380. mesh.computeWorldMatrix(true);
  56381. return mesh;
  56382. };
  56383. return CSG;
  56384. }());
  56385. BABYLON.CSG = CSG;
  56386. })(BABYLON || (BABYLON = {}));
  56387. //# sourceMappingURL=babylon.csg.js.map
  56388. var BABYLON;
  56389. (function (BABYLON) {
  56390. var LensFlare = (function () {
  56391. function LensFlare(size, position, color, imgUrl, system) {
  56392. this.size = size;
  56393. this.position = position;
  56394. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  56395. this.dispose = function () {
  56396. if (this.texture) {
  56397. this.texture.dispose();
  56398. }
  56399. // Remove from scene
  56400. var index = this._system.lensFlares.indexOf(this);
  56401. this._system.lensFlares.splice(index, 1);
  56402. };
  56403. this.color = color || new BABYLON.Color3(1, 1, 1);
  56404. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  56405. this._system = system;
  56406. system.lensFlares.push(this);
  56407. }
  56408. return LensFlare;
  56409. }());
  56410. BABYLON.LensFlare = LensFlare;
  56411. })(BABYLON || (BABYLON = {}));
  56412. //# sourceMappingURL=babylon.lensFlare.js.map
  56413. var BABYLON;
  56414. (function (BABYLON) {
  56415. var LensFlareSystem = (function () {
  56416. function LensFlareSystem(name, emitter, scene) {
  56417. this.name = name;
  56418. this.lensFlares = new Array();
  56419. this.borderLimit = 300;
  56420. this.viewportBorder = 0;
  56421. this.layerMask = 0x0FFFFFFF;
  56422. this._vertexBuffers = {};
  56423. this._isEnabled = true;
  56424. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56425. this._emitter = emitter;
  56426. this.id = name;
  56427. scene.lensFlareSystems.push(this);
  56428. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  56429. var engine = scene.getEngine();
  56430. // VBO
  56431. var vertices = [];
  56432. vertices.push(1, 1);
  56433. vertices.push(-1, 1);
  56434. vertices.push(-1, -1);
  56435. vertices.push(1, -1);
  56436. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  56437. // Indices
  56438. var indices = [];
  56439. indices.push(0);
  56440. indices.push(1);
  56441. indices.push(2);
  56442. indices.push(0);
  56443. indices.push(2);
  56444. indices.push(3);
  56445. this._indexBuffer = engine.createIndexBuffer(indices);
  56446. // Effects
  56447. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  56448. }
  56449. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  56450. get: function () {
  56451. return this._isEnabled;
  56452. },
  56453. set: function (value) {
  56454. this._isEnabled = value;
  56455. },
  56456. enumerable: true,
  56457. configurable: true
  56458. });
  56459. LensFlareSystem.prototype.getScene = function () {
  56460. return this._scene;
  56461. };
  56462. LensFlareSystem.prototype.getEmitter = function () {
  56463. return this._emitter;
  56464. };
  56465. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  56466. this._emitter = newEmitter;
  56467. };
  56468. LensFlareSystem.prototype.getEmitterPosition = function () {
  56469. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  56470. };
  56471. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  56472. var position = this.getEmitterPosition();
  56473. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  56474. this._positionX = position.x;
  56475. this._positionY = position.y;
  56476. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  56477. if (this.viewportBorder > 0) {
  56478. globalViewport.x -= this.viewportBorder;
  56479. globalViewport.y -= this.viewportBorder;
  56480. globalViewport.width += this.viewportBorder * 2;
  56481. globalViewport.height += this.viewportBorder * 2;
  56482. position.x += this.viewportBorder;
  56483. position.y += this.viewportBorder;
  56484. this._positionX += this.viewportBorder;
  56485. this._positionY += this.viewportBorder;
  56486. }
  56487. if (position.z > 0) {
  56488. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  56489. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  56490. return true;
  56491. }
  56492. return true;
  56493. }
  56494. return false;
  56495. };
  56496. LensFlareSystem.prototype._isVisible = function () {
  56497. if (!this._isEnabled) {
  56498. return false;
  56499. }
  56500. var emitterPosition = this.getEmitterPosition();
  56501. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  56502. var distance = direction.length();
  56503. direction.normalize();
  56504. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  56505. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  56506. return !pickInfo.hit || pickInfo.distance > distance;
  56507. };
  56508. LensFlareSystem.prototype.render = function () {
  56509. if (!this._effect.isReady())
  56510. return false;
  56511. var engine = this._scene.getEngine();
  56512. var viewport = this._scene.activeCamera.viewport;
  56513. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  56514. // Position
  56515. if (!this.computeEffectivePosition(globalViewport)) {
  56516. return false;
  56517. }
  56518. // Visibility
  56519. if (!this._isVisible()) {
  56520. return false;
  56521. }
  56522. // Intensity
  56523. var awayX;
  56524. var awayY;
  56525. if (this._positionX < this.borderLimit + globalViewport.x) {
  56526. awayX = this.borderLimit + globalViewport.x - this._positionX;
  56527. }
  56528. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  56529. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  56530. }
  56531. else {
  56532. awayX = 0;
  56533. }
  56534. if (this._positionY < this.borderLimit + globalViewport.y) {
  56535. awayY = this.borderLimit + globalViewport.y - this._positionY;
  56536. }
  56537. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  56538. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  56539. }
  56540. else {
  56541. awayY = 0;
  56542. }
  56543. var away = (awayX > awayY) ? awayX : awayY;
  56544. away -= this.viewportBorder;
  56545. if (away > this.borderLimit) {
  56546. away = this.borderLimit;
  56547. }
  56548. var intensity = 1.0 - (away / this.borderLimit);
  56549. if (intensity < 0) {
  56550. return false;
  56551. }
  56552. if (intensity > 1.0) {
  56553. intensity = 1.0;
  56554. }
  56555. if (this.viewportBorder > 0) {
  56556. globalViewport.x += this.viewportBorder;
  56557. globalViewport.y += this.viewportBorder;
  56558. globalViewport.width -= this.viewportBorder * 2;
  56559. globalViewport.height -= this.viewportBorder * 2;
  56560. this._positionX -= this.viewportBorder;
  56561. this._positionY -= this.viewportBorder;
  56562. }
  56563. // Position
  56564. var centerX = globalViewport.x + globalViewport.width / 2;
  56565. var centerY = globalViewport.y + globalViewport.height / 2;
  56566. var distX = centerX - this._positionX;
  56567. var distY = centerY - this._positionY;
  56568. // Effects
  56569. engine.enableEffect(this._effect);
  56570. engine.setState(false);
  56571. engine.setDepthBuffer(false);
  56572. // VBOs
  56573. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56574. // Flares
  56575. for (var index = 0; index < this.lensFlares.length; index++) {
  56576. var flare = this.lensFlares[index];
  56577. engine.setAlphaMode(flare.alphaMode);
  56578. var x = centerX - (distX * flare.position);
  56579. var y = centerY - (distY * flare.position);
  56580. var cw = flare.size;
  56581. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  56582. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  56583. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  56584. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  56585. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  56586. // Texture
  56587. this._effect.setTexture("textureSampler", flare.texture);
  56588. // Color
  56589. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  56590. // Draw order
  56591. engine.draw(true, 0, 6);
  56592. }
  56593. engine.setDepthBuffer(true);
  56594. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56595. return true;
  56596. };
  56597. LensFlareSystem.prototype.dispose = function () {
  56598. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56599. if (vertexBuffer) {
  56600. vertexBuffer.dispose();
  56601. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56602. }
  56603. if (this._indexBuffer) {
  56604. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56605. this._indexBuffer = null;
  56606. }
  56607. while (this.lensFlares.length) {
  56608. this.lensFlares[0].dispose();
  56609. }
  56610. // Remove from scene
  56611. var index = this._scene.lensFlareSystems.indexOf(this);
  56612. this._scene.lensFlareSystems.splice(index, 1);
  56613. };
  56614. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  56615. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  56616. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  56617. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  56618. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  56619. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  56620. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  56621. var parsedFlare = parsedLensFlareSystem.flares[index];
  56622. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  56623. }
  56624. return lensFlareSystem;
  56625. };
  56626. LensFlareSystem.prototype.serialize = function () {
  56627. var serializationObject = {};
  56628. serializationObject.id = this.id;
  56629. serializationObject.name = this.name;
  56630. serializationObject.emitterId = this.getEmitter().id;
  56631. serializationObject.borderLimit = this.borderLimit;
  56632. serializationObject.flares = [];
  56633. for (var index = 0; index < this.lensFlares.length; index++) {
  56634. var flare = this.lensFlares[index];
  56635. serializationObject.flares.push({
  56636. size: flare.size,
  56637. position: flare.position,
  56638. color: flare.color.asArray(),
  56639. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  56640. });
  56641. }
  56642. return serializationObject;
  56643. };
  56644. return LensFlareSystem;
  56645. }());
  56646. BABYLON.LensFlareSystem = LensFlareSystem;
  56647. })(BABYLON || (BABYLON = {}));
  56648. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  56649. var BABYLON;
  56650. (function (BABYLON) {
  56651. /**
  56652. * This is a holder class for the physics joint created by the physics plugin.
  56653. * It holds a set of functions to control the underlying joint.
  56654. */
  56655. var PhysicsJoint = (function () {
  56656. function PhysicsJoint(type, jointData) {
  56657. this.type = type;
  56658. this.jointData = jointData;
  56659. jointData.nativeParams = jointData.nativeParams || {};
  56660. }
  56661. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  56662. get: function () {
  56663. return this._physicsJoint;
  56664. },
  56665. set: function (newJoint) {
  56666. if (this._physicsJoint) {
  56667. //remove from the wolrd
  56668. }
  56669. this._physicsJoint = newJoint;
  56670. },
  56671. enumerable: true,
  56672. configurable: true
  56673. });
  56674. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  56675. set: function (physicsPlugin) {
  56676. this._physicsPlugin = physicsPlugin;
  56677. },
  56678. enumerable: true,
  56679. configurable: true
  56680. });
  56681. /**
  56682. * Execute a function that is physics-plugin specific.
  56683. * @param {Function} func the function that will be executed.
  56684. * It accepts two parameters: the physics world and the physics joint.
  56685. */
  56686. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  56687. func(this._physicsPlugin.world, this._physicsJoint);
  56688. };
  56689. return PhysicsJoint;
  56690. }());
  56691. //TODO check if the native joints are the same
  56692. //Joint Types
  56693. PhysicsJoint.DistanceJoint = 0;
  56694. PhysicsJoint.HingeJoint = 1;
  56695. PhysicsJoint.BallAndSocketJoint = 2;
  56696. PhysicsJoint.WheelJoint = 3;
  56697. PhysicsJoint.SliderJoint = 4;
  56698. //OIMO
  56699. PhysicsJoint.PrismaticJoint = 5;
  56700. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  56701. PhysicsJoint.UniversalJoint = 6;
  56702. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  56703. //Cannon
  56704. //Similar to a Ball-Joint. Different in params
  56705. PhysicsJoint.PointToPointJoint = 8;
  56706. //Cannon only at the moment
  56707. PhysicsJoint.SpringJoint = 9;
  56708. PhysicsJoint.LockJoint = 10;
  56709. BABYLON.PhysicsJoint = PhysicsJoint;
  56710. /**
  56711. * A class representing a physics distance joint.
  56712. */
  56713. var DistanceJoint = (function (_super) {
  56714. __extends(DistanceJoint, _super);
  56715. function DistanceJoint(jointData) {
  56716. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  56717. }
  56718. /**
  56719. * Update the predefined distance.
  56720. */
  56721. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  56722. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  56723. };
  56724. return DistanceJoint;
  56725. }(PhysicsJoint));
  56726. BABYLON.DistanceJoint = DistanceJoint;
  56727. var MotorEnabledJoint = (function (_super) {
  56728. __extends(MotorEnabledJoint, _super);
  56729. function MotorEnabledJoint(type, jointData) {
  56730. return _super.call(this, type, jointData) || this;
  56731. }
  56732. /**
  56733. * Set the motor values.
  56734. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56735. * @param {number} force the force to apply
  56736. * @param {number} maxForce max force for this motor.
  56737. */
  56738. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  56739. this._physicsPlugin.setMotor(this, force, maxForce);
  56740. };
  56741. /**
  56742. * Set the motor's limits.
  56743. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56744. */
  56745. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  56746. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  56747. };
  56748. return MotorEnabledJoint;
  56749. }(PhysicsJoint));
  56750. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  56751. /**
  56752. * This class represents a single hinge physics joint
  56753. */
  56754. var HingeJoint = (function (_super) {
  56755. __extends(HingeJoint, _super);
  56756. function HingeJoint(jointData) {
  56757. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  56758. }
  56759. /**
  56760. * Set the motor values.
  56761. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56762. * @param {number} force the force to apply
  56763. * @param {number} maxForce max force for this motor.
  56764. */
  56765. HingeJoint.prototype.setMotor = function (force, maxForce) {
  56766. this._physicsPlugin.setMotor(this, force, maxForce);
  56767. };
  56768. /**
  56769. * Set the motor's limits.
  56770. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56771. */
  56772. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  56773. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  56774. };
  56775. return HingeJoint;
  56776. }(MotorEnabledJoint));
  56777. BABYLON.HingeJoint = HingeJoint;
  56778. /**
  56779. * This class represents a dual hinge physics joint (same as wheel joint)
  56780. */
  56781. var Hinge2Joint = (function (_super) {
  56782. __extends(Hinge2Joint, _super);
  56783. function Hinge2Joint(jointData) {
  56784. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  56785. }
  56786. /**
  56787. * Set the motor values.
  56788. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56789. * @param {number} force the force to apply
  56790. * @param {number} maxForce max force for this motor.
  56791. * @param {motorIndex} the motor's index, 0 or 1.
  56792. */
  56793. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  56794. if (motorIndex === void 0) { motorIndex = 0; }
  56795. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  56796. };
  56797. /**
  56798. * Set the motor limits.
  56799. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56800. * @param {number} upperLimit the upper limit
  56801. * @param {number} lowerLimit lower limit
  56802. * @param {motorIndex} the motor's index, 0 or 1.
  56803. */
  56804. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  56805. if (motorIndex === void 0) { motorIndex = 0; }
  56806. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  56807. };
  56808. return Hinge2Joint;
  56809. }(MotorEnabledJoint));
  56810. BABYLON.Hinge2Joint = Hinge2Joint;
  56811. })(BABYLON || (BABYLON = {}));
  56812. //# sourceMappingURL=babylon.physicsJoint.js.map
  56813. var BABYLON;
  56814. (function (BABYLON) {
  56815. var PhysicsImpostor = (function () {
  56816. function PhysicsImpostor(object, type, _options, _scene) {
  56817. if (_options === void 0) { _options = { mass: 0 }; }
  56818. var _this = this;
  56819. this.object = object;
  56820. this.type = type;
  56821. this._options = _options;
  56822. this._scene = _scene;
  56823. this._bodyUpdateRequired = false;
  56824. this._onBeforePhysicsStepCallbacks = new Array();
  56825. this._onAfterPhysicsStepCallbacks = new Array();
  56826. this._onPhysicsCollideCallbacks = [];
  56827. this._deltaPosition = BABYLON.Vector3.Zero();
  56828. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  56829. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  56830. /**
  56831. * this function is executed by the physics engine.
  56832. */
  56833. this.beforeStep = function () {
  56834. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  56835. //conjugate deltaRotation
  56836. if (_this._deltaRotationConjugated) {
  56837. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  56838. }
  56839. else {
  56840. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  56841. }
  56842. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  56843. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  56844. func(_this);
  56845. });
  56846. };
  56847. /**
  56848. * this function is executed by the physics engine.
  56849. */
  56850. this.afterStep = function () {
  56851. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  56852. func(_this);
  56853. });
  56854. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  56855. _this.object.position.addInPlace(_this._deltaPosition);
  56856. if (_this._deltaRotation) {
  56857. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  56858. }
  56859. };
  56860. /**
  56861. * Legacy collision detection event support
  56862. */
  56863. this.onCollideEvent = null;
  56864. //event and body object due to cannon's event-based architecture.
  56865. this.onCollide = function (e) {
  56866. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  56867. return;
  56868. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  56869. if (otherImpostor) {
  56870. // Legacy collision detection event support
  56871. if (_this.onCollideEvent) {
  56872. _this.onCollideEvent(_this, otherImpostor);
  56873. }
  56874. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  56875. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  56876. }).forEach(function (obj) {
  56877. obj.callback(_this, otherImpostor);
  56878. });
  56879. }
  56880. };
  56881. //sanity check!
  56882. if (!this.object) {
  56883. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  56884. return;
  56885. }
  56886. //legacy support for old syntax.
  56887. if (!this._scene && object.getScene) {
  56888. this._scene = object.getScene();
  56889. }
  56890. this._physicsEngine = this._scene.getPhysicsEngine();
  56891. if (!this._physicsEngine) {
  56892. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  56893. }
  56894. else {
  56895. //set the object's quaternion, if not set
  56896. if (!this.object.rotationQuaternion) {
  56897. if (this.object.rotation) {
  56898. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  56899. }
  56900. else {
  56901. this.object.rotationQuaternion = new BABYLON.Quaternion();
  56902. }
  56903. }
  56904. //default options params
  56905. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  56906. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  56907. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  56908. this._joints = [];
  56909. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  56910. if (!this.object.parent) {
  56911. this._init();
  56912. }
  56913. else if (this.object.parent.physicsImpostor) {
  56914. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  56915. }
  56916. }
  56917. }
  56918. /**
  56919. * This function will completly initialize this impostor.
  56920. * It will create a new body - but only if this mesh has no parent.
  56921. * If it has, this impostor will not be used other than to define the impostor
  56922. * of the child mesh.
  56923. */
  56924. PhysicsImpostor.prototype._init = function () {
  56925. this._physicsEngine.removeImpostor(this);
  56926. this.physicsBody = null;
  56927. this._parent = this._parent || this._getPhysicsParent();
  56928. if (!this.parent) {
  56929. this._physicsEngine.addImpostor(this);
  56930. }
  56931. };
  56932. PhysicsImpostor.prototype._getPhysicsParent = function () {
  56933. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  56934. var parentMesh = this.object.parent;
  56935. return parentMesh.physicsImpostor;
  56936. }
  56937. return;
  56938. };
  56939. /**
  56940. * Should a new body be generated.
  56941. */
  56942. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  56943. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  56944. };
  56945. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  56946. this.forceUpdate();
  56947. };
  56948. /**
  56949. * Force a regeneration of this or the parent's impostor's body.
  56950. * Use under cautious - This will remove all joints already implemented.
  56951. */
  56952. PhysicsImpostor.prototype.forceUpdate = function () {
  56953. this._init();
  56954. if (this.parent) {
  56955. this.parent.forceUpdate();
  56956. }
  56957. };
  56958. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  56959. /*public get mesh(): AbstractMesh {
  56960. return this._mesh;
  56961. }*/
  56962. /**
  56963. * Gets the body that holds this impostor. Either its own, or its parent.
  56964. */
  56965. get: function () {
  56966. return this._parent ? this._parent.physicsBody : this._physicsBody;
  56967. },
  56968. /**
  56969. * Set the physics body. Used mainly by the physics engine/plugin
  56970. */
  56971. set: function (physicsBody) {
  56972. if (this._physicsBody) {
  56973. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  56974. }
  56975. this._physicsBody = physicsBody;
  56976. this.resetUpdateFlags();
  56977. },
  56978. enumerable: true,
  56979. configurable: true
  56980. });
  56981. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  56982. get: function () {
  56983. return this._parent;
  56984. },
  56985. set: function (value) {
  56986. this._parent = value;
  56987. },
  56988. enumerable: true,
  56989. configurable: true
  56990. });
  56991. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  56992. this._bodyUpdateRequired = false;
  56993. };
  56994. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  56995. if (this.object.getBoundingInfo) {
  56996. var q = this.object.rotationQuaternion;
  56997. //reset rotation
  56998. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  56999. //calculate the world matrix with no rotation
  57000. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  57001. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  57002. //bring back the rotation
  57003. this.object.rotationQuaternion = q;
  57004. //calculate the world matrix with the new rotation
  57005. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  57006. return size;
  57007. }
  57008. else {
  57009. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  57010. }
  57011. };
  57012. PhysicsImpostor.prototype.getObjectCenter = function () {
  57013. if (this.object.getBoundingInfo) {
  57014. return this.object.getBoundingInfo().boundingBox.centerWorld;
  57015. }
  57016. else {
  57017. return this.object.position;
  57018. }
  57019. };
  57020. /**
  57021. * Get a specific parametes from the options parameter.
  57022. */
  57023. PhysicsImpostor.prototype.getParam = function (paramName) {
  57024. return this._options[paramName];
  57025. };
  57026. /**
  57027. * Sets a specific parameter in the options given to the physics plugin
  57028. */
  57029. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  57030. this._options[paramName] = value;
  57031. this._bodyUpdateRequired = true;
  57032. };
  57033. /**
  57034. * Specifically change the body's mass option. Won't recreate the physics body object
  57035. */
  57036. PhysicsImpostor.prototype.setMass = function (mass) {
  57037. if (this.getParam("mass") !== mass) {
  57038. this.setParam("mass", mass);
  57039. }
  57040. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  57041. };
  57042. PhysicsImpostor.prototype.getLinearVelocity = function () {
  57043. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  57044. };
  57045. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  57046. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  57047. };
  57048. PhysicsImpostor.prototype.getAngularVelocity = function () {
  57049. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  57050. };
  57051. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  57052. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  57053. };
  57054. /**
  57055. * Execute a function with the physics plugin native code.
  57056. * Provide a function the will have two variables - the world object and the physics body object.
  57057. */
  57058. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  57059. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  57060. };
  57061. /**
  57062. * Register a function that will be executed before the physics world is stepping forward.
  57063. */
  57064. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  57065. this._onBeforePhysicsStepCallbacks.push(func);
  57066. };
  57067. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  57068. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  57069. if (index > -1) {
  57070. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  57071. }
  57072. else {
  57073. BABYLON.Tools.Warn("Function to remove was not found");
  57074. }
  57075. };
  57076. /**
  57077. * Register a function that will be executed after the physics step
  57078. */
  57079. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  57080. this._onAfterPhysicsStepCallbacks.push(func);
  57081. };
  57082. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  57083. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  57084. if (index > -1) {
  57085. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  57086. }
  57087. else {
  57088. BABYLON.Tools.Warn("Function to remove was not found");
  57089. }
  57090. };
  57091. /**
  57092. * register a function that will be executed when this impostor collides against a different body.
  57093. */
  57094. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  57095. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  57096. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  57097. };
  57098. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  57099. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  57100. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  57101. if (index > -1) {
  57102. this._onPhysicsCollideCallbacks.splice(index, 1);
  57103. }
  57104. else {
  57105. BABYLON.Tools.Warn("Function to remove was not found");
  57106. }
  57107. };
  57108. /**
  57109. * Apply a force
  57110. */
  57111. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  57112. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  57113. };
  57114. /**
  57115. * Apply an impulse
  57116. */
  57117. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  57118. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  57119. };
  57120. /**
  57121. * A help function to create a joint.
  57122. */
  57123. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  57124. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  57125. this.addJoint(otherImpostor, joint);
  57126. };
  57127. /**
  57128. * Add a joint to this impostor with a different impostor.
  57129. */
  57130. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  57131. this._joints.push({
  57132. otherImpostor: otherImpostor,
  57133. joint: joint
  57134. });
  57135. this._physicsEngine.addJoint(this, otherImpostor, joint);
  57136. };
  57137. /**
  57138. * Will keep this body still, in a sleep mode.
  57139. */
  57140. PhysicsImpostor.prototype.sleep = function () {
  57141. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  57142. };
  57143. /**
  57144. * Wake the body up.
  57145. */
  57146. PhysicsImpostor.prototype.wakeUp = function () {
  57147. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  57148. };
  57149. PhysicsImpostor.prototype.clone = function (newObject) {
  57150. if (!newObject)
  57151. return null;
  57152. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  57153. };
  57154. PhysicsImpostor.prototype.dispose = function () {
  57155. var _this = this;
  57156. //no dispose if no physics engine is available.
  57157. if (!this._physicsEngine) {
  57158. return;
  57159. }
  57160. this._joints.forEach(function (j) {
  57161. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  57162. });
  57163. //dispose the physics body
  57164. this._physicsEngine.removeImpostor(this);
  57165. if (this.parent) {
  57166. this.parent.forceUpdate();
  57167. }
  57168. else {
  57169. /*this._object.getChildMeshes().forEach(function(mesh) {
  57170. if (mesh.physicsImpostor) {
  57171. if (disposeChildren) {
  57172. mesh.physicsImpostor.dispose();
  57173. mesh.physicsImpostor = null;
  57174. }
  57175. }
  57176. })*/
  57177. }
  57178. };
  57179. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  57180. this._deltaPosition.copyFrom(position);
  57181. };
  57182. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  57183. if (!this._deltaRotation) {
  57184. this._deltaRotation = new BABYLON.Quaternion();
  57185. }
  57186. this._deltaRotation.copyFrom(rotation);
  57187. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  57188. };
  57189. return PhysicsImpostor;
  57190. }());
  57191. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  57192. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  57193. //Impostor types
  57194. PhysicsImpostor.NoImpostor = 0;
  57195. PhysicsImpostor.SphereImpostor = 1;
  57196. PhysicsImpostor.BoxImpostor = 2;
  57197. PhysicsImpostor.PlaneImpostor = 3;
  57198. PhysicsImpostor.MeshImpostor = 4;
  57199. PhysicsImpostor.CylinderImpostor = 7;
  57200. PhysicsImpostor.ParticleImpostor = 8;
  57201. PhysicsImpostor.HeightmapImpostor = 9;
  57202. BABYLON.PhysicsImpostor = PhysicsImpostor;
  57203. })(BABYLON || (BABYLON = {}));
  57204. //# sourceMappingURL=babylon.physicsImpostor.js.map
  57205. var BABYLON;
  57206. (function (BABYLON) {
  57207. var PhysicsEngine = (function () {
  57208. function PhysicsEngine(gravity, _physicsPlugin) {
  57209. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  57210. this._physicsPlugin = _physicsPlugin;
  57211. //new methods and parameters
  57212. this._impostors = [];
  57213. this._joints = [];
  57214. if (!this._physicsPlugin.isSupported()) {
  57215. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  57216. + "Please make sure it is included.");
  57217. }
  57218. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  57219. this.setGravity(gravity);
  57220. this.setTimeStep();
  57221. }
  57222. PhysicsEngine.prototype.setGravity = function (gravity) {
  57223. this.gravity = gravity;
  57224. this._physicsPlugin.setGravity(this.gravity);
  57225. };
  57226. /**
  57227. * Set the time step of the physics engine.
  57228. * default is 1/60.
  57229. * To slow it down, enter 1/600 for example.
  57230. * To speed it up, 1/30
  57231. * @param {number} newTimeStep the new timestep to apply to this world.
  57232. */
  57233. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  57234. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  57235. this._physicsPlugin.setTimeStep(newTimeStep);
  57236. };
  57237. PhysicsEngine.prototype.dispose = function () {
  57238. this._impostors.forEach(function (impostor) {
  57239. impostor.dispose();
  57240. });
  57241. this._physicsPlugin.dispose();
  57242. };
  57243. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  57244. return this._physicsPlugin.name;
  57245. };
  57246. /**
  57247. * Adding a new impostor for the impostor tracking.
  57248. * This will be done by the impostor itself.
  57249. * @param {PhysicsImpostor} impostor the impostor to add
  57250. */
  57251. PhysicsEngine.prototype.addImpostor = function (impostor) {
  57252. impostor.uniqueId = this._impostors.push(impostor);
  57253. //if no parent, generate the body
  57254. if (!impostor.parent) {
  57255. this._physicsPlugin.generatePhysicsBody(impostor);
  57256. }
  57257. };
  57258. /**
  57259. * Remove an impostor from the engine.
  57260. * This impostor and its mesh will not longer be updated by the physics engine.
  57261. * @param {PhysicsImpostor} impostor the impostor to remove
  57262. */
  57263. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  57264. var index = this._impostors.indexOf(impostor);
  57265. if (index > -1) {
  57266. var removed = this._impostors.splice(index, 1);
  57267. //Is it needed?
  57268. if (removed.length) {
  57269. //this will also remove it from the world.
  57270. removed[0].physicsBody = null;
  57271. }
  57272. }
  57273. };
  57274. /**
  57275. * Add a joint to the physics engine
  57276. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  57277. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  57278. * @param {PhysicsJoint} the joint that will connect both impostors.
  57279. */
  57280. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  57281. var impostorJoint = {
  57282. mainImpostor: mainImpostor,
  57283. connectedImpostor: connectedImpostor,
  57284. joint: joint
  57285. };
  57286. joint.physicsPlugin = this._physicsPlugin;
  57287. this._joints.push(impostorJoint);
  57288. this._physicsPlugin.generateJoint(impostorJoint);
  57289. };
  57290. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  57291. var matchingJoints = this._joints.filter(function (impostorJoint) {
  57292. return (impostorJoint.connectedImpostor === connectedImpostor
  57293. && impostorJoint.joint === joint
  57294. && impostorJoint.mainImpostor === mainImpostor);
  57295. });
  57296. if (matchingJoints.length) {
  57297. this._physicsPlugin.removeJoint(matchingJoints[0]);
  57298. //TODO remove it from the list as well
  57299. }
  57300. };
  57301. /**
  57302. * Called by the scene. no need to call it.
  57303. */
  57304. PhysicsEngine.prototype._step = function (delta) {
  57305. var _this = this;
  57306. //check if any mesh has no body / requires an update
  57307. this._impostors.forEach(function (impostor) {
  57308. if (impostor.isBodyInitRequired()) {
  57309. _this._physicsPlugin.generatePhysicsBody(impostor);
  57310. }
  57311. });
  57312. if (delta > 0.1) {
  57313. delta = 0.1;
  57314. }
  57315. else if (delta <= 0) {
  57316. delta = 1.0 / 60.0;
  57317. }
  57318. this._physicsPlugin.executeStep(delta, this._impostors);
  57319. };
  57320. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  57321. return this._physicsPlugin;
  57322. };
  57323. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  57324. for (var i = 0; i < this._impostors.length; ++i) {
  57325. if (this._impostors[i].object === object) {
  57326. return this._impostors[i];
  57327. }
  57328. }
  57329. };
  57330. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  57331. for (var i = 0; i < this._impostors.length; ++i) {
  57332. if (this._impostors[i].physicsBody === body) {
  57333. return this._impostors[i];
  57334. }
  57335. }
  57336. };
  57337. return PhysicsEngine;
  57338. }());
  57339. // Statics
  57340. PhysicsEngine.Epsilon = 0.001;
  57341. BABYLON.PhysicsEngine = PhysicsEngine;
  57342. })(BABYLON || (BABYLON = {}));
  57343. //# sourceMappingURL=babylon.physicsEngine.js.map
  57344. var BABYLON;
  57345. (function (BABYLON) {
  57346. var CannonJSPlugin = (function () {
  57347. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  57348. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  57349. if (iterations === void 0) { iterations = 10; }
  57350. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  57351. this.name = "CannonJSPlugin";
  57352. this._physicsMaterials = [];
  57353. this._fixedTimeStep = 1 / 60;
  57354. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  57355. this._currentCollisionGroup = 2;
  57356. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  57357. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  57358. this._tmpPosition = BABYLON.Vector3.Zero();
  57359. this._tmpQuaternion = new BABYLON.Quaternion();
  57360. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  57361. this._tmpDeltaRotation = new BABYLON.Quaternion();
  57362. this._tmpUnityRotation = new BABYLON.Quaternion();
  57363. if (!this.isSupported()) {
  57364. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  57365. return;
  57366. }
  57367. this.world = new CANNON.World();
  57368. this.world.broadphase = new CANNON.NaiveBroadphase();
  57369. this.world.solver.iterations = iterations;
  57370. }
  57371. CannonJSPlugin.prototype.setGravity = function (gravity) {
  57372. this.world.gravity.copy(gravity);
  57373. };
  57374. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  57375. this._fixedTimeStep = timeStep;
  57376. };
  57377. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  57378. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  57379. };
  57380. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  57381. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  57382. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  57383. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  57384. };
  57385. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  57386. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  57387. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  57388. impostor.physicsBody.applyForce(impulse, worldPoint);
  57389. };
  57390. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  57391. //parent-child relationship. Does this impostor has a parent impostor?
  57392. if (impostor.parent) {
  57393. if (impostor.physicsBody) {
  57394. this.removePhysicsBody(impostor);
  57395. //TODO is that needed?
  57396. impostor.forceUpdate();
  57397. }
  57398. return;
  57399. }
  57400. //should a new body be created for this impostor?
  57401. if (impostor.isBodyInitRequired()) {
  57402. var shape = this._createShape(impostor);
  57403. //unregister events, if body is being changed
  57404. var oldBody = impostor.physicsBody;
  57405. if (oldBody) {
  57406. this.removePhysicsBody(impostor);
  57407. }
  57408. //create the body and material
  57409. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  57410. var bodyCreationObject = {
  57411. mass: impostor.getParam("mass"),
  57412. material: material
  57413. };
  57414. // A simple extend, in case native options were used.
  57415. var nativeOptions = impostor.getParam("nativeOptions");
  57416. for (var key in nativeOptions) {
  57417. if (nativeOptions.hasOwnProperty(key)) {
  57418. bodyCreationObject[key] = nativeOptions[key];
  57419. }
  57420. }
  57421. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  57422. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  57423. this.world.addEventListener("preStep", impostor.beforeStep);
  57424. this.world.addEventListener("postStep", impostor.afterStep);
  57425. impostor.physicsBody.addShape(shape);
  57426. this.world.add(impostor.physicsBody);
  57427. //try to keep the body moving in the right direction by taking old properties.
  57428. //Should be tested!
  57429. if (oldBody) {
  57430. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  57431. impostor.physicsBody[param].copy(oldBody[param]);
  57432. });
  57433. }
  57434. this._processChildMeshes(impostor);
  57435. }
  57436. //now update the body's transformation
  57437. this._updatePhysicsBodyTransformation(impostor);
  57438. };
  57439. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  57440. var _this = this;
  57441. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  57442. if (meshChildren.length) {
  57443. var processMesh = function (localPosition, mesh) {
  57444. var childImpostor = mesh.getPhysicsImpostor();
  57445. if (childImpostor) {
  57446. var parent = childImpostor.parent;
  57447. if (parent !== mainImpostor) {
  57448. var localPosition = mesh.position;
  57449. if (childImpostor.physicsBody) {
  57450. _this.removePhysicsBody(childImpostor);
  57451. childImpostor.physicsBody = null;
  57452. }
  57453. childImpostor.parent = mainImpostor;
  57454. childImpostor.resetUpdateFlags();
  57455. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  57456. //Add the mass of the children.
  57457. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  57458. }
  57459. }
  57460. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  57461. };
  57462. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  57463. }
  57464. };
  57465. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  57466. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  57467. this.world.removeEventListener("preStep", impostor.beforeStep);
  57468. this.world.removeEventListener("postStep", impostor.afterStep);
  57469. this.world.remove(impostor.physicsBody);
  57470. };
  57471. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  57472. var mainBody = impostorJoint.mainImpostor.physicsBody;
  57473. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  57474. if (!mainBody || !connectedBody) {
  57475. return;
  57476. }
  57477. var constraint;
  57478. var jointData = impostorJoint.joint.jointData;
  57479. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  57480. var constraintData = {
  57481. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  57482. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  57483. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  57484. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  57485. maxForce: jointData.nativeParams.maxForce,
  57486. collideConnected: !!jointData.collision
  57487. };
  57488. switch (impostorJoint.joint.type) {
  57489. case BABYLON.PhysicsJoint.HingeJoint:
  57490. case BABYLON.PhysicsJoint.Hinge2Joint:
  57491. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  57492. break;
  57493. case BABYLON.PhysicsJoint.DistanceJoint:
  57494. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  57495. break;
  57496. case BABYLON.PhysicsJoint.SpringJoint:
  57497. var springData = jointData;
  57498. constraint = new CANNON.Spring(mainBody, connectedBody, {
  57499. restLength: springData.length,
  57500. stiffness: springData.stiffness,
  57501. damping: springData.damping,
  57502. localAnchorA: constraintData.pivotA,
  57503. localAnchorB: constraintData.pivotB
  57504. });
  57505. break;
  57506. case BABYLON.PhysicsJoint.LockJoint:
  57507. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  57508. break;
  57509. case BABYLON.PhysicsJoint.PointToPointJoint:
  57510. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  57511. default:
  57512. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  57513. break;
  57514. }
  57515. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  57516. constraint.collideConnected = !!jointData.collision;
  57517. impostorJoint.joint.physicsJoint = constraint;
  57518. //don't add spring as constraint, as it is not one.
  57519. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  57520. this.world.addConstraint(constraint);
  57521. }
  57522. else {
  57523. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  57524. constraint.applyForce();
  57525. });
  57526. }
  57527. };
  57528. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  57529. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  57530. };
  57531. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  57532. var index;
  57533. var mat;
  57534. for (index = 0; index < this._physicsMaterials.length; index++) {
  57535. mat = this._physicsMaterials[index];
  57536. if (mat.friction === friction && mat.restitution === restitution) {
  57537. return mat;
  57538. }
  57539. }
  57540. var currentMat = new CANNON.Material(name);
  57541. currentMat.friction = friction;
  57542. currentMat.restitution = restitution;
  57543. this._physicsMaterials.push(currentMat);
  57544. return currentMat;
  57545. };
  57546. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  57547. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  57548. };
  57549. CannonJSPlugin.prototype._createShape = function (impostor) {
  57550. var object = impostor.object;
  57551. var returnValue;
  57552. var extendSize = impostor.getObjectExtendSize();
  57553. switch (impostor.type) {
  57554. case BABYLON.PhysicsImpostor.SphereImpostor:
  57555. var radiusX = extendSize.x;
  57556. var radiusY = extendSize.y;
  57557. var radiusZ = extendSize.z;
  57558. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  57559. break;
  57560. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  57561. case BABYLON.PhysicsImpostor.CylinderImpostor:
  57562. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  57563. break;
  57564. case BABYLON.PhysicsImpostor.BoxImpostor:
  57565. var box = extendSize.scale(0.5);
  57566. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  57567. break;
  57568. case BABYLON.PhysicsImpostor.PlaneImpostor:
  57569. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  57570. returnValue = new CANNON.Plane();
  57571. break;
  57572. case BABYLON.PhysicsImpostor.MeshImpostor:
  57573. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  57574. var rawFaces = object.getIndices ? object.getIndices() : [];
  57575. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  57576. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  57577. break;
  57578. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  57579. returnValue = this._createHeightmap(object);
  57580. break;
  57581. case BABYLON.PhysicsImpostor.ParticleImpostor:
  57582. returnValue = new CANNON.Particle();
  57583. break;
  57584. }
  57585. return returnValue;
  57586. };
  57587. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  57588. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57589. var matrix = [];
  57590. //For now pointDepth will not be used and will be automatically calculated.
  57591. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  57592. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  57593. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  57594. var elementSize = dim * 2 / arraySize;
  57595. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  57596. for (var i = 0; i < pos.length; i = i + 3) {
  57597. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  57598. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  57599. var y = pos[i + 1] + minY;
  57600. if (!matrix[x]) {
  57601. matrix[x] = [];
  57602. }
  57603. if (!matrix[x][z]) {
  57604. matrix[x][z] = y;
  57605. }
  57606. matrix[x][z] = Math.max(y, matrix[x][z]);
  57607. }
  57608. for (var x = 0; x <= arraySize; ++x) {
  57609. if (!matrix[x]) {
  57610. var loc = 1;
  57611. while (!matrix[(x + loc) % arraySize]) {
  57612. loc++;
  57613. }
  57614. matrix[x] = matrix[(x + loc) % arraySize].slice();
  57615. //console.log("missing x", x);
  57616. }
  57617. for (var z = 0; z <= arraySize; ++z) {
  57618. if (!matrix[x][z]) {
  57619. var loc = 1;
  57620. var newValue;
  57621. while (newValue === undefined) {
  57622. newValue = matrix[x][(z + loc++) % arraySize];
  57623. }
  57624. matrix[x][z] = newValue;
  57625. }
  57626. }
  57627. }
  57628. var shape = new CANNON.Heightfield(matrix, {
  57629. elementSize: elementSize
  57630. });
  57631. //For future reference, needed for body transformation
  57632. shape.minY = minY;
  57633. return shape;
  57634. };
  57635. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  57636. var object = impostor.object;
  57637. //make sure it is updated...
  57638. object.computeWorldMatrix && object.computeWorldMatrix(true);
  57639. // The delta between the mesh position and the mesh bounding box center
  57640. var center = impostor.getObjectCenter();
  57641. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  57642. this._tmpPosition.copyFrom(center);
  57643. var quaternion = object.rotationQuaternion;
  57644. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  57645. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  57646. //-90 DEG in X, precalculated
  57647. quaternion = quaternion.multiply(this._minus90X);
  57648. //Invert! (Precalculated, 90 deg in X)
  57649. //No need to clone. this will never change.
  57650. impostor.setDeltaRotation(this._plus90X);
  57651. }
  57652. //If it is a heightfield, if should be centered.
  57653. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  57654. var mesh = object;
  57655. //calculate the correct body position:
  57656. var rotationQuaternion = mesh.rotationQuaternion;
  57657. mesh.rotationQuaternion = this._tmpUnityRotation;
  57658. mesh.computeWorldMatrix(true);
  57659. //get original center with no rotation
  57660. var c = center.clone();
  57661. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  57662. //rotation is back
  57663. mesh.rotationQuaternion = rotationQuaternion;
  57664. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  57665. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  57666. mesh.setPivotMatrix(p);
  57667. mesh.computeWorldMatrix(true);
  57668. //calculate the translation
  57669. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  57670. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  57671. //add it inverted to the delta
  57672. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  57673. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  57674. mesh.setPivotMatrix(oldPivot);
  57675. mesh.computeWorldMatrix(true);
  57676. }
  57677. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  57678. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  57679. this._tmpPosition.copyFrom(object.position);
  57680. }
  57681. impostor.setDeltaPosition(this._tmpDeltaPosition);
  57682. //Now update the impostor object
  57683. impostor.physicsBody.position.copy(this._tmpPosition);
  57684. impostor.physicsBody.quaternion.copy(quaternion);
  57685. };
  57686. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  57687. impostor.object.position.copyFrom(impostor.physicsBody.position);
  57688. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  57689. };
  57690. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  57691. impostor.physicsBody.position.copy(newPosition);
  57692. impostor.physicsBody.quaternion.copy(newRotation);
  57693. };
  57694. CannonJSPlugin.prototype.isSupported = function () {
  57695. return window.CANNON !== undefined;
  57696. };
  57697. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  57698. impostor.physicsBody.velocity.copy(velocity);
  57699. };
  57700. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  57701. impostor.physicsBody.angularVelocity.copy(velocity);
  57702. };
  57703. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  57704. var v = impostor.physicsBody.velocity;
  57705. if (!v)
  57706. return null;
  57707. return new BABYLON.Vector3(v.x, v.y, v.z);
  57708. };
  57709. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  57710. var v = impostor.physicsBody.angularVelocity;
  57711. if (!v)
  57712. return null;
  57713. return new BABYLON.Vector3(v.x, v.y, v.z);
  57714. };
  57715. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  57716. impostor.physicsBody.mass = mass;
  57717. impostor.physicsBody.updateMassProperties();
  57718. };
  57719. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  57720. impostor.physicsBody.sleep();
  57721. };
  57722. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  57723. impostor.physicsBody.wakeUp();
  57724. };
  57725. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  57726. joint.physicsJoint.distance = maxDistance;
  57727. };
  57728. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  57729. if (!motorIndex) {
  57730. joint.physicsJoint.enableMotor();
  57731. }
  57732. };
  57733. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  57734. if (!motorIndex) {
  57735. joint.physicsJoint.disableMotor();
  57736. }
  57737. };
  57738. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  57739. if (!motorIndex) {
  57740. joint.physicsJoint.enableMotor();
  57741. joint.physicsJoint.setMotorSpeed(speed);
  57742. if (maxForce) {
  57743. this.setLimit(joint, maxForce);
  57744. }
  57745. }
  57746. };
  57747. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  57748. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  57749. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  57750. };
  57751. CannonJSPlugin.prototype.dispose = function () {
  57752. //nothing to do, actually.
  57753. };
  57754. return CannonJSPlugin;
  57755. }());
  57756. BABYLON.CannonJSPlugin = CannonJSPlugin;
  57757. })(BABYLON || (BABYLON = {}));
  57758. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  57759. var BABYLON;
  57760. (function (BABYLON) {
  57761. var OimoJSPlugin = (function () {
  57762. function OimoJSPlugin(iterations) {
  57763. this.name = "OimoJSPlugin";
  57764. this._tmpImpostorsArray = [];
  57765. this._tmpPositionVector = BABYLON.Vector3.Zero();
  57766. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  57767. this.world.worldscale(1);
  57768. this.world.clear();
  57769. //making sure no stats are calculated
  57770. this.world.isNoStat = true;
  57771. }
  57772. OimoJSPlugin.prototype.setGravity = function (gravity) {
  57773. this.world.gravity.copy(gravity);
  57774. };
  57775. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  57776. this.world.timeStep = timeStep;
  57777. };
  57778. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  57779. var _this = this;
  57780. impostors.forEach(function (impostor) {
  57781. impostor.beforeStep();
  57782. });
  57783. this.world.step();
  57784. impostors.forEach(function (impostor) {
  57785. impostor.afterStep();
  57786. //update the ordered impostors array
  57787. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  57788. });
  57789. //check for collisions
  57790. var contact = this.world.contacts;
  57791. while (contact !== null) {
  57792. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  57793. contact = contact.next;
  57794. continue;
  57795. }
  57796. //is this body colliding with any other? get the impostor
  57797. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  57798. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  57799. if (!mainImpostor || !collidingImpostor) {
  57800. contact = contact.next;
  57801. continue;
  57802. }
  57803. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  57804. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  57805. contact = contact.next;
  57806. }
  57807. };
  57808. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  57809. var mass = impostor.physicsBody.massInfo.mass;
  57810. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  57811. };
  57812. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  57813. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  57814. this.applyImpulse(impostor, force, contactPoint);
  57815. };
  57816. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  57817. var _this = this;
  57818. //parent-child relationship. Does this impostor has a parent impostor?
  57819. if (impostor.parent) {
  57820. if (impostor.physicsBody) {
  57821. this.removePhysicsBody(impostor);
  57822. //TODO is that needed?
  57823. impostor.forceUpdate();
  57824. }
  57825. return;
  57826. }
  57827. if (impostor.isBodyInitRequired()) {
  57828. var bodyConfig = {
  57829. name: impostor.uniqueId,
  57830. //Oimo must have mass, also for static objects.
  57831. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  57832. size: [],
  57833. type: [],
  57834. pos: [],
  57835. rot: [],
  57836. move: impostor.getParam("mass") !== 0,
  57837. //Supporting older versions of Oimo
  57838. world: this.world
  57839. };
  57840. var impostors = [impostor];
  57841. var addToArray = function (parent) {
  57842. if (!parent.getChildMeshes)
  57843. return;
  57844. parent.getChildMeshes().forEach(function (m) {
  57845. if (m.physicsImpostor) {
  57846. impostors.push(m.physicsImpostor);
  57847. m.physicsImpostor._init();
  57848. }
  57849. });
  57850. };
  57851. addToArray(impostor.object);
  57852. var checkWithEpsilon_1 = function (value) {
  57853. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  57854. };
  57855. impostors.forEach(function (i) {
  57856. //get the correct bounding box
  57857. var oldQuaternion = i.object.rotationQuaternion;
  57858. var rot = new OIMO.Euler().setFromQuaternion({
  57859. x: impostor.object.rotationQuaternion.x,
  57860. y: impostor.object.rotationQuaternion.y,
  57861. z: impostor.object.rotationQuaternion.z,
  57862. s: impostor.object.rotationQuaternion.w
  57863. });
  57864. var extendSize = i.getObjectExtendSize();
  57865. if (i === impostor) {
  57866. var center = impostor.getObjectCenter();
  57867. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  57868. //Can also use Array.prototype.push.apply
  57869. bodyConfig.pos.push(center.x);
  57870. bodyConfig.pos.push(center.y);
  57871. bodyConfig.pos.push(center.z);
  57872. //tmp solution
  57873. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  57874. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  57875. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  57876. }
  57877. else {
  57878. bodyConfig.pos.push(i.object.position.x);
  57879. bodyConfig.pos.push(i.object.position.y);
  57880. bodyConfig.pos.push(i.object.position.z);
  57881. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  57882. bodyConfig.rot.push(0);
  57883. bodyConfig.rot.push(0);
  57884. bodyConfig.rot.push(0);
  57885. }
  57886. // register mesh
  57887. switch (i.type) {
  57888. case BABYLON.PhysicsImpostor.ParticleImpostor:
  57889. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  57890. case BABYLON.PhysicsImpostor.SphereImpostor:
  57891. var radiusX = extendSize.x;
  57892. var radiusY = extendSize.y;
  57893. var radiusZ = extendSize.z;
  57894. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  57895. bodyConfig.type.push('sphere');
  57896. //due to the way oimo works with compounds, add 3 times
  57897. bodyConfig.size.push(size);
  57898. bodyConfig.size.push(size);
  57899. bodyConfig.size.push(size);
  57900. break;
  57901. case BABYLON.PhysicsImpostor.CylinderImpostor:
  57902. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  57903. var sizeY = checkWithEpsilon_1(extendSize.y);
  57904. bodyConfig.type.push('cylinder');
  57905. bodyConfig.size.push(sizeX);
  57906. bodyConfig.size.push(sizeY);
  57907. //due to the way oimo works with compounds, add one more value.
  57908. bodyConfig.size.push(sizeY);
  57909. break;
  57910. case BABYLON.PhysicsImpostor.PlaneImpostor:
  57911. case BABYLON.PhysicsImpostor.BoxImpostor:
  57912. default:
  57913. var sizeX = checkWithEpsilon_1(extendSize.x);
  57914. var sizeY = checkWithEpsilon_1(extendSize.y);
  57915. var sizeZ = checkWithEpsilon_1(extendSize.z);
  57916. bodyConfig.type.push('box');
  57917. bodyConfig.size.push(sizeX);
  57918. bodyConfig.size.push(sizeY);
  57919. bodyConfig.size.push(sizeZ);
  57920. break;
  57921. }
  57922. //actually not needed, but hey...
  57923. i.object.rotationQuaternion = oldQuaternion;
  57924. });
  57925. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  57926. }
  57927. else {
  57928. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  57929. }
  57930. impostor.setDeltaPosition(this._tmpPositionVector);
  57931. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  57932. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  57933. };
  57934. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  57935. //impostor.physicsBody.dispose();
  57936. //Same as : (older oimo versions)
  57937. this.world.removeRigidBody(impostor.physicsBody);
  57938. };
  57939. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  57940. var mainBody = impostorJoint.mainImpostor.physicsBody;
  57941. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  57942. if (!mainBody || !connectedBody) {
  57943. return;
  57944. }
  57945. var jointData = impostorJoint.joint.jointData;
  57946. var options = jointData.nativeParams || {};
  57947. var type;
  57948. var nativeJointData = {
  57949. body1: mainBody,
  57950. body2: connectedBody,
  57951. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  57952. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  57953. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  57954. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  57955. min: options.min,
  57956. max: options.max,
  57957. collision: options.collision || jointData.collision,
  57958. spring: options.spring,
  57959. //supporting older version of Oimo
  57960. world: this.world
  57961. };
  57962. switch (impostorJoint.joint.type) {
  57963. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  57964. type = "jointBall";
  57965. break;
  57966. case BABYLON.PhysicsJoint.SpringJoint:
  57967. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  57968. var springData = jointData;
  57969. nativeJointData.min = springData.length || nativeJointData.min;
  57970. //Max should also be set, just make sure it is at least min
  57971. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  57972. case BABYLON.PhysicsJoint.DistanceJoint:
  57973. type = "jointDistance";
  57974. nativeJointData.max = jointData.maxDistance;
  57975. break;
  57976. case BABYLON.PhysicsJoint.PrismaticJoint:
  57977. type = "jointPrisme";
  57978. break;
  57979. case BABYLON.PhysicsJoint.SliderJoint:
  57980. type = "jointSlide";
  57981. break;
  57982. case BABYLON.PhysicsJoint.WheelJoint:
  57983. type = "jointWheel";
  57984. break;
  57985. case BABYLON.PhysicsJoint.HingeJoint:
  57986. default:
  57987. type = "jointHinge";
  57988. break;
  57989. }
  57990. nativeJointData.type = type;
  57991. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  57992. };
  57993. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  57994. //Bug in Oimo prevents us from disposing a joint in the playground
  57995. //joint.joint.physicsJoint.dispose();
  57996. //So we will bruteforce it!
  57997. try {
  57998. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  57999. }
  58000. catch (e) {
  58001. BABYLON.Tools.Warn(e);
  58002. }
  58003. };
  58004. OimoJSPlugin.prototype.isSupported = function () {
  58005. return OIMO !== undefined;
  58006. };
  58007. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  58008. if (!impostor.physicsBody.sleeping) {
  58009. //TODO check that
  58010. if (impostor.physicsBody.shapes.next) {
  58011. var parentShape = this._getLastShape(impostor.physicsBody);
  58012. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  58013. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  58014. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  58015. }
  58016. else {
  58017. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  58018. }
  58019. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  58020. impostor.object.rotationQuaternion.normalize();
  58021. }
  58022. };
  58023. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  58024. var body = impostor.physicsBody;
  58025. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  58026. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  58027. body.syncShapes();
  58028. body.awake();
  58029. };
  58030. OimoJSPlugin.prototype._getLastShape = function (body) {
  58031. var lastShape = body.shapes;
  58032. while (lastShape.next) {
  58033. lastShape = lastShape.next;
  58034. }
  58035. return lastShape;
  58036. };
  58037. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  58038. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  58039. };
  58040. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  58041. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  58042. };
  58043. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  58044. var v = impostor.physicsBody.linearVelocity;
  58045. if (!v)
  58046. return null;
  58047. return new BABYLON.Vector3(v.x, v.y, v.z);
  58048. };
  58049. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  58050. var v = impostor.physicsBody.angularVelocity;
  58051. if (!v)
  58052. return null;
  58053. return new BABYLON.Vector3(v.x, v.y, v.z);
  58054. };
  58055. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  58056. var staticBody = mass === 0;
  58057. //this will actually set the body's density and not its mass.
  58058. //But this is how oimo treats the mass variable.
  58059. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  58060. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  58061. };
  58062. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  58063. impostor.physicsBody.sleep();
  58064. };
  58065. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  58066. impostor.physicsBody.awake();
  58067. };
  58068. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  58069. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  58070. if (minDistance !== void 0) {
  58071. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  58072. }
  58073. };
  58074. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  58075. //TODO separate rotational and transational motors.
  58076. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  58077. if (motor) {
  58078. motor.setMotor(speed, maxForce);
  58079. }
  58080. };
  58081. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  58082. //TODO separate rotational and transational motors.
  58083. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  58084. if (motor) {
  58085. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  58086. }
  58087. };
  58088. OimoJSPlugin.prototype.dispose = function () {
  58089. this.world.clear();
  58090. };
  58091. return OimoJSPlugin;
  58092. }());
  58093. BABYLON.OimoJSPlugin = OimoJSPlugin;
  58094. })(BABYLON || (BABYLON = {}));
  58095. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  58096. var BABYLON;
  58097. (function (BABYLON) {
  58098. var Internals;
  58099. (function (Internals) {
  58100. /*
  58101. * Based on jsTGALoader - Javascript loader for TGA file
  58102. * By Vincent Thibault
  58103. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  58104. */
  58105. var TGATools = (function () {
  58106. function TGATools() {
  58107. }
  58108. TGATools.GetTGAHeader = function (data) {
  58109. var offset = 0;
  58110. var header = {
  58111. id_length: data[offset++],
  58112. colormap_type: data[offset++],
  58113. image_type: data[offset++],
  58114. colormap_index: data[offset++] | data[offset++] << 8,
  58115. colormap_length: data[offset++] | data[offset++] << 8,
  58116. colormap_size: data[offset++],
  58117. origin: [
  58118. data[offset++] | data[offset++] << 8,
  58119. data[offset++] | data[offset++] << 8
  58120. ],
  58121. width: data[offset++] | data[offset++] << 8,
  58122. height: data[offset++] | data[offset++] << 8,
  58123. pixel_size: data[offset++],
  58124. flags: data[offset++]
  58125. };
  58126. return header;
  58127. };
  58128. TGATools.UploadContent = function (gl, data) {
  58129. // Not enough data to contain header ?
  58130. if (data.length < 19) {
  58131. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  58132. return;
  58133. }
  58134. // Read Header
  58135. var offset = 18;
  58136. var header = TGATools.GetTGAHeader(data);
  58137. // Assume it's a valid Targa file.
  58138. if (header.id_length + offset > data.length) {
  58139. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  58140. return;
  58141. }
  58142. // Skip not needed data
  58143. offset += header.id_length;
  58144. var use_rle = false;
  58145. var use_pal = false;
  58146. var use_rgb = false;
  58147. var use_grey = false;
  58148. // Get some informations.
  58149. switch (header.image_type) {
  58150. case TGATools._TYPE_RLE_INDEXED:
  58151. use_rle = true;
  58152. case TGATools._TYPE_INDEXED:
  58153. use_pal = true;
  58154. break;
  58155. case TGATools._TYPE_RLE_RGB:
  58156. use_rle = true;
  58157. case TGATools._TYPE_RGB:
  58158. use_rgb = true;
  58159. break;
  58160. case TGATools._TYPE_RLE_GREY:
  58161. use_rle = true;
  58162. case TGATools._TYPE_GREY:
  58163. use_grey = true;
  58164. break;
  58165. }
  58166. var pixel_data;
  58167. var numAlphaBits = header.flags & 0xf;
  58168. var pixel_size = header.pixel_size >> 3;
  58169. var pixel_total = header.width * header.height * pixel_size;
  58170. // Read palettes
  58171. var palettes;
  58172. if (use_pal) {
  58173. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  58174. }
  58175. // Read LRE
  58176. if (use_rle) {
  58177. pixel_data = new Uint8Array(pixel_total);
  58178. var c, count, i;
  58179. var localOffset = 0;
  58180. var pixels = new Uint8Array(pixel_size);
  58181. while (offset < pixel_total && localOffset < pixel_total) {
  58182. c = data[offset++];
  58183. count = (c & 0x7f) + 1;
  58184. // RLE pixels
  58185. if (c & 0x80) {
  58186. // Bind pixel tmp array
  58187. for (i = 0; i < pixel_size; ++i) {
  58188. pixels[i] = data[offset++];
  58189. }
  58190. // Copy pixel array
  58191. for (i = 0; i < count; ++i) {
  58192. pixel_data.set(pixels, localOffset + i * pixel_size);
  58193. }
  58194. localOffset += pixel_size * count;
  58195. }
  58196. else {
  58197. count *= pixel_size;
  58198. for (i = 0; i < count; ++i) {
  58199. pixel_data[localOffset + i] = data[offset++];
  58200. }
  58201. localOffset += count;
  58202. }
  58203. }
  58204. }
  58205. else {
  58206. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  58207. }
  58208. // Load to texture
  58209. var x_start, y_start, x_step, y_step, y_end, x_end;
  58210. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  58211. default:
  58212. case TGATools._ORIGIN_UL:
  58213. x_start = 0;
  58214. x_step = 1;
  58215. x_end = header.width;
  58216. y_start = 0;
  58217. y_step = 1;
  58218. y_end = header.height;
  58219. break;
  58220. case TGATools._ORIGIN_BL:
  58221. x_start = 0;
  58222. x_step = 1;
  58223. x_end = header.width;
  58224. y_start = header.height - 1;
  58225. y_step = -1;
  58226. y_end = -1;
  58227. break;
  58228. case TGATools._ORIGIN_UR:
  58229. x_start = header.width - 1;
  58230. x_step = -1;
  58231. x_end = -1;
  58232. y_start = 0;
  58233. y_step = 1;
  58234. y_end = header.height;
  58235. break;
  58236. case TGATools._ORIGIN_BR:
  58237. x_start = header.width - 1;
  58238. x_step = -1;
  58239. x_end = -1;
  58240. y_start = header.height - 1;
  58241. y_step = -1;
  58242. y_end = -1;
  58243. break;
  58244. }
  58245. // Load the specify method
  58246. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  58247. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  58248. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  58249. };
  58250. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58251. var image = pixel_data, colormap = palettes;
  58252. var width = header.width, height = header.height;
  58253. var color, i = 0, x, y;
  58254. var imageData = new Uint8Array(width * height * 4);
  58255. for (y = y_start; y !== y_end; y += y_step) {
  58256. for (x = x_start; x !== x_end; x += x_step, i++) {
  58257. color = image[i];
  58258. imageData[(x + width * y) * 4 + 3] = 255;
  58259. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  58260. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  58261. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  58262. }
  58263. }
  58264. return imageData;
  58265. };
  58266. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58267. var image = pixel_data;
  58268. var width = header.width, height = header.height;
  58269. var color, i = 0, x, y;
  58270. var imageData = new Uint8Array(width * height * 4);
  58271. for (y = y_start; y !== y_end; y += y_step) {
  58272. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  58273. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  58274. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  58275. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  58276. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  58277. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  58278. }
  58279. }
  58280. return imageData;
  58281. };
  58282. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58283. var image = pixel_data;
  58284. var width = header.width, height = header.height;
  58285. var i = 0, x, y;
  58286. var imageData = new Uint8Array(width * height * 4);
  58287. for (y = y_start; y !== y_end; y += y_step) {
  58288. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  58289. imageData[(x + width * y) * 4 + 3] = 255;
  58290. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58291. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  58292. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  58293. }
  58294. }
  58295. return imageData;
  58296. };
  58297. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58298. var image = pixel_data;
  58299. var width = header.width, height = header.height;
  58300. var i = 0, x, y;
  58301. var imageData = new Uint8Array(width * height * 4);
  58302. for (y = y_start; y !== y_end; y += y_step) {
  58303. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  58304. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58305. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  58306. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  58307. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  58308. }
  58309. }
  58310. return imageData;
  58311. };
  58312. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58313. var image = pixel_data;
  58314. var width = header.width, height = header.height;
  58315. var color, i = 0, x, y;
  58316. var imageData = new Uint8Array(width * height * 4);
  58317. for (y = y_start; y !== y_end; y += y_step) {
  58318. for (x = x_start; x !== x_end; x += x_step, i++) {
  58319. color = image[i];
  58320. imageData[(x + width * y) * 4 + 0] = color;
  58321. imageData[(x + width * y) * 4 + 1] = color;
  58322. imageData[(x + width * y) * 4 + 2] = color;
  58323. imageData[(x + width * y) * 4 + 3] = 255;
  58324. }
  58325. }
  58326. return imageData;
  58327. };
  58328. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58329. var image = pixel_data;
  58330. var width = header.width, height = header.height;
  58331. var i = 0, x, y;
  58332. var imageData = new Uint8Array(width * height * 4);
  58333. for (y = y_start; y !== y_end; y += y_step) {
  58334. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  58335. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  58336. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  58337. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58338. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  58339. }
  58340. }
  58341. return imageData;
  58342. };
  58343. return TGATools;
  58344. }());
  58345. TGATools._TYPE_NO_DATA = 0;
  58346. TGATools._TYPE_INDEXED = 1;
  58347. TGATools._TYPE_RGB = 2;
  58348. TGATools._TYPE_GREY = 3;
  58349. TGATools._TYPE_RLE_INDEXED = 9;
  58350. TGATools._TYPE_RLE_RGB = 10;
  58351. TGATools._TYPE_RLE_GREY = 11;
  58352. TGATools._ORIGIN_MASK = 0x30;
  58353. TGATools._ORIGIN_SHIFT = 0x04;
  58354. TGATools._ORIGIN_BL = 0x00;
  58355. TGATools._ORIGIN_BR = 0x01;
  58356. TGATools._ORIGIN_UL = 0x02;
  58357. TGATools._ORIGIN_UR = 0x03;
  58358. Internals.TGATools = TGATools;
  58359. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58360. })(BABYLON || (BABYLON = {}));
  58361. //# sourceMappingURL=babylon.tga.js.map
  58362. var BABYLON;
  58363. (function (BABYLON) {
  58364. var Internals;
  58365. (function (Internals) {
  58366. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  58367. // All values and structures referenced from:
  58368. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  58369. var DDS_MAGIC = 0x20534444;
  58370. 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;
  58371. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  58372. 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;
  58373. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  58374. function FourCCToInt32(value) {
  58375. return value.charCodeAt(0) +
  58376. (value.charCodeAt(1) << 8) +
  58377. (value.charCodeAt(2) << 16) +
  58378. (value.charCodeAt(3) << 24);
  58379. }
  58380. function Int32ToFourCC(value) {
  58381. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  58382. }
  58383. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  58384. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  58385. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  58386. var headerLengthInt = 31; // The header length in 32 bit ints
  58387. // Offsets into the header array
  58388. var off_magic = 0;
  58389. var off_size = 1;
  58390. var off_flags = 2;
  58391. var off_height = 3;
  58392. var off_width = 4;
  58393. var off_mipmapCount = 7;
  58394. var off_pfFlags = 20;
  58395. var off_pfFourCC = 21;
  58396. var off_RGBbpp = 22;
  58397. var off_RMask = 23;
  58398. var off_GMask = 24;
  58399. var off_BMask = 25;
  58400. var off_AMask = 26;
  58401. var off_caps1 = 27;
  58402. var off_caps2 = 28;
  58403. ;
  58404. var DDSTools = (function () {
  58405. function DDSTools() {
  58406. }
  58407. DDSTools.GetDDSInfo = function (arrayBuffer) {
  58408. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  58409. var mipmapCount = 1;
  58410. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  58411. mipmapCount = Math.max(1, header[off_mipmapCount]);
  58412. }
  58413. return {
  58414. width: header[off_width],
  58415. height: header[off_height],
  58416. mipmapCount: mipmapCount,
  58417. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  58418. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  58419. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  58420. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  58421. };
  58422. };
  58423. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  58424. var byteArray = new Uint8Array(dataLength);
  58425. var srcData = new Uint8Array(arrayBuffer);
  58426. var index = 0;
  58427. for (var y = height - 1; y >= 0; y--) {
  58428. for (var x = 0; x < width; x++) {
  58429. var srcPos = dataOffset + (x + y * width) * 4;
  58430. byteArray[index + 2] = srcData[srcPos];
  58431. byteArray[index + 1] = srcData[srcPos + 1];
  58432. byteArray[index] = srcData[srcPos + 2];
  58433. byteArray[index + 3] = srcData[srcPos + 3];
  58434. index += 4;
  58435. }
  58436. }
  58437. return byteArray;
  58438. };
  58439. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  58440. var byteArray = new Uint8Array(dataLength);
  58441. var srcData = new Uint8Array(arrayBuffer);
  58442. var index = 0;
  58443. for (var y = height - 1; y >= 0; y--) {
  58444. for (var x = 0; x < width; x++) {
  58445. var srcPos = dataOffset + (x + y * width) * 3;
  58446. byteArray[index + 2] = srcData[srcPos];
  58447. byteArray[index + 1] = srcData[srcPos + 1];
  58448. byteArray[index] = srcData[srcPos + 2];
  58449. index += 3;
  58450. }
  58451. }
  58452. return byteArray;
  58453. };
  58454. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  58455. var byteArray = new Uint8Array(dataLength);
  58456. var srcData = new Uint8Array(arrayBuffer);
  58457. var index = 0;
  58458. for (var y = height - 1; y >= 0; y--) {
  58459. for (var x = 0; x < width; x++) {
  58460. var srcPos = dataOffset + (x + y * width);
  58461. byteArray[index] = srcData[srcPos];
  58462. index++;
  58463. }
  58464. }
  58465. return byteArray;
  58466. };
  58467. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  58468. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  58469. if (header[off_magic] != DDS_MAGIC) {
  58470. BABYLON.Tools.Error("Invalid magic number in DDS header");
  58471. return;
  58472. }
  58473. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  58474. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  58475. return;
  58476. }
  58477. if (info.isFourCC) {
  58478. fourCC = header[off_pfFourCC];
  58479. switch (fourCC) {
  58480. case FOURCC_DXT1:
  58481. blockBytes = 8;
  58482. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  58483. break;
  58484. case FOURCC_DXT3:
  58485. blockBytes = 16;
  58486. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  58487. break;
  58488. case FOURCC_DXT5:
  58489. blockBytes = 16;
  58490. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  58491. break;
  58492. default:
  58493. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  58494. return;
  58495. }
  58496. }
  58497. mipmapCount = 1;
  58498. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  58499. mipmapCount = Math.max(1, header[off_mipmapCount]);
  58500. }
  58501. var bpp = header[off_RGBbpp];
  58502. for (var face = 0; face < faces; face++) {
  58503. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  58504. width = header[off_width];
  58505. height = header[off_height];
  58506. dataOffset = header[off_size] + 4;
  58507. for (i = 0; i < mipmapCount; ++i) {
  58508. if (info.isRGB) {
  58509. if (bpp === 24) {
  58510. dataLength = width * height * 3;
  58511. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  58512. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  58513. }
  58514. else {
  58515. dataLength = width * height * 4;
  58516. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  58517. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  58518. }
  58519. }
  58520. else if (info.isLuminance) {
  58521. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  58522. var unpaddedRowSize = width;
  58523. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  58524. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  58525. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  58526. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  58527. }
  58528. else {
  58529. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  58530. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  58531. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  58532. }
  58533. dataOffset += dataLength;
  58534. width *= 0.5;
  58535. height *= 0.5;
  58536. width = Math.max(1.0, width);
  58537. height = Math.max(1.0, height);
  58538. }
  58539. }
  58540. };
  58541. return DDSTools;
  58542. }());
  58543. Internals.DDSTools = DDSTools;
  58544. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58545. })(BABYLON || (BABYLON = {}));
  58546. //# sourceMappingURL=babylon.dds.js.map
  58547. var BABYLON;
  58548. (function (BABYLON) {
  58549. var Internals;
  58550. (function (Internals) {
  58551. /**
  58552. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  58553. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  58554. */
  58555. var KhronosTextureContainer = (function () {
  58556. /**
  58557. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  58558. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  58559. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  58560. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  58561. */
  58562. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  58563. this.arrayBuffer = arrayBuffer;
  58564. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  58565. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  58566. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  58567. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  58568. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  58569. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  58570. BABYLON.Tools.Error("texture missing KTX identifier");
  58571. return;
  58572. }
  58573. // load the reset of the header in native 32 bit int
  58574. var header = new Int32Array(this.arrayBuffer, 12, 13);
  58575. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  58576. var oppositeEndianess = header[0] === 0x01020304;
  58577. // read all the header elements in order they exist in the file, without modification (sans endainness)
  58578. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  58579. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  58580. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  58581. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  58582. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  58583. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  58584. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  58585. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  58586. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  58587. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  58588. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  58589. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  58590. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  58591. if (this.glType !== 0) {
  58592. BABYLON.Tools.Error("only compressed formats currently supported");
  58593. return;
  58594. }
  58595. else {
  58596. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  58597. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  58598. }
  58599. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  58600. BABYLON.Tools.Error("only 2D textures currently supported");
  58601. return;
  58602. }
  58603. if (this.numberOfArrayElements !== 0) {
  58604. BABYLON.Tools.Error("texture arrays not currently supported");
  58605. return;
  58606. }
  58607. if (this.numberOfFaces !== facesExpected) {
  58608. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  58609. return;
  58610. }
  58611. // we now have a completely validated file, so could use existence of loadType as success
  58612. // would need to make this more elaborate & adjust checks above to support more than one load type
  58613. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  58614. }
  58615. // not as fast hardware based, but will probably never need to use
  58616. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  58617. return ((val & 0xFF) << 24)
  58618. | ((val & 0xFF00) << 8)
  58619. | ((val >> 8) & 0xFF00)
  58620. | ((val >> 24) & 0xFF);
  58621. };
  58622. /**
  58623. * It is assumed that the texture has already been created & is currently bound
  58624. */
  58625. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  58626. switch (this.loadType) {
  58627. case KhronosTextureContainer.COMPRESSED_2D:
  58628. this._upload2DCompressedLevels(gl, loadMipmaps);
  58629. break;
  58630. case KhronosTextureContainer.TEX_2D:
  58631. case KhronosTextureContainer.COMPRESSED_3D:
  58632. case KhronosTextureContainer.TEX_3D:
  58633. }
  58634. };
  58635. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  58636. // initialize width & height for level 1
  58637. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  58638. var width = this.pixelWidth;
  58639. var height = this.pixelHeight;
  58640. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  58641. for (var level = 0; level < mipmapCount; level++) {
  58642. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  58643. for (var face = 0; face < this.numberOfFaces; face++) {
  58644. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  58645. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  58646. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  58647. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  58648. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  58649. }
  58650. width = Math.max(1.0, width * 0.5);
  58651. height = Math.max(1.0, height * 0.5);
  58652. }
  58653. };
  58654. return KhronosTextureContainer;
  58655. }());
  58656. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  58657. // load types
  58658. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  58659. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  58660. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  58661. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  58662. Internals.KhronosTextureContainer = KhronosTextureContainer;
  58663. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58664. })(BABYLON || (BABYLON = {}));
  58665. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  58666. var BABYLON;
  58667. (function (BABYLON) {
  58668. var DynamicFloatArrayElementInfo = (function () {
  58669. function DynamicFloatArrayElementInfo() {
  58670. }
  58671. return DynamicFloatArrayElementInfo;
  58672. }());
  58673. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  58674. /**
  58675. * 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.
  58676. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  58677. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  58678. * 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.
  58679. * 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.
  58680. * 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".
  58681. */
  58682. var DynamicFloatArray = (function () {
  58683. /**
  58684. * Construct an instance of the dynamic float array
  58685. * @param stride size of one element in float (i.e. not bytes!)
  58686. * @param initialElementCount the number of available entries at construction
  58687. */
  58688. function DynamicFloatArray(stride, initialElementCount) {
  58689. this.compareValueOffset = null;
  58690. this.sortingAscending = true;
  58691. this._stride = stride;
  58692. this.buffer = new Float32Array(stride * initialElementCount);
  58693. this._lastUsed = 0;
  58694. this._firstFree = 0;
  58695. this._allEntries = new Array(initialElementCount);
  58696. this._freeEntries = new Array(initialElementCount);
  58697. for (var i = 0; i < initialElementCount; i++) {
  58698. var element = new DynamicFloatArrayElementInfo();
  58699. element.offset = i * stride;
  58700. this._allEntries[i] = element;
  58701. this._freeEntries[initialElementCount - i - 1] = element;
  58702. }
  58703. }
  58704. /**
  58705. * Allocate an element in the array.
  58706. * @return the element info instance that contains the offset into the main buffer of the element's location.
  58707. * Beware, this offset may change when you call pack()
  58708. */
  58709. DynamicFloatArray.prototype.allocElement = function () {
  58710. if (this._freeEntries.length === 0) {
  58711. this._growBuffer();
  58712. }
  58713. var el = this._freeEntries.pop();
  58714. this._lastUsed = Math.max(el.offset, this._lastUsed);
  58715. if (el.offset === this._firstFree) {
  58716. if (this._freeEntries.length > 0) {
  58717. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  58718. }
  58719. else {
  58720. this._firstFree += this._stride;
  58721. }
  58722. }
  58723. return el;
  58724. };
  58725. /**
  58726. * Free the element corresponding to the given element info
  58727. * @param elInfo the element that describe the allocated element
  58728. */
  58729. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  58730. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  58731. this._freeEntries.push(elInfo);
  58732. };
  58733. /**
  58734. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  58735. * 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().
  58736. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  58737. */
  58738. DynamicFloatArray.prototype.pack = function () {
  58739. // no free slot? no need to pack
  58740. if (this._freeEntries.length === 0) {
  58741. return this.buffer;
  58742. }
  58743. // If the buffer is already packed the last used will always be lower than the first free
  58744. // 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.
  58745. if (this._lastUsed < this._firstFree) {
  58746. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  58747. return elementsBuffer_1;
  58748. }
  58749. var s = this._stride;
  58750. // 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
  58751. var lastFree = new DynamicFloatArrayElementInfo();
  58752. lastFree.offset = this.totalElementCount * s;
  58753. this._freeEntries.push(lastFree);
  58754. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  58755. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  58756. var firstFreeSlotOffset = sortedFree[0].offset;
  58757. var freeZoneSize = 1;
  58758. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  58759. var prevOffset = sortedFree[0].offset;
  58760. for (var i = 1; i < sortedFree.length; i++) {
  58761. // 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
  58762. if (firstFreeSlotOffset >= occupiedZoneSize) {
  58763. break;
  58764. }
  58765. var curFree = sortedFree[i];
  58766. var curOffset = curFree.offset;
  58767. // Compute the distance between this offset and the previous
  58768. var distance = curOffset - prevOffset;
  58769. // If the distance is the stride size, they are adjacent, it good, move to the next
  58770. if (distance === s) {
  58771. // Free zone is one element bigger
  58772. ++freeZoneSize;
  58773. // as we're about to iterate to the next, the cur becomes the previous...
  58774. prevOffset = curOffset;
  58775. continue;
  58776. }
  58777. // Distance is bigger, which means there's x element between the previous free and this one
  58778. var usedRange = (distance / s) - 1;
  58779. // Two cases the free zone is smaller than the data to move or bigger
  58780. // Copy what can fit in the free zone
  58781. var curMoveOffset = curOffset - s;
  58782. var copyCount = Math.min(freeZoneSize, usedRange);
  58783. for (var j = 0; j < copyCount; j++) {
  58784. var freeI = firstFreeSlotOffset / s;
  58785. var curI = curMoveOffset / s;
  58786. var moveEl = sortedAll[curI];
  58787. this._moveElement(moveEl, firstFreeSlotOffset);
  58788. var replacedEl = sortedAll[freeI];
  58789. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  58790. replacedEl.offset = curMoveOffset;
  58791. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  58792. sortedAll[freeI] = moveEl;
  58793. sortedAll[curI] = replacedEl;
  58794. curMoveOffset -= s;
  58795. firstFreeSlotOffset += s;
  58796. }
  58797. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  58798. if (freeZoneSize <= usedRange) {
  58799. firstFreeSlotOffset = curMoveOffset + s;
  58800. freeZoneSize = 1 + copyCount;
  58801. }
  58802. else {
  58803. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  58804. }
  58805. // as we're about to iterate to the next, the cur becomes the previous...
  58806. prevOffset = curOffset;
  58807. }
  58808. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  58809. this._lastUsed = firstFreeSlotOffset - s;
  58810. this._firstFree = firstFreeSlotOffset;
  58811. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  58812. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  58813. this._allEntries = sortedAll;
  58814. return elementsBuffer;
  58815. };
  58816. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  58817. for (var i = 0; i < this._stride; i++) {
  58818. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  58819. }
  58820. element.offset = destOffset;
  58821. };
  58822. DynamicFloatArray.prototype._growBuffer = function () {
  58823. // Allocate the new buffer with 50% more entries, copy the content of the current one
  58824. var newElCount = Math.floor(this.totalElementCount * 1.5);
  58825. var newBuffer = new Float32Array(newElCount * this._stride);
  58826. newBuffer.set(this.buffer);
  58827. var curCount = this.totalElementCount;
  58828. var addedCount = newElCount - this.totalElementCount;
  58829. for (var i = 0; i < addedCount; i++) {
  58830. var element = new DynamicFloatArrayElementInfo();
  58831. element.offset = (curCount + i) * this.stride;
  58832. this._allEntries.push(element);
  58833. this._freeEntries[addedCount - i - 1] = element;
  58834. }
  58835. this._firstFree = curCount * this.stride;
  58836. this.buffer = newBuffer;
  58837. };
  58838. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  58839. /**
  58840. * Get the total count of entries that can fit in the current buffer
  58841. * @returns the elements count
  58842. */
  58843. get: function () {
  58844. return this._allEntries.length;
  58845. },
  58846. enumerable: true,
  58847. configurable: true
  58848. });
  58849. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  58850. /**
  58851. * Get the count of free entries that can still be allocated without resizing the buffer
  58852. * @returns the free elements count
  58853. */
  58854. get: function () {
  58855. return this._freeEntries.length;
  58856. },
  58857. enumerable: true,
  58858. configurable: true
  58859. });
  58860. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  58861. /**
  58862. * Get the count of allocated elements
  58863. * @returns the allocated elements count
  58864. */
  58865. get: function () {
  58866. return this._allEntries.length - this._freeEntries.length;
  58867. },
  58868. enumerable: true,
  58869. configurable: true
  58870. });
  58871. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  58872. /**
  58873. * Return the size of one element in float
  58874. * @returns the size in float
  58875. */
  58876. get: function () {
  58877. return this._stride;
  58878. },
  58879. enumerable: true,
  58880. configurable: true
  58881. });
  58882. DynamicFloatArray.prototype.sort = function () {
  58883. var _this = this;
  58884. if (!this.compareValueOffset) {
  58885. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  58886. }
  58887. var count = this.usedElementCount;
  58888. // Do we have to (re)create the sort table?
  58889. if (!this._sortTable || this._sortTable.length < count) {
  58890. // 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...
  58891. var newCount = Math.min(this.totalElementCount, count * 2);
  58892. this._sortTable = new Array(newCount);
  58893. }
  58894. if (!this._sortedTable || this._sortedTable.length !== count) {
  58895. this._sortedTable = new Array(count);
  58896. }
  58897. // Because, you know...
  58898. this.pack();
  58899. //let stride = this.stride;
  58900. //for (let i = 0; i < count; i++) {
  58901. // let si = this._sortTable[i];
  58902. // if (!si) {
  58903. // si = new SortInfo();
  58904. // this._sortTable[i] = si;
  58905. // }
  58906. // si.entry = this._allEntries[i];
  58907. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  58908. // si.swapedOffset = null;
  58909. // this._sortedTable[i] = si;
  58910. //}
  58911. var curOffset = 0;
  58912. var stride = this.stride;
  58913. for (var i = 0; i < count; i++, curOffset += stride) {
  58914. var si = this._sortTable[i];
  58915. if (!si) {
  58916. si = new SortInfo();
  58917. this._sortTable[i] = si;
  58918. }
  58919. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  58920. si.offset = curOffset;
  58921. si.swapedOffset = null;
  58922. this._sortedTable[i] = si;
  58923. }
  58924. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  58925. if (this.sortingAscending) {
  58926. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  58927. }
  58928. else {
  58929. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  58930. }
  58931. var swapElements = function (src, dst) {
  58932. for (var i = 0; i < stride; i++) {
  58933. var tps = _this.buffer[dst + i];
  58934. _this.buffer[dst + i] = _this.buffer[src + i];
  58935. _this.buffer[src + i] = tps;
  58936. }
  58937. };
  58938. // 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:
  58939. // 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),
  58940. // and I still want something with a good algorithm complexity.
  58941. // 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,
  58942. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  58943. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  58944. // 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
  58945. // until we find a SortInfo object without a swapedOffset which means we got the right location
  58946. // 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
  58947. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  58948. for (var i = 0; i < count; i++) {
  58949. // Get the element to move
  58950. var sourceSI = this._sortedTable[i];
  58951. var destSI = this._sortTable[i];
  58952. var sourceOff = sourceSI.offset;
  58953. // If the source changed location, find the new one
  58954. if (sourceSI.swapedOffset) {
  58955. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  58956. var curSI = sourceSI;
  58957. while (curSI.swapedOffset) {
  58958. curSI = this._sortTable[curSI.swapedOffset / stride];
  58959. }
  58960. // Finally get the right location
  58961. sourceOff = curSI.offset;
  58962. }
  58963. // Tag the element being replaced with its new location
  58964. destSI.swapedOffset = sourceOff;
  58965. // Swap elements (only if needed)
  58966. if (sourceOff !== destSI.offset) {
  58967. swapElements(sourceOff, destSI.offset);
  58968. }
  58969. // Update the offset in the corresponding DFAE
  58970. //sourceSI.entry.offset = destSI.entry.offset;
  58971. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  58972. }
  58973. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  58974. return true;
  58975. };
  58976. return DynamicFloatArray;
  58977. }());
  58978. BABYLON.DynamicFloatArray = DynamicFloatArray;
  58979. var SortInfo = (function () {
  58980. function SortInfo() {
  58981. this.compareData = this.offset = this.swapedOffset = null;
  58982. }
  58983. return SortInfo;
  58984. }());
  58985. })(BABYLON || (BABYLON = {}));
  58986. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  58987. var BABYLON;
  58988. (function (BABYLON) {
  58989. var Debug;
  58990. (function (Debug) {
  58991. /**
  58992. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  58993. */
  58994. var SkeletonViewer = (function () {
  58995. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  58996. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58997. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58998. this.skeleton = skeleton;
  58999. this.mesh = mesh;
  59000. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59001. this.renderingGroupId = renderingGroupId;
  59002. this.color = BABYLON.Color3.White();
  59003. this._debugLines = [];
  59004. this._isEnabled = false;
  59005. this._scene = scene;
  59006. this.update();
  59007. this._renderFunction = this.update.bind(this);
  59008. }
  59009. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59010. get: function () {
  59011. return this._isEnabled;
  59012. },
  59013. set: function (value) {
  59014. if (this._isEnabled === value) {
  59015. return;
  59016. }
  59017. this._isEnabled = value;
  59018. if (value) {
  59019. this._scene.registerBeforeRender(this._renderFunction);
  59020. }
  59021. else {
  59022. this._scene.unregisterBeforeRender(this._renderFunction);
  59023. }
  59024. },
  59025. enumerable: true,
  59026. configurable: true
  59027. });
  59028. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59029. if (x === void 0) { x = 0; }
  59030. if (y === void 0) { y = 0; }
  59031. if (z === void 0) { z = 0; }
  59032. var tmat = BABYLON.Tmp.Matrix[0];
  59033. var parentBone = bone.getParent();
  59034. tmat.copyFrom(bone.getLocalMatrix());
  59035. if (x !== 0 || y !== 0 || z !== 0) {
  59036. var tmat2 = BABYLON.Tmp.Matrix[1];
  59037. BABYLON.Matrix.IdentityToRef(tmat2);
  59038. tmat2.m[12] = x;
  59039. tmat2.m[13] = y;
  59040. tmat2.m[14] = z;
  59041. tmat2.multiplyToRef(tmat, tmat);
  59042. }
  59043. if (parentBone) {
  59044. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59045. }
  59046. tmat.multiplyToRef(meshMat, tmat);
  59047. position.x = tmat.m[12];
  59048. position.y = tmat.m[13];
  59049. position.z = tmat.m[14];
  59050. };
  59051. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59052. var len = bones.length;
  59053. var meshPos = this.mesh.position;
  59054. for (var i = 0; i < len; i++) {
  59055. var bone = bones[i];
  59056. var points = this._debugLines[i];
  59057. if (!points) {
  59058. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59059. this._debugLines[i] = points;
  59060. }
  59061. this._getBonePosition(points[0], bone, meshMat);
  59062. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59063. points[0].subtractInPlace(meshPos);
  59064. points[1].subtractInPlace(meshPos);
  59065. }
  59066. };
  59067. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59068. var len = bones.length;
  59069. var boneNum = 0;
  59070. var meshPos = this.mesh.position;
  59071. for (var i = len - 1; i >= 0; i--) {
  59072. var childBone = bones[i];
  59073. var parentBone = childBone.getParent();
  59074. if (!parentBone) {
  59075. continue;
  59076. }
  59077. var points = this._debugLines[boneNum];
  59078. if (!points) {
  59079. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59080. this._debugLines[boneNum] = points;
  59081. }
  59082. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59083. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59084. points[0].subtractInPlace(meshPos);
  59085. points[1].subtractInPlace(meshPos);
  59086. boneNum++;
  59087. }
  59088. };
  59089. SkeletonViewer.prototype.update = function () {
  59090. if (this.autoUpdateBonesMatrices) {
  59091. this.skeleton.computeAbsoluteTransforms();
  59092. }
  59093. if (this.skeleton.bones[0].length === undefined) {
  59094. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59095. }
  59096. else {
  59097. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59098. }
  59099. if (!this._debugMesh) {
  59100. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59101. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59102. }
  59103. else {
  59104. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59105. }
  59106. this._debugMesh.position.copyFrom(this.mesh.position);
  59107. this._debugMesh.color = this.color;
  59108. };
  59109. SkeletonViewer.prototype.dispose = function () {
  59110. if (this._debugMesh) {
  59111. this.isEnabled = false;
  59112. this._debugMesh.dispose();
  59113. this._debugMesh = null;
  59114. }
  59115. };
  59116. return SkeletonViewer;
  59117. }());
  59118. Debug.SkeletonViewer = SkeletonViewer;
  59119. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59120. })(BABYLON || (BABYLON = {}));
  59121. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59122. var BABYLON;
  59123. (function (BABYLON) {
  59124. var Debug;
  59125. (function (Debug) {
  59126. var AxesViewer = (function () {
  59127. function AxesViewer(scene, scaleLines) {
  59128. if (scaleLines === void 0) { scaleLines = 1; }
  59129. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59130. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59131. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59132. this.scaleLines = 1;
  59133. this.scaleLines = scaleLines;
  59134. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59135. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59136. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59137. this._xmesh.renderingGroupId = 2;
  59138. this._ymesh.renderingGroupId = 2;
  59139. this._zmesh.renderingGroupId = 2;
  59140. this._xmesh.material.checkReadyOnlyOnce = true;
  59141. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59142. this._ymesh.material.checkReadyOnlyOnce = true;
  59143. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59144. this._zmesh.material.checkReadyOnlyOnce = true;
  59145. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59146. this.scene = scene;
  59147. }
  59148. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59149. var scaleLines = this.scaleLines;
  59150. this._xmesh.position.copyFrom(position);
  59151. this._ymesh.position.copyFrom(position);
  59152. this._zmesh.position.copyFrom(position);
  59153. var point2 = this._xline[1];
  59154. point2.x = xaxis.x * scaleLines;
  59155. point2.y = xaxis.y * scaleLines;
  59156. point2.z = xaxis.z * scaleLines;
  59157. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  59158. point2 = this._yline[1];
  59159. point2.x = yaxis.x * scaleLines;
  59160. point2.y = yaxis.y * scaleLines;
  59161. point2.z = yaxis.z * scaleLines;
  59162. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  59163. point2 = this._zline[1];
  59164. point2.x = zaxis.x * scaleLines;
  59165. point2.y = zaxis.y * scaleLines;
  59166. point2.z = zaxis.z * scaleLines;
  59167. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  59168. };
  59169. AxesViewer.prototype.dispose = function () {
  59170. if (this._xmesh) {
  59171. this._xmesh.dispose();
  59172. this._ymesh.dispose();
  59173. this._zmesh.dispose();
  59174. this._xmesh = null;
  59175. this._ymesh = null;
  59176. this._zmesh = null;
  59177. this._xline = null;
  59178. this._yline = null;
  59179. this._zline = null;
  59180. this.scene = null;
  59181. }
  59182. };
  59183. return AxesViewer;
  59184. }());
  59185. Debug.AxesViewer = AxesViewer;
  59186. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59187. })(BABYLON || (BABYLON = {}));
  59188. //# sourceMappingURL=babylon.axesViewer.js.map
  59189. var BABYLON;
  59190. (function (BABYLON) {
  59191. var Debug;
  59192. (function (Debug) {
  59193. var BoneAxesViewer = (function (_super) {
  59194. __extends(BoneAxesViewer, _super);
  59195. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59196. if (scaleLines === void 0) { scaleLines = 1; }
  59197. var _this = _super.call(this, scene, scaleLines) || this;
  59198. _this.pos = BABYLON.Vector3.Zero();
  59199. _this.xaxis = BABYLON.Vector3.Zero();
  59200. _this.yaxis = BABYLON.Vector3.Zero();
  59201. _this.zaxis = BABYLON.Vector3.Zero();
  59202. _this.mesh = mesh;
  59203. _this.bone = bone;
  59204. return _this;
  59205. }
  59206. BoneAxesViewer.prototype.update = function () {
  59207. var bone = this.bone;
  59208. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59209. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59210. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59211. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59212. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59213. };
  59214. BoneAxesViewer.prototype.dispose = function () {
  59215. if (this.pos) {
  59216. this.pos = null;
  59217. this.xaxis = null;
  59218. this.yaxis = null;
  59219. this.zaxis = null;
  59220. this.mesh = null;
  59221. this.bone = null;
  59222. _super.prototype.dispose.call(this);
  59223. }
  59224. };
  59225. return BoneAxesViewer;
  59226. }(Debug.AxesViewer));
  59227. Debug.BoneAxesViewer = BoneAxesViewer;
  59228. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59229. })(BABYLON || (BABYLON = {}));
  59230. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59231. var BABYLON;
  59232. (function (BABYLON) {
  59233. var RayHelper = (function () {
  59234. function RayHelper(ray) {
  59235. this.ray = ray;
  59236. }
  59237. RayHelper.CreateAndShow = function (ray, scene, color) {
  59238. var helper = new RayHelper(ray);
  59239. helper.show(scene, color);
  59240. return helper;
  59241. };
  59242. RayHelper.prototype.show = function (scene, color) {
  59243. if (!this._renderFunction) {
  59244. var ray = this.ray;
  59245. this._renderFunction = this._render.bind(this);
  59246. this._scene = scene;
  59247. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59248. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59249. this._scene.registerBeforeRender(this._renderFunction);
  59250. }
  59251. if (color) {
  59252. this._renderLine.color.copyFrom(color);
  59253. }
  59254. };
  59255. RayHelper.prototype.hide = function () {
  59256. if (this._renderFunction) {
  59257. this._scene.unregisterBeforeRender(this._renderFunction);
  59258. this._scene = null;
  59259. this._renderFunction = null;
  59260. this._renderLine.dispose();
  59261. this._renderLine = null;
  59262. this._renderPoints = null;
  59263. }
  59264. };
  59265. RayHelper.prototype._render = function () {
  59266. var ray = this.ray;
  59267. var point = this._renderPoints[1];
  59268. var len = Math.min(ray.length, 1000000);
  59269. point.copyFrom(ray.direction);
  59270. point.scaleInPlace(len);
  59271. point.addInPlace(ray.origin);
  59272. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59273. };
  59274. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59275. this._attachedToMesh = mesh;
  59276. var ray = this.ray;
  59277. if (!ray.direction) {
  59278. ray.direction = BABYLON.Vector3.Zero();
  59279. }
  59280. if (!ray.origin) {
  59281. ray.origin = BABYLON.Vector3.Zero();
  59282. }
  59283. if (length) {
  59284. ray.length = length;
  59285. }
  59286. if (!meshSpaceOrigin) {
  59287. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59288. }
  59289. if (!meshSpaceDirection) {
  59290. // -1 so that this will work with Mesh.lookAt
  59291. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59292. }
  59293. if (!this._meshSpaceDirection) {
  59294. this._meshSpaceDirection = meshSpaceDirection.clone();
  59295. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59296. }
  59297. else {
  59298. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59299. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59300. }
  59301. if (!this._updateToMeshFunction) {
  59302. this._updateToMeshFunction = this._updateToMesh.bind(this);
  59303. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  59304. }
  59305. this._updateToMesh();
  59306. };
  59307. RayHelper.prototype.detachFromMesh = function () {
  59308. if (this._attachedToMesh) {
  59309. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  59310. this._attachedToMesh = null;
  59311. this._updateToMeshFunction = null;
  59312. }
  59313. };
  59314. RayHelper.prototype._updateToMesh = function () {
  59315. var ray = this.ray;
  59316. if (this._attachedToMesh._isDisposed) {
  59317. this.detachFromMesh();
  59318. return;
  59319. }
  59320. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  59321. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  59322. };
  59323. RayHelper.prototype.dispose = function () {
  59324. this.hide();
  59325. this.detachFromMesh();
  59326. this.ray = null;
  59327. };
  59328. return RayHelper;
  59329. }());
  59330. BABYLON.RayHelper = RayHelper;
  59331. })(BABYLON || (BABYLON = {}));
  59332. //# sourceMappingURL=babylon.rayHelper.js.map
  59333. var BABYLON;
  59334. (function (BABYLON) {
  59335. var DebugLayer = (function () {
  59336. function DebugLayer(scene) {
  59337. this._scene = scene;
  59338. }
  59339. /** Creates the inspector window. */
  59340. DebugLayer.prototype._createInspector = function (config) {
  59341. if (config === void 0) { config = {}; }
  59342. var popup = config.popup || false;
  59343. var initialTab = config.initialTab || 0;
  59344. var parentElement = config.parentElement || null;
  59345. if (!this._inspector) {
  59346. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59347. } // else nothing to do,; instance is already existing
  59348. };
  59349. DebugLayer.prototype.isVisible = function () {
  59350. if (!this._inspector) {
  59351. return false;
  59352. }
  59353. return true;
  59354. };
  59355. DebugLayer.prototype.hide = function () {
  59356. if (this._inspector) {
  59357. try {
  59358. this._inspector.dispose();
  59359. }
  59360. catch (e) {
  59361. // If the inspector has been removed directly from the inspector tool
  59362. }
  59363. this._inspector = null;
  59364. }
  59365. };
  59366. DebugLayer.prototype.show = function (config) {
  59367. if (config === void 0) { config = {}; }
  59368. if (typeof INSPECTOR == 'undefined') {
  59369. // Load inspector and add it to the DOM
  59370. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59371. }
  59372. else {
  59373. // Otherwise creates the inspector
  59374. this._createInspector(config);
  59375. }
  59376. };
  59377. return DebugLayer;
  59378. }());
  59379. // Get protocol used - http or https
  59380. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  59381. BABYLON.DebugLayer = DebugLayer;
  59382. })(BABYLON || (BABYLON = {}));
  59383. //# sourceMappingURL=babylon.debugLayer.js.map
  59384. var BABYLON;
  59385. (function (BABYLON) {
  59386. var BoundingBoxRenderer = (function () {
  59387. function BoundingBoxRenderer(scene) {
  59388. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59389. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59390. this.showBackLines = true;
  59391. this.renderList = new BABYLON.SmartArray(32);
  59392. this._vertexBuffers = {};
  59393. this._scene = scene;
  59394. }
  59395. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59396. if (this._colorShader) {
  59397. return;
  59398. }
  59399. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  59400. attributes: [BABYLON.VertexBuffer.PositionKind],
  59401. uniforms: ["world", "viewProjection", "color"]
  59402. });
  59403. var engine = this._scene.getEngine();
  59404. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  59405. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59406. 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]);
  59407. };
  59408. BoundingBoxRenderer.prototype.reset = function () {
  59409. this.renderList.reset();
  59410. };
  59411. BoundingBoxRenderer.prototype.render = function () {
  59412. if (this.renderList.length === 0) {
  59413. return;
  59414. }
  59415. this._prepareRessources();
  59416. if (!this._colorShader.isReady()) {
  59417. return;
  59418. }
  59419. var engine = this._scene.getEngine();
  59420. engine.setDepthWrite(false);
  59421. this._colorShader._preBind();
  59422. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59423. var boundingBox = this.renderList.data[boundingBoxIndex];
  59424. var min = boundingBox.minimum;
  59425. var max = boundingBox.maximum;
  59426. var diff = max.subtract(min);
  59427. var median = min.add(diff.scale(0.5));
  59428. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59429. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59430. .multiply(boundingBox.getWorldMatrix());
  59431. // VBOs
  59432. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59433. if (this.showBackLines) {
  59434. // Back
  59435. engine.setDepthFunctionToGreaterOrEqual();
  59436. this._scene.resetCachedMaterial();
  59437. this._colorShader.setColor4("color", this.backColor.toColor4());
  59438. this._colorShader.bind(worldMatrix);
  59439. // Draw order
  59440. engine.draw(false, 0, 24);
  59441. }
  59442. // Front
  59443. engine.setDepthFunctionToLess();
  59444. this._scene.resetCachedMaterial();
  59445. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59446. this._colorShader.bind(worldMatrix);
  59447. // Draw order
  59448. engine.draw(false, 0, 24);
  59449. }
  59450. this._colorShader.unbind();
  59451. engine.setDepthFunctionToLessOrEqual();
  59452. engine.setDepthWrite(true);
  59453. };
  59454. BoundingBoxRenderer.prototype.dispose = function () {
  59455. if (!this._colorShader) {
  59456. return;
  59457. }
  59458. this.renderList.dispose();
  59459. this._colorShader.dispose();
  59460. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59461. if (buffer) {
  59462. buffer.dispose();
  59463. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59464. }
  59465. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59466. };
  59467. return BoundingBoxRenderer;
  59468. }());
  59469. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59470. })(BABYLON || (BABYLON = {}));
  59471. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59472. var BABYLON;
  59473. (function (BABYLON) {
  59474. var MorphTarget = (function () {
  59475. function MorphTarget(name, influence) {
  59476. if (influence === void 0) { influence = 0; }
  59477. this.name = name;
  59478. this.animations = new Array();
  59479. this.onInfluenceChanged = new BABYLON.Observable();
  59480. this.influence = influence;
  59481. }
  59482. Object.defineProperty(MorphTarget.prototype, "influence", {
  59483. get: function () {
  59484. return this._influence;
  59485. },
  59486. set: function (influence) {
  59487. if (this._influence === influence) {
  59488. return;
  59489. }
  59490. var previous = this._influence;
  59491. this._influence = influence;
  59492. if (this.onInfluenceChanged.hasObservers) {
  59493. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  59494. }
  59495. },
  59496. enumerable: true,
  59497. configurable: true
  59498. });
  59499. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  59500. get: function () {
  59501. return this._normals !== undefined;
  59502. },
  59503. enumerable: true,
  59504. configurable: true
  59505. });
  59506. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  59507. get: function () {
  59508. return this._tangents !== undefined;
  59509. },
  59510. enumerable: true,
  59511. configurable: true
  59512. });
  59513. MorphTarget.prototype.setPositions = function (data) {
  59514. this._positions = new Float32Array(data);
  59515. };
  59516. MorphTarget.prototype.getPositions = function () {
  59517. return this._positions;
  59518. };
  59519. MorphTarget.prototype.setNormals = function (data) {
  59520. this._normals = new Float32Array(data);
  59521. };
  59522. MorphTarget.prototype.getNormals = function () {
  59523. return this._normals;
  59524. };
  59525. MorphTarget.prototype.setTangents = function (data) {
  59526. this._tangents = new Float32Array(data);
  59527. };
  59528. MorphTarget.prototype.getTangents = function () {
  59529. return this._tangents;
  59530. };
  59531. /**
  59532. * Serializes the current target into a Serialization object.
  59533. * Returns the serialized object.
  59534. */
  59535. MorphTarget.prototype.serialize = function () {
  59536. var serializationObject = {};
  59537. serializationObject.name = this.name;
  59538. serializationObject.influence = this.influence;
  59539. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  59540. if (this.hasNormals) {
  59541. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  59542. }
  59543. if (this.hasTangents) {
  59544. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  59545. }
  59546. return serializationObject;
  59547. };
  59548. // Statics
  59549. MorphTarget.Parse = function (serializationObject) {
  59550. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  59551. result.setPositions(serializationObject.positions);
  59552. if (serializationObject.normals) {
  59553. result.setNormals(serializationObject.normals);
  59554. }
  59555. if (serializationObject.tangents) {
  59556. result.setTangents(serializationObject.tangents);
  59557. }
  59558. return result;
  59559. };
  59560. MorphTarget.FromMesh = function (mesh, name, influence) {
  59561. if (!name) {
  59562. name = mesh.name;
  59563. }
  59564. var result = new MorphTarget(name, influence);
  59565. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  59566. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59567. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  59568. }
  59569. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  59570. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  59571. }
  59572. return result;
  59573. };
  59574. return MorphTarget;
  59575. }());
  59576. BABYLON.MorphTarget = MorphTarget;
  59577. })(BABYLON || (BABYLON = {}));
  59578. //# sourceMappingURL=babylon.morphTarget.js.map
  59579. var BABYLON;
  59580. (function (BABYLON) {
  59581. var MorphTargetManager = (function () {
  59582. function MorphTargetManager(scene) {
  59583. this._targets = new Array();
  59584. this._targetObservable = new Array();
  59585. this._activeTargets = new BABYLON.SmartArray(16);
  59586. this._supportsNormals = false;
  59587. this._supportsTangents = false;
  59588. this._vertexCount = 0;
  59589. this._uniqueId = 0;
  59590. if (!scene) {
  59591. scene = BABYLON.Engine.LastCreatedScene;
  59592. }
  59593. this._scene = scene;
  59594. this._scene.morphTargetManagers.push(this);
  59595. this._uniqueId = scene.getUniqueId();
  59596. }
  59597. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  59598. get: function () {
  59599. return this._uniqueId;
  59600. },
  59601. enumerable: true,
  59602. configurable: true
  59603. });
  59604. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  59605. get: function () {
  59606. return this._vertexCount;
  59607. },
  59608. enumerable: true,
  59609. configurable: true
  59610. });
  59611. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  59612. get: function () {
  59613. return this._supportsNormals;
  59614. },
  59615. enumerable: true,
  59616. configurable: true
  59617. });
  59618. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  59619. get: function () {
  59620. return this._supportsTangents;
  59621. },
  59622. enumerable: true,
  59623. configurable: true
  59624. });
  59625. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  59626. get: function () {
  59627. return this._targets.length;
  59628. },
  59629. enumerable: true,
  59630. configurable: true
  59631. });
  59632. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  59633. get: function () {
  59634. return this._activeTargets.length;
  59635. },
  59636. enumerable: true,
  59637. configurable: true
  59638. });
  59639. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  59640. get: function () {
  59641. return this._influences;
  59642. },
  59643. enumerable: true,
  59644. configurable: true
  59645. });
  59646. MorphTargetManager.prototype.getActiveTarget = function (index) {
  59647. return this._activeTargets.data[index];
  59648. };
  59649. MorphTargetManager.prototype.getTarget = function (index) {
  59650. return this._targets[index];
  59651. };
  59652. MorphTargetManager.prototype.addTarget = function (target) {
  59653. var _this = this;
  59654. if (this._vertexCount) {
  59655. if (this._vertexCount !== target.getPositions().length / 3) {
  59656. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  59657. return;
  59658. }
  59659. }
  59660. this._targets.push(target);
  59661. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  59662. _this._syncActiveTargets(needUpdate);
  59663. }));
  59664. this._syncActiveTargets(true);
  59665. };
  59666. MorphTargetManager.prototype.removeTarget = function (target) {
  59667. var index = this._targets.indexOf(target);
  59668. if (index >= 0) {
  59669. this._targets.splice(index, 1);
  59670. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  59671. this._vertexCount = 0;
  59672. this._syncActiveTargets(true);
  59673. }
  59674. };
  59675. /**
  59676. * Serializes the current manager into a Serialization object.
  59677. * Returns the serialized object.
  59678. */
  59679. MorphTargetManager.prototype.serialize = function () {
  59680. var serializationObject = {};
  59681. serializationObject.id = this.uniqueId;
  59682. serializationObject.targets = [];
  59683. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  59684. var target = _a[_i];
  59685. serializationObject.targets.push(target.serialize());
  59686. }
  59687. return serializationObject;
  59688. };
  59689. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  59690. this._syncActiveTargets(needUpdate);
  59691. };
  59692. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  59693. this._activeTargets.reset();
  59694. var tempInfluences = [];
  59695. this._supportsNormals = true;
  59696. this._supportsTangents = true;
  59697. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  59698. var target = _a[_i];
  59699. if (target.influence > 0) {
  59700. this._activeTargets.push(target);
  59701. tempInfluences.push(target.influence);
  59702. this._supportsNormals = this._supportsNormals && target.hasNormals;
  59703. this._supportsTangents = this._supportsTangents && target.hasTangents;
  59704. if (this._vertexCount === 0) {
  59705. this._vertexCount = target.getPositions().length / 3;
  59706. }
  59707. }
  59708. }
  59709. this._influences = new Float32Array(tempInfluences);
  59710. if (needUpdate) {
  59711. // Flag meshes as dirty to resync with the active targets
  59712. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  59713. var mesh = _c[_b];
  59714. if (mesh.morphTargetManager === this) {
  59715. mesh._syncGeometryWithMorphTargetManager();
  59716. }
  59717. }
  59718. }
  59719. };
  59720. // Statics
  59721. MorphTargetManager.Parse = function (serializationObject, scene) {
  59722. var result = new MorphTargetManager(scene);
  59723. result._uniqueId = serializationObject.id;
  59724. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  59725. var targetData = _a[_i];
  59726. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  59727. }
  59728. return result;
  59729. };
  59730. return MorphTargetManager;
  59731. }());
  59732. BABYLON.MorphTargetManager = MorphTargetManager;
  59733. })(BABYLON || (BABYLON = {}));
  59734. //# sourceMappingURL=babylon.morphTargetManager.js.map
  59735. var BABYLON;
  59736. (function (BABYLON) {
  59737. /**
  59738. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  59739. * It can help converting any input color in a desired output one. This can then be used to create effects
  59740. * from sepia, black and white to sixties or futuristic rendering...
  59741. *
  59742. * The only supported format is currently 3dl.
  59743. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  59744. */
  59745. var ColorGradingTexture = (function (_super) {
  59746. __extends(ColorGradingTexture, _super);
  59747. /**
  59748. * Instantiates a ColorGradingTexture from the following parameters.
  59749. *
  59750. * @param url The location of the color gradind data (currently only supporting 3dl)
  59751. * @param scene The scene the texture will be used in
  59752. */
  59753. function ColorGradingTexture(url, scene) {
  59754. var _this = _super.call(this, scene) || this;
  59755. if (!url) {
  59756. return _this;
  59757. }
  59758. _this._textureMatrix = BABYLON.Matrix.Identity();
  59759. _this.name = url;
  59760. _this.url = url;
  59761. _this.hasAlpha = false;
  59762. _this.isCube = false;
  59763. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59764. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59765. _this.anisotropicFilteringLevel = 1;
  59766. _this._texture = _this._getFromCache(url, true);
  59767. if (!_this._texture) {
  59768. if (!scene.useDelayedTextureLoading) {
  59769. _this.loadTexture();
  59770. }
  59771. else {
  59772. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59773. }
  59774. }
  59775. return _this;
  59776. }
  59777. /**
  59778. * Returns the texture matrix used in most of the material.
  59779. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  59780. */
  59781. ColorGradingTexture.prototype.getTextureMatrix = function () {
  59782. return this._textureMatrix;
  59783. };
  59784. /**
  59785. * Occurs when the file being loaded is a .3dl LUT file.
  59786. */
  59787. ColorGradingTexture.prototype.load3dlTexture = function () {
  59788. var _this = this;
  59789. var mipLevels = 0;
  59790. var floatArrayView = null;
  59791. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59792. this._texture = texture;
  59793. var callback = function (text) {
  59794. var data;
  59795. var tempData;
  59796. var line;
  59797. var lines = text.split('\n');
  59798. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  59799. var maxColor = 0;
  59800. for (var i = 0; i < lines.length; i++) {
  59801. line = lines[i];
  59802. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  59803. continue;
  59804. if (line.indexOf('#') === 0)
  59805. continue;
  59806. var words = line.split(" ");
  59807. if (size === 0) {
  59808. // Number of space + one
  59809. size = words.length;
  59810. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  59811. tempData = new Float32Array(size * size * size * 4);
  59812. continue;
  59813. }
  59814. if (size != 0) {
  59815. var r = Math.max(parseInt(words[0]), 0);
  59816. var g = Math.max(parseInt(words[1]), 0);
  59817. var b = Math.max(parseInt(words[2]), 0);
  59818. maxColor = Math.max(r, maxColor);
  59819. maxColor = Math.max(g, maxColor);
  59820. maxColor = Math.max(b, maxColor);
  59821. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  59822. tempData[pixelStorageIndex + 0] = r;
  59823. tempData[pixelStorageIndex + 1] = g;
  59824. tempData[pixelStorageIndex + 2] = b;
  59825. tempData[pixelStorageIndex + 3] = 0;
  59826. pixelIndexSlice++;
  59827. if (pixelIndexSlice % size == 0) {
  59828. pixelIndexH++;
  59829. pixelIndexSlice = 0;
  59830. if (pixelIndexH % size == 0) {
  59831. pixelIndexW++;
  59832. pixelIndexH = 0;
  59833. }
  59834. }
  59835. }
  59836. }
  59837. for (var i = 0; i < tempData.length; i++) {
  59838. var value = tempData[i];
  59839. data[i] = (value / maxColor * 255);
  59840. }
  59841. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  59842. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  59843. };
  59844. BABYLON.Tools.LoadFile(this.url, callback);
  59845. return this._texture;
  59846. };
  59847. /**
  59848. * Starts the loading process of the texture.
  59849. */
  59850. ColorGradingTexture.prototype.loadTexture = function () {
  59851. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  59852. this.load3dlTexture();
  59853. }
  59854. };
  59855. /**
  59856. * Clones the color gradind texture.
  59857. */
  59858. ColorGradingTexture.prototype.clone = function () {
  59859. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  59860. // Base texture
  59861. newTexture.level = this.level;
  59862. return newTexture;
  59863. };
  59864. /**
  59865. * Called during delayed load for textures.
  59866. */
  59867. ColorGradingTexture.prototype.delayLoad = function () {
  59868. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59869. return;
  59870. }
  59871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59872. this._texture = this._getFromCache(this.url, true);
  59873. if (!this._texture) {
  59874. this.loadTexture();
  59875. }
  59876. };
  59877. /**
  59878. * Binds the color grading to the shader.
  59879. * @param colorGrading The texture to bind
  59880. * @param effect The effect to bind to
  59881. */
  59882. ColorGradingTexture.Bind = function (colorGrading, effect) {
  59883. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  59884. var x = colorGrading.level; // Texture Level
  59885. var y = colorGrading.getSize().height; // Texture Size example with 8
  59886. var z = y - 1.0; // SizeMinusOne 8 - 1
  59887. var w = 1 / y; // Space of 1 slice 1 / 8
  59888. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  59889. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  59890. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  59891. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  59892. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  59893. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  59894. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  59895. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  59896. };
  59897. /**
  59898. * Prepare the list of uniforms associated with the ColorGrading effects.
  59899. * @param uniformsList The list of uniforms used in the effect
  59900. * @param samplersList The list of samplers used in the effect
  59901. */
  59902. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  59903. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  59904. samplersList.push("cameraColorGrading2DSampler");
  59905. };
  59906. /**
  59907. * Parses a color grading texture serialized by Babylon.
  59908. * @param parsedTexture The texture information being parsedTexture
  59909. * @param scene The scene to load the texture in
  59910. * @param rootUrl The root url of the data assets to load
  59911. * @return A color gradind texture
  59912. */
  59913. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59914. var texture = null;
  59915. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59916. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  59917. texture.name = parsedTexture.name;
  59918. texture.level = parsedTexture.level;
  59919. }
  59920. return texture;
  59921. };
  59922. /**
  59923. * Serializes the LUT texture to json format.
  59924. */
  59925. ColorGradingTexture.prototype.serialize = function () {
  59926. if (!this.name) {
  59927. return null;
  59928. }
  59929. var serializationObject = {};
  59930. serializationObject.name = this.name;
  59931. serializationObject.level = this.level;
  59932. serializationObject.customType = "BABYLON.ColorGradingTexture";
  59933. return serializationObject;
  59934. };
  59935. return ColorGradingTexture;
  59936. }(BABYLON.BaseTexture));
  59937. /**
  59938. * Empty line regex stored for GC.
  59939. */
  59940. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  59941. BABYLON.ColorGradingTexture = ColorGradingTexture;
  59942. })(BABYLON || (BABYLON = {}));
  59943. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  59944. var BABYLON;
  59945. (function (BABYLON) {
  59946. /**
  59947. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59948. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59949. * 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;
  59950. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59951. */
  59952. var ColorCurves = (function () {
  59953. function ColorCurves() {
  59954. this._dirty = true;
  59955. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59956. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59957. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59958. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59959. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59960. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59961. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59962. this._globalHue = 30;
  59963. this._globalDensity = 0;
  59964. this._globalSaturation = 0;
  59965. this._globalExposure = 0;
  59966. this._highlightsHue = 30;
  59967. this._highlightsDensity = 0;
  59968. this._highlightsSaturation = 0;
  59969. this._highlightsExposure = 0;
  59970. this._midtonesHue = 30;
  59971. this._midtonesDensity = 0;
  59972. this._midtonesSaturation = 0;
  59973. this._midtonesExposure = 0;
  59974. this._shadowsHue = 30;
  59975. this._shadowsDensity = 0;
  59976. this._shadowsSaturation = 0;
  59977. this._shadowsExposure = 0;
  59978. }
  59979. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  59980. /**
  59981. * Gets the global Hue value.
  59982. * 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).
  59983. */
  59984. get: function () {
  59985. return this._globalHue;
  59986. },
  59987. /**
  59988. * Sets the global Hue value.
  59989. * 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).
  59990. */
  59991. set: function (value) {
  59992. this._globalHue = value;
  59993. this._dirty = true;
  59994. },
  59995. enumerable: true,
  59996. configurable: true
  59997. });
  59998. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  59999. /**
  60000. * Gets the global Density value.
  60001. * 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.
  60002. * Values less than zero provide a filter of opposite hue.
  60003. */
  60004. get: function () {
  60005. return this._globalDensity;
  60006. },
  60007. /**
  60008. * Sets the global Density value.
  60009. * 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.
  60010. * Values less than zero provide a filter of opposite hue.
  60011. */
  60012. set: function (value) {
  60013. this._globalDensity = value;
  60014. this._dirty = true;
  60015. },
  60016. enumerable: true,
  60017. configurable: true
  60018. });
  60019. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  60020. /**
  60021. * Gets the global Saturation value.
  60022. * 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.
  60023. */
  60024. get: function () {
  60025. return this._globalSaturation;
  60026. },
  60027. /**
  60028. * Sets the global Saturation value.
  60029. * 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.
  60030. */
  60031. set: function (value) {
  60032. this._globalSaturation = value;
  60033. this._dirty = true;
  60034. },
  60035. enumerable: true,
  60036. configurable: true
  60037. });
  60038. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  60039. /**
  60040. * Gets the highlights Hue value.
  60041. * 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).
  60042. */
  60043. get: function () {
  60044. return this._highlightsHue;
  60045. },
  60046. /**
  60047. * Sets the highlights Hue value.
  60048. * 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).
  60049. */
  60050. set: function (value) {
  60051. this._highlightsHue = value;
  60052. this._dirty = true;
  60053. },
  60054. enumerable: true,
  60055. configurable: true
  60056. });
  60057. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  60058. /**
  60059. * Gets the highlights Density value.
  60060. * 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.
  60061. * Values less than zero provide a filter of opposite hue.
  60062. */
  60063. get: function () {
  60064. return this._highlightsDensity;
  60065. },
  60066. /**
  60067. * Sets the highlights Density value.
  60068. * 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.
  60069. * Values less than zero provide a filter of opposite hue.
  60070. */
  60071. set: function (value) {
  60072. this._highlightsDensity = value;
  60073. this._dirty = true;
  60074. },
  60075. enumerable: true,
  60076. configurable: true
  60077. });
  60078. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  60079. /**
  60080. * Gets the highlights Saturation value.
  60081. * 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.
  60082. */
  60083. get: function () {
  60084. return this._highlightsSaturation;
  60085. },
  60086. /**
  60087. * Sets the highlights Saturation value.
  60088. * 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.
  60089. */
  60090. set: function (value) {
  60091. this._highlightsSaturation = value;
  60092. this._dirty = true;
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  60098. /**
  60099. * Gets the highlights Exposure value.
  60100. * 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.
  60101. */
  60102. get: function () {
  60103. return this._highlightsExposure;
  60104. },
  60105. /**
  60106. * Sets the highlights Exposure value.
  60107. * 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.
  60108. */
  60109. set: function (value) {
  60110. this._highlightsExposure = value;
  60111. this._dirty = true;
  60112. },
  60113. enumerable: true,
  60114. configurable: true
  60115. });
  60116. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  60117. /**
  60118. * Gets the midtones Hue value.
  60119. * 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).
  60120. */
  60121. get: function () {
  60122. return this._midtonesHue;
  60123. },
  60124. /**
  60125. * Sets the midtones Hue value.
  60126. * 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).
  60127. */
  60128. set: function (value) {
  60129. this._midtonesHue = value;
  60130. this._dirty = true;
  60131. },
  60132. enumerable: true,
  60133. configurable: true
  60134. });
  60135. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  60136. /**
  60137. * Gets the midtones Density value.
  60138. * 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.
  60139. * Values less than zero provide a filter of opposite hue.
  60140. */
  60141. get: function () {
  60142. return this._midtonesDensity;
  60143. },
  60144. /**
  60145. * Sets the midtones Density value.
  60146. * 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.
  60147. * Values less than zero provide a filter of opposite hue.
  60148. */
  60149. set: function (value) {
  60150. this._midtonesDensity = value;
  60151. this._dirty = true;
  60152. },
  60153. enumerable: true,
  60154. configurable: true
  60155. });
  60156. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  60157. /**
  60158. * Gets the midtones Saturation value.
  60159. * 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.
  60160. */
  60161. get: function () {
  60162. return this._midtonesSaturation;
  60163. },
  60164. /**
  60165. * Sets the midtones Saturation value.
  60166. * 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.
  60167. */
  60168. set: function (value) {
  60169. this._midtonesSaturation = value;
  60170. this._dirty = true;
  60171. },
  60172. enumerable: true,
  60173. configurable: true
  60174. });
  60175. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  60176. /**
  60177. * Gets the midtones Exposure value.
  60178. * 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.
  60179. */
  60180. get: function () {
  60181. return this._midtonesExposure;
  60182. },
  60183. /**
  60184. * Sets the midtones Exposure value.
  60185. * 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.
  60186. */
  60187. set: function (value) {
  60188. this._midtonesExposure = value;
  60189. this._dirty = true;
  60190. },
  60191. enumerable: true,
  60192. configurable: true
  60193. });
  60194. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  60195. /**
  60196. * Gets the shadows Hue value.
  60197. * 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).
  60198. */
  60199. get: function () {
  60200. return this._shadowsHue;
  60201. },
  60202. /**
  60203. * Sets the shadows Hue value.
  60204. * 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).
  60205. */
  60206. set: function (value) {
  60207. this._shadowsHue = value;
  60208. this._dirty = true;
  60209. },
  60210. enumerable: true,
  60211. configurable: true
  60212. });
  60213. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  60214. /**
  60215. * Gets the shadows Density value.
  60216. * 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.
  60217. * Values less than zero provide a filter of opposite hue.
  60218. */
  60219. get: function () {
  60220. return this._shadowsDensity;
  60221. },
  60222. /**
  60223. * Sets the shadows Density value.
  60224. * 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.
  60225. * Values less than zero provide a filter of opposite hue.
  60226. */
  60227. set: function (value) {
  60228. this._shadowsDensity = value;
  60229. this._dirty = true;
  60230. },
  60231. enumerable: true,
  60232. configurable: true
  60233. });
  60234. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  60235. /**
  60236. * Gets the shadows Saturation value.
  60237. * 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.
  60238. */
  60239. get: function () {
  60240. return this._shadowsSaturation;
  60241. },
  60242. /**
  60243. * Sets the shadows Saturation value.
  60244. * 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.
  60245. */
  60246. set: function (value) {
  60247. this._shadowsSaturation = value;
  60248. this._dirty = true;
  60249. },
  60250. enumerable: true,
  60251. configurable: true
  60252. });
  60253. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  60254. /**
  60255. * Gets the shadows Exposure value.
  60256. * 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.
  60257. */
  60258. get: function () {
  60259. return this._shadowsExposure;
  60260. },
  60261. /**
  60262. * Sets the shadows Exposure value.
  60263. * 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.
  60264. */
  60265. set: function (value) {
  60266. this._shadowsExposure = value;
  60267. this._dirty = true;
  60268. },
  60269. enumerable: true,
  60270. configurable: true
  60271. });
  60272. /**
  60273. * Binds the color curves to the shader.
  60274. * @param colorCurves The color curve to bind
  60275. * @param effect The effect to bind to
  60276. */
  60277. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  60278. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  60279. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  60280. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  60281. if (colorCurves._dirty) {
  60282. colorCurves._dirty = false;
  60283. // Fill in global info.
  60284. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60285. // Compute highlights info.
  60286. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60287. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60288. // Compute midtones info.
  60289. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60290. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60291. // Compute shadows info.
  60292. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60293. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60294. // Compute deltas (neutral is midtones).
  60295. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60296. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60297. }
  60298. if (effect) {
  60299. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60300. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60301. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  60302. }
  60303. };
  60304. /**
  60305. * Prepare the list of uniforms associated with the ColorCurves effects.
  60306. * @param uniformsList The list of uniforms used in the effect
  60307. */
  60308. ColorCurves.PrepareUniforms = function (uniformsList) {
  60309. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  60310. };
  60311. /**
  60312. * Returns color grading data based on a hue, density, saturation and exposure value.
  60313. * @param filterHue The hue of the color filter.
  60314. * @param filterDensity The density of the color filter.
  60315. * @param saturation The saturation.
  60316. * @param exposure The exposure.
  60317. * @param result The result data container.
  60318. */
  60319. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  60320. if (hue == null) {
  60321. return;
  60322. }
  60323. hue = ColorCurves.clamp(hue, 0, 360);
  60324. density = ColorCurves.clamp(density, -100, 100);
  60325. saturation = ColorCurves.clamp(saturation, -100, 100);
  60326. exposure = ColorCurves.clamp(exposure, -100, 100);
  60327. // Remap the slider/config filter density with non-linear mapping and also scale by half
  60328. // so that the maximum filter density is only 50% control. This provides fine control
  60329. // for small values and reasonable range.
  60330. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  60331. density *= 0.5;
  60332. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  60333. if (density < 0) {
  60334. density *= -1;
  60335. hue = (hue + 180) % 360;
  60336. }
  60337. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  60338. result.scaleToRef(2, result);
  60339. result.a = 1 + 0.01 * saturation;
  60340. };
  60341. /**
  60342. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  60343. * @param value The input slider value in range [-100,100].
  60344. * @returns Adjusted value.
  60345. */
  60346. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  60347. value /= 100;
  60348. var x = Math.abs(value);
  60349. x = Math.pow(x, 2);
  60350. if (value < 0) {
  60351. x *= -1;
  60352. }
  60353. x *= 100;
  60354. return x;
  60355. };
  60356. /**
  60357. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  60358. * @param hue The hue (H) input.
  60359. * @param saturation The saturation (S) input.
  60360. * @param brightness The brightness (B) input.
  60361. * @result An RGBA color represented as Vector4.
  60362. */
  60363. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  60364. var h = ColorCurves.clamp(hue, 0, 360);
  60365. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  60366. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  60367. if (s === 0) {
  60368. result.r = v;
  60369. result.g = v;
  60370. result.b = v;
  60371. }
  60372. else {
  60373. // sector 0 to 5
  60374. h /= 60;
  60375. var i = Math.floor(h);
  60376. // fractional part of h
  60377. var f = h - i;
  60378. var p = v * (1 - s);
  60379. var q = v * (1 - s * f);
  60380. var t = v * (1 - s * (1 - f));
  60381. switch (i) {
  60382. case 0:
  60383. result.r = v;
  60384. result.g = t;
  60385. result.b = p;
  60386. break;
  60387. case 1:
  60388. result.r = q;
  60389. result.g = v;
  60390. result.b = p;
  60391. break;
  60392. case 2:
  60393. result.r = p;
  60394. result.g = v;
  60395. result.b = t;
  60396. break;
  60397. case 3:
  60398. result.r = p;
  60399. result.g = q;
  60400. result.b = v;
  60401. break;
  60402. case 4:
  60403. result.r = t;
  60404. result.g = p;
  60405. result.b = v;
  60406. break;
  60407. default:
  60408. result.r = v;
  60409. result.g = p;
  60410. result.b = q;
  60411. break;
  60412. }
  60413. }
  60414. result.a = 1;
  60415. };
  60416. /**
  60417. * Returns a value clamped between min and max
  60418. * @param value The value to clamp
  60419. * @param min The minimum of value
  60420. * @param max The maximum of value
  60421. * @returns The clamped value.
  60422. */
  60423. ColorCurves.clamp = function (value, min, max) {
  60424. return Math.min(Math.max(value, min), max);
  60425. };
  60426. /**
  60427. * Clones the current color curve instance.
  60428. * @return The cloned curves
  60429. */
  60430. ColorCurves.prototype.clone = function () {
  60431. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  60432. };
  60433. /**
  60434. * Serializes the current color curve instance to a json representation.
  60435. * @return a JSON representation
  60436. */
  60437. ColorCurves.prototype.serialize = function () {
  60438. return BABYLON.SerializationHelper.Serialize(this);
  60439. };
  60440. /**
  60441. * Parses the color curve from a json representation.
  60442. * @param source the JSON source to parse
  60443. * @return The parsed curves
  60444. */
  60445. ColorCurves.Parse = function (source) {
  60446. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  60447. };
  60448. return ColorCurves;
  60449. }());
  60450. __decorate([
  60451. BABYLON.serialize()
  60452. ], ColorCurves.prototype, "_globalHue", void 0);
  60453. __decorate([
  60454. BABYLON.serialize()
  60455. ], ColorCurves.prototype, "_globalDensity", void 0);
  60456. __decorate([
  60457. BABYLON.serialize()
  60458. ], ColorCurves.prototype, "_globalSaturation", void 0);
  60459. __decorate([
  60460. BABYLON.serialize()
  60461. ], ColorCurves.prototype, "_globalExposure", void 0);
  60462. __decorate([
  60463. BABYLON.serialize()
  60464. ], ColorCurves.prototype, "_highlightsHue", void 0);
  60465. __decorate([
  60466. BABYLON.serialize()
  60467. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  60468. __decorate([
  60469. BABYLON.serialize()
  60470. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  60471. __decorate([
  60472. BABYLON.serialize()
  60473. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  60474. __decorate([
  60475. BABYLON.serialize()
  60476. ], ColorCurves.prototype, "_midtonesHue", void 0);
  60477. __decorate([
  60478. BABYLON.serialize()
  60479. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  60480. __decorate([
  60481. BABYLON.serialize()
  60482. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60483. __decorate([
  60484. BABYLON.serialize()
  60485. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60486. BABYLON.ColorCurves = ColorCurves;
  60487. })(BABYLON || (BABYLON = {}));
  60488. //# sourceMappingURL=babylon.colorCurves.js.map
  60489. var BABYLON;
  60490. (function (BABYLON) {
  60491. var Octree = (function () {
  60492. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  60493. if (maxDepth === void 0) { maxDepth = 2; }
  60494. this.maxDepth = maxDepth;
  60495. this.dynamicContent = new Array();
  60496. this._maxBlockCapacity = maxBlockCapacity || 64;
  60497. this._selectionContent = new BABYLON.SmartArray(1024);
  60498. this._creationFunc = creationFunc;
  60499. }
  60500. // Methods
  60501. Octree.prototype.update = function (worldMin, worldMax, entries) {
  60502. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  60503. };
  60504. Octree.prototype.addMesh = function (entry) {
  60505. for (var index = 0; index < this.blocks.length; index++) {
  60506. var block = this.blocks[index];
  60507. block.addEntry(entry);
  60508. }
  60509. };
  60510. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  60511. this._selectionContent.reset();
  60512. for (var index = 0; index < this.blocks.length; index++) {
  60513. var block = this.blocks[index];
  60514. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  60515. }
  60516. if (allowDuplicate) {
  60517. this._selectionContent.concat(this.dynamicContent);
  60518. }
  60519. else {
  60520. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  60521. }
  60522. return this._selectionContent;
  60523. };
  60524. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  60525. this._selectionContent.reset();
  60526. for (var index = 0; index < this.blocks.length; index++) {
  60527. var block = this.blocks[index];
  60528. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  60529. }
  60530. if (allowDuplicate) {
  60531. this._selectionContent.concat(this.dynamicContent);
  60532. }
  60533. else {
  60534. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  60535. }
  60536. return this._selectionContent;
  60537. };
  60538. Octree.prototype.intersectsRay = function (ray) {
  60539. this._selectionContent.reset();
  60540. for (var index = 0; index < this.blocks.length; index++) {
  60541. var block = this.blocks[index];
  60542. block.intersectsRay(ray, this._selectionContent);
  60543. }
  60544. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  60545. return this._selectionContent;
  60546. };
  60547. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  60548. target.blocks = new Array();
  60549. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  60550. // Segmenting space
  60551. for (var x = 0; x < 2; x++) {
  60552. for (var y = 0; y < 2; y++) {
  60553. for (var z = 0; z < 2; z++) {
  60554. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  60555. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  60556. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  60557. block.addEntries(entries);
  60558. target.blocks.push(block);
  60559. }
  60560. }
  60561. }
  60562. };
  60563. return Octree;
  60564. }());
  60565. Octree.CreationFuncForMeshes = function (entry, block) {
  60566. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  60567. block.entries.push(entry);
  60568. }
  60569. };
  60570. Octree.CreationFuncForSubMeshes = function (entry, block) {
  60571. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  60572. block.entries.push(entry);
  60573. }
  60574. };
  60575. BABYLON.Octree = Octree;
  60576. })(BABYLON || (BABYLON = {}));
  60577. //# sourceMappingURL=babylon.octree.js.map
  60578. var BABYLON;
  60579. (function (BABYLON) {
  60580. var OctreeBlock = (function () {
  60581. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  60582. this.entries = new Array();
  60583. this._boundingVectors = new Array();
  60584. this._capacity = capacity;
  60585. this._depth = depth;
  60586. this._maxDepth = maxDepth;
  60587. this._creationFunc = creationFunc;
  60588. this._minPoint = minPoint;
  60589. this._maxPoint = maxPoint;
  60590. this._boundingVectors.push(minPoint.clone());
  60591. this._boundingVectors.push(maxPoint.clone());
  60592. this._boundingVectors.push(minPoint.clone());
  60593. this._boundingVectors[2].x = maxPoint.x;
  60594. this._boundingVectors.push(minPoint.clone());
  60595. this._boundingVectors[3].y = maxPoint.y;
  60596. this._boundingVectors.push(minPoint.clone());
  60597. this._boundingVectors[4].z = maxPoint.z;
  60598. this._boundingVectors.push(maxPoint.clone());
  60599. this._boundingVectors[5].z = minPoint.z;
  60600. this._boundingVectors.push(maxPoint.clone());
  60601. this._boundingVectors[6].x = minPoint.x;
  60602. this._boundingVectors.push(maxPoint.clone());
  60603. this._boundingVectors[7].y = minPoint.y;
  60604. }
  60605. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  60606. // Property
  60607. get: function () {
  60608. return this._capacity;
  60609. },
  60610. enumerable: true,
  60611. configurable: true
  60612. });
  60613. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  60614. get: function () {
  60615. return this._minPoint;
  60616. },
  60617. enumerable: true,
  60618. configurable: true
  60619. });
  60620. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  60621. get: function () {
  60622. return this._maxPoint;
  60623. },
  60624. enumerable: true,
  60625. configurable: true
  60626. });
  60627. // Methods
  60628. OctreeBlock.prototype.addEntry = function (entry) {
  60629. if (this.blocks) {
  60630. for (var index = 0; index < this.blocks.length; index++) {
  60631. var block = this.blocks[index];
  60632. block.addEntry(entry);
  60633. }
  60634. return;
  60635. }
  60636. this._creationFunc(entry, this);
  60637. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  60638. this.createInnerBlocks();
  60639. }
  60640. };
  60641. OctreeBlock.prototype.addEntries = function (entries) {
  60642. for (var index = 0; index < entries.length; index++) {
  60643. var mesh = entries[index];
  60644. this.addEntry(mesh);
  60645. }
  60646. };
  60647. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  60648. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  60649. if (this.blocks) {
  60650. for (var index = 0; index < this.blocks.length; index++) {
  60651. var block = this.blocks[index];
  60652. block.select(frustumPlanes, selection, allowDuplicate);
  60653. }
  60654. return;
  60655. }
  60656. if (allowDuplicate) {
  60657. selection.concat(this.entries);
  60658. }
  60659. else {
  60660. selection.concatWithNoDuplicate(this.entries);
  60661. }
  60662. }
  60663. };
  60664. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  60665. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  60666. if (this.blocks) {
  60667. for (var index = 0; index < this.blocks.length; index++) {
  60668. var block = this.blocks[index];
  60669. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  60670. }
  60671. return;
  60672. }
  60673. if (allowDuplicate) {
  60674. selection.concat(this.entries);
  60675. }
  60676. else {
  60677. selection.concatWithNoDuplicate(this.entries);
  60678. }
  60679. }
  60680. };
  60681. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  60682. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  60683. if (this.blocks) {
  60684. for (var index = 0; index < this.blocks.length; index++) {
  60685. var block = this.blocks[index];
  60686. block.intersectsRay(ray, selection);
  60687. }
  60688. return;
  60689. }
  60690. selection.concatWithNoDuplicate(this.entries);
  60691. }
  60692. };
  60693. OctreeBlock.prototype.createInnerBlocks = function () {
  60694. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  60695. };
  60696. return OctreeBlock;
  60697. }());
  60698. BABYLON.OctreeBlock = OctreeBlock;
  60699. })(BABYLON || (BABYLON = {}));
  60700. //# sourceMappingURL=babylon.octreeBlock.js.map
  60701. var BABYLON;
  60702. (function (BABYLON) {
  60703. var SIMDVector3 = (function () {
  60704. function SIMDVector3() {
  60705. }
  60706. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  60707. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  60708. };
  60709. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  60710. var m = transformation.m;
  60711. var m0 = SIMD.Float32x4.load(m, 0);
  60712. var m1 = SIMD.Float32x4.load(m, 4);
  60713. var m2 = SIMD.Float32x4.load(m, 8);
  60714. var m3 = SIMD.Float32x4.load(m, 12);
  60715. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  60716. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  60717. result.x = SIMD.Float32x4.extractLane(r, 0);
  60718. result.y = SIMD.Float32x4.extractLane(r, 1);
  60719. result.z = SIMD.Float32x4.extractLane(r, 2);
  60720. };
  60721. return SIMDVector3;
  60722. }());
  60723. var SIMDMatrix = (function () {
  60724. function SIMDMatrix() {
  60725. }
  60726. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  60727. var tm = this.m;
  60728. var om = other.m;
  60729. var m0 = SIMD.Float32x4.load(om, 0);
  60730. var m1 = SIMD.Float32x4.load(om, 4);
  60731. var m2 = SIMD.Float32x4.load(om, 8);
  60732. var m3 = SIMD.Float32x4.load(om, 12);
  60733. for (var i = 0; i < 16; i += 4) {
  60734. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  60735. }
  60736. return this;
  60737. };
  60738. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  60739. var src = this.m;
  60740. var dest = other.m;
  60741. // Load the 4 rows
  60742. var src0 = SIMD.Float32x4.load(src, 0);
  60743. var src1 = SIMD.Float32x4.load(src, 4);
  60744. var src2 = SIMD.Float32x4.load(src, 8);
  60745. var src3 = SIMD.Float32x4.load(src, 12);
  60746. // Transpose the source matrix. Sort of. Not a true transpose operation
  60747. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  60748. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  60749. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  60750. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  60751. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  60752. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  60753. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  60754. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  60755. // This is a true transposition, but it will lead to an incorrect result
  60756. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  60757. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  60758. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  60759. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  60760. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  60761. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  60762. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  60763. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  60764. // ----
  60765. tmp1 = SIMD.Float32x4.mul(row2, row3);
  60766. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60767. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  60768. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  60769. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60770. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  60771. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  60772. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  60773. // ----
  60774. tmp1 = SIMD.Float32x4.mul(row1, row2);
  60775. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60776. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  60777. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  60778. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60779. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  60780. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  60781. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  60782. // ----
  60783. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  60784. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60785. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  60786. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  60787. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  60788. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60789. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  60790. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  60791. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  60792. // ----
  60793. tmp1 = SIMD.Float32x4.mul(row0, row1);
  60794. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60795. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  60796. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  60797. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60798. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  60799. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  60800. // ----
  60801. tmp1 = SIMD.Float32x4.mul(row0, row3);
  60802. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60803. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  60804. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  60805. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60806. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  60807. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  60808. // ----
  60809. tmp1 = SIMD.Float32x4.mul(row0, row2);
  60810. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60811. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  60812. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  60813. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60814. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  60815. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  60816. // Compute determinant
  60817. var det = SIMD.Float32x4.mul(row0, minor0);
  60818. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  60819. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  60820. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  60821. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  60822. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  60823. // These shuffles aren't necessary if the faulty transposition is done
  60824. // up at the top of this function.
  60825. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  60826. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  60827. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  60828. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  60829. // Compute final values by multiplying with 1/det
  60830. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  60831. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  60832. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  60833. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  60834. return this;
  60835. };
  60836. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  60837. var out = result.m;
  60838. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  60839. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  60840. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  60841. // cc.kmVec3Subtract(f, pCenter, pEye);
  60842. var f = SIMD.Float32x4.sub(center, eye);
  60843. // cc.kmVec3Normalize(f, f);
  60844. var tmp = SIMD.Float32x4.mul(f, f);
  60845. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60846. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60847. // cc.kmVec3Assign(up, pUp);
  60848. // cc.kmVec3Normalize(up, up);
  60849. tmp = SIMD.Float32x4.mul(up, up);
  60850. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60851. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60852. // cc.kmVec3Cross(s, f, up);
  60853. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  60854. // cc.kmVec3Normalize(s, s);
  60855. tmp = SIMD.Float32x4.mul(s, s);
  60856. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60857. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60858. // cc.kmVec3Cross(u, s, f);
  60859. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  60860. // cc.kmVec3Normalize(s, s);
  60861. tmp = SIMD.Float32x4.mul(s, s);
  60862. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60863. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60864. var zero = SIMD.Float32x4.splat(0.0);
  60865. s = SIMD.Float32x4.neg(s);
  60866. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  60867. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  60868. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  60869. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  60870. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  60871. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  60872. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  60873. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  60874. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  60875. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  60876. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  60877. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  60878. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  60879. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  60880. };
  60881. return SIMDMatrix;
  60882. }());
  60883. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  60884. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  60885. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  60886. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  60887. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  60888. var SIMDHelper = (function () {
  60889. function SIMDHelper() {
  60890. }
  60891. Object.defineProperty(SIMDHelper, "IsEnabled", {
  60892. get: function () {
  60893. return SIMDHelper._isEnabled;
  60894. },
  60895. enumerable: true,
  60896. configurable: true
  60897. });
  60898. SIMDHelper.DisableSIMD = function () {
  60899. // Replace functions
  60900. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  60901. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  60902. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  60903. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  60904. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  60905. SIMDHelper._isEnabled = false;
  60906. };
  60907. SIMDHelper.EnableSIMD = function () {
  60908. if (self.SIMD === undefined) {
  60909. return;
  60910. }
  60911. // check if polyfills needed
  60912. if (!self.Math.fround) {
  60913. self.Math.fround = (function (array) { return function (x) {
  60914. return array[0] = x, array[0];
  60915. }; })(new Float32Array(1));
  60916. }
  60917. if (!self.Math.imul) {
  60918. self.Math.imul = function (a, b) {
  60919. var ah = (a >>> 16) & 0xffff;
  60920. var al = a & 0xffff;
  60921. var bh = (b >>> 16) & 0xffff;
  60922. var bl = b & 0xffff;
  60923. // the shift by 0 fixes the sign on the high part
  60924. // the final |0 converts the unsigned value into a signed value
  60925. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  60926. };
  60927. }
  60928. // Replace functions
  60929. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  60930. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  60931. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  60932. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  60933. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  60934. SIMDHelper._isEnabled = true;
  60935. };
  60936. return SIMDHelper;
  60937. }());
  60938. SIMDHelper._isEnabled = false;
  60939. BABYLON.SIMDHelper = SIMDHelper;
  60940. })(BABYLON || (BABYLON = {}));
  60941. //# sourceMappingURL=babylon.math.SIMD.js.map
  60942. var BABYLON;
  60943. (function (BABYLON) {
  60944. var VRDistortionCorrectionPostProcess = (function (_super) {
  60945. __extends(VRDistortionCorrectionPostProcess, _super);
  60946. //ANY
  60947. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  60948. var _this = _super.call(this, name, "vrDistortionCorrection", [
  60949. 'LensCenter',
  60950. 'Scale',
  60951. 'ScaleIn',
  60952. 'HmdWarpParam'
  60953. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  60954. _this._isRightEye = isRightEye;
  60955. _this._distortionFactors = vrMetrics.distortionK;
  60956. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  60957. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  60958. _this.onSizeChangedObservable.add(function () {
  60959. _this.aspectRatio = _this.width * .5 / _this.height;
  60960. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  60961. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  60962. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  60963. });
  60964. _this.onApplyObservable.add(function (effect) {
  60965. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  60966. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  60967. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  60968. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  60969. });
  60970. return _this;
  60971. }
  60972. return VRDistortionCorrectionPostProcess;
  60973. }(BABYLON.PostProcess));
  60974. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  60975. })(BABYLON || (BABYLON = {}));
  60976. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  60977. var BABYLON;
  60978. (function (BABYLON) {
  60979. var AnaglyphPostProcess = (function (_super) {
  60980. __extends(AnaglyphPostProcess, _super);
  60981. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  60982. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  60983. _this._passedProcess = rigCameras[0]._rigPostProcess;
  60984. _this.onApplyObservable.add(function (effect) {
  60985. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  60986. });
  60987. return _this;
  60988. }
  60989. return AnaglyphPostProcess;
  60990. }(BABYLON.PostProcess));
  60991. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  60992. })(BABYLON || (BABYLON = {}));
  60993. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  60994. var BABYLON;
  60995. (function (BABYLON) {
  60996. var StereoscopicInterlacePostProcess = (function (_super) {
  60997. __extends(StereoscopicInterlacePostProcess, _super);
  60998. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  60999. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  61000. _this._passedProcess = rigCameras[0]._rigPostProcess;
  61001. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  61002. _this.onSizeChangedObservable.add(function () {
  61003. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  61004. });
  61005. _this.onApplyObservable.add(function (effect) {
  61006. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  61007. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  61008. });
  61009. return _this;
  61010. }
  61011. return StereoscopicInterlacePostProcess;
  61012. }(BABYLON.PostProcess));
  61013. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  61014. })(BABYLON || (BABYLON = {}));
  61015. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  61016. var BABYLON;
  61017. (function (BABYLON) {
  61018. var FreeCameraDeviceOrientationInput = (function () {
  61019. function FreeCameraDeviceOrientationInput() {
  61020. var _this = this;
  61021. this._screenOrientationAngle = 0;
  61022. this._screenQuaternion = new BABYLON.Quaternion();
  61023. this._alpha = 0;
  61024. this._beta = 0;
  61025. this._gamma = 0;
  61026. this._orientationChanged = function () {
  61027. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  61028. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  61029. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  61030. };
  61031. this._deviceOrientation = function (evt) {
  61032. _this._alpha = evt.alpha;
  61033. _this._beta = evt.beta;
  61034. _this._gamma = evt.gamma;
  61035. };
  61036. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  61037. this._orientationChanged();
  61038. }
  61039. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  61040. get: function () {
  61041. return this._camera;
  61042. },
  61043. set: function (camera) {
  61044. this._camera = camera;
  61045. if (!this._camera.rotationQuaternion)
  61046. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  61047. },
  61048. enumerable: true,
  61049. configurable: true
  61050. });
  61051. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  61052. window.addEventListener("orientationchange", this._orientationChanged);
  61053. window.addEventListener("deviceorientation", this._deviceOrientation);
  61054. //In certain cases, the attach control is called AFTER orientation was changed,
  61055. //So this is needed.
  61056. this._orientationChanged();
  61057. };
  61058. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  61059. window.removeEventListener("orientationchange", this._orientationChanged);
  61060. window.removeEventListener("deviceorientation", this._deviceOrientation);
  61061. };
  61062. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  61063. //if no device orientation provided, don't update the rotation.
  61064. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  61065. if (!this._alpha)
  61066. return;
  61067. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  61068. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  61069. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  61070. //Mirror on XY Plane
  61071. this._camera.rotationQuaternion.z *= -1;
  61072. this._camera.rotationQuaternion.w *= -1;
  61073. };
  61074. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  61075. return "FreeCameraDeviceOrientationInput";
  61076. };
  61077. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  61078. return "deviceOrientation";
  61079. };
  61080. return FreeCameraDeviceOrientationInput;
  61081. }());
  61082. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  61083. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  61084. })(BABYLON || (BABYLON = {}));
  61085. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  61086. var BABYLON;
  61087. (function (BABYLON) {
  61088. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  61089. function ArcRotateCameraVRDeviceOrientationInput() {
  61090. this.alphaCorrection = 1;
  61091. this.betaCorrection = 1;
  61092. this.gammaCorrection = 1;
  61093. this._alpha = 0;
  61094. this._beta = 0;
  61095. this._gamma = 0;
  61096. this._dirty = false;
  61097. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  61098. }
  61099. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  61100. this.camera.attachControl(element, noPreventDefault);
  61101. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  61102. };
  61103. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  61104. var camera = this.camera;
  61105. this._alpha = +evt.alpha | 0;
  61106. this._beta = +evt.beta | 0;
  61107. this._gamma = +evt.gamma | 0;
  61108. this._dirty = true;
  61109. };
  61110. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  61111. if (this._dirty) {
  61112. this._dirty = false;
  61113. if (this._gamma < 0) {
  61114. this._gamma = 180 + this._gamma;
  61115. }
  61116. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  61117. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  61118. }
  61119. };
  61120. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  61121. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  61122. };
  61123. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  61124. return "ArcRotateCameraVRDeviceOrientationInput";
  61125. };
  61126. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  61127. return "VRDeviceOrientation";
  61128. };
  61129. return ArcRotateCameraVRDeviceOrientationInput;
  61130. }());
  61131. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  61132. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  61133. })(BABYLON || (BABYLON = {}));
  61134. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  61135. var BABYLON;
  61136. (function (BABYLON) {
  61137. var VRCameraMetrics = (function () {
  61138. function VRCameraMetrics() {
  61139. this.compensateDistortion = true;
  61140. }
  61141. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  61142. get: function () {
  61143. return this.hResolution / (2 * this.vResolution);
  61144. },
  61145. enumerable: true,
  61146. configurable: true
  61147. });
  61148. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  61149. get: function () {
  61150. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  61151. },
  61152. enumerable: true,
  61153. configurable: true
  61154. });
  61155. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  61156. get: function () {
  61157. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61158. var h = (4 * meters) / this.hScreenSize;
  61159. return BABYLON.Matrix.Translation(h, 0, 0);
  61160. },
  61161. enumerable: true,
  61162. configurable: true
  61163. });
  61164. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  61165. get: function () {
  61166. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61167. var h = (4 * meters) / this.hScreenSize;
  61168. return BABYLON.Matrix.Translation(-h, 0, 0);
  61169. },
  61170. enumerable: true,
  61171. configurable: true
  61172. });
  61173. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  61174. get: function () {
  61175. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  61176. },
  61177. enumerable: true,
  61178. configurable: true
  61179. });
  61180. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  61181. get: function () {
  61182. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  61183. },
  61184. enumerable: true,
  61185. configurable: true
  61186. });
  61187. VRCameraMetrics.GetDefault = function () {
  61188. var result = new VRCameraMetrics();
  61189. result.hResolution = 1280;
  61190. result.vResolution = 800;
  61191. result.hScreenSize = 0.149759993;
  61192. result.vScreenSize = 0.0935999975;
  61193. result.vScreenCenter = 0.0467999987;
  61194. result.eyeToScreenDistance = 0.0410000011;
  61195. result.lensSeparationDistance = 0.0635000020;
  61196. result.interpupillaryDistance = 0.0640000030;
  61197. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  61198. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  61199. result.postProcessScaleFactor = 1.714605507808412;
  61200. result.lensCenterOffset = 0.151976421;
  61201. return result;
  61202. };
  61203. return VRCameraMetrics;
  61204. }());
  61205. BABYLON.VRCameraMetrics = VRCameraMetrics;
  61206. })(BABYLON || (BABYLON = {}));
  61207. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  61208. var BABYLON;
  61209. (function (BABYLON) {
  61210. var WebVRFreeCamera = (function (_super) {
  61211. __extends(WebVRFreeCamera, _super);
  61212. function WebVRFreeCamera(name, position, scene, webVROptions) {
  61213. if (webVROptions === void 0) { webVROptions = {}; }
  61214. var _this = _super.call(this, name, position, scene) || this;
  61215. _this.webVROptions = webVROptions;
  61216. _this._vrDevice = null;
  61217. _this.rawPose = null;
  61218. _this._vrEnabled = false;
  61219. _this._specsVersion = 1.1;
  61220. _this._attached = false;
  61221. _this._positionOffset = BABYLON.Vector3.Zero();
  61222. _this._descendants = [];
  61223. _this.devicePosition = BABYLON.Vector3.Zero();
  61224. _this.deviceScaleFactor = 1;
  61225. _this.controllers = [];
  61226. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  61227. //legacy support - the compensation boolean was removed.
  61228. if (arguments.length === 5) {
  61229. _this.webVROptions = arguments[4];
  61230. }
  61231. // default webVR options
  61232. if (_this.webVROptions.trackPosition == undefined) {
  61233. _this.webVROptions.trackPosition = true;
  61234. }
  61235. if (_this.webVROptions.controllerMeshes == undefined) {
  61236. _this.webVROptions.controllerMeshes = true;
  61237. }
  61238. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  61239. _this.webVROptions.defaultLightningOnControllers = true;
  61240. }
  61241. _this.rotationQuaternion = new BABYLON.Quaternion();
  61242. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61243. if (_this.webVROptions && _this.webVROptions.positionScale) {
  61244. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  61245. }
  61246. //enable VR
  61247. _this.getEngine().initWebVR();
  61248. //check specs version
  61249. if (!window.VRFrameData) {
  61250. _this._specsVersion = 1.0;
  61251. _this._frameData = {};
  61252. }
  61253. else {
  61254. _this._frameData = new VRFrameData();
  61255. }
  61256. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  61257. if (!device) {
  61258. return;
  61259. }
  61260. _this._vrEnabled = true;
  61261. _this._vrDevice = device;
  61262. //reset the rig parameters.
  61263. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  61264. if (_this._attached) {
  61265. _this.getEngine().enableVR(_this._vrDevice);
  61266. }
  61267. });
  61268. // try to attach the controllers, if found.
  61269. _this.initControllers();
  61270. /**
  61271. * The idea behind the following lines:
  61272. * objects that have the camera as parent should actually have the rig cameras as a parent.
  61273. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  61274. * the second will not show it correctly.
  61275. *
  61276. * To solve this - each object that has the camera as parent will be added to a protected array.
  61277. * When the rig camera renders, it will take this array and set all of those to be its children.
  61278. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  61279. * Amazing!
  61280. */
  61281. scene.onBeforeCameraRenderObservable.add(function (camera) {
  61282. if (camera.parent === _this && _this.rigParenting) {
  61283. _this._descendants = _this.getDescendants(true, function (n) {
  61284. // don't take the cameras or the controllers!
  61285. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  61286. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  61287. return !isController && !isRigCamera;
  61288. });
  61289. _this._descendants.forEach(function (node) {
  61290. node.parent = camera;
  61291. });
  61292. }
  61293. });
  61294. scene.onAfterCameraRenderObservable.add(function (camera) {
  61295. if (camera.parent === _this && _this.rigParenting) {
  61296. _this._descendants.forEach(function (node) {
  61297. node.parent = _this;
  61298. });
  61299. }
  61300. });
  61301. return _this;
  61302. }
  61303. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  61304. set: function (callback) {
  61305. this._onControllersAttached = callback;
  61306. // after setting - if the controllers are already set, execute the callback.
  61307. if (this.controllers.length >= 2) {
  61308. callback(this.controllers);
  61309. }
  61310. },
  61311. enumerable: true,
  61312. configurable: true
  61313. });
  61314. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  61315. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  61316. var gp = _a[_i];
  61317. if (gp.hand === name) {
  61318. return gp;
  61319. }
  61320. }
  61321. return undefined;
  61322. };
  61323. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  61324. get: function () {
  61325. if (!this._leftController) {
  61326. this._leftController = this.getControllerByName("left");
  61327. }
  61328. return this._leftController;
  61329. },
  61330. enumerable: true,
  61331. configurable: true
  61332. });
  61333. ;
  61334. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  61335. get: function () {
  61336. if (!this._rightController) {
  61337. this._rightController = this.getControllerByName("right");
  61338. }
  61339. return this._rightController;
  61340. },
  61341. enumerable: true,
  61342. configurable: true
  61343. });
  61344. ;
  61345. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  61346. if (length === void 0) { length = 100; }
  61347. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  61348. };
  61349. WebVRFreeCamera.prototype._checkInputs = function () {
  61350. if (this._vrEnabled) {
  61351. if (this._specsVersion === 1.1) {
  61352. this._vrDevice.getFrameData(this._frameData);
  61353. }
  61354. else {
  61355. //backwards comp
  61356. var pose = this._vrDevice.getPose();
  61357. this._frameData.pose = pose;
  61358. // calculate view and projection matrix
  61359. }
  61360. this.updateFromDevice(this._frameData.pose);
  61361. }
  61362. _super.prototype._checkInputs.call(this);
  61363. };
  61364. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  61365. if (poseData && poseData.orientation) {
  61366. this.rawPose = poseData;
  61367. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  61368. if (this.getScene().useRightHandedSystem) {
  61369. this.deviceRotationQuaternion.z *= -1;
  61370. this.deviceRotationQuaternion.w *= -1;
  61371. }
  61372. if (this.webVROptions.trackPosition && this.rawPose.position) {
  61373. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  61374. if (this.getScene().useRightHandedSystem) {
  61375. this.devicePosition.z *= -1;
  61376. }
  61377. }
  61378. }
  61379. };
  61380. /**
  61381. * WebVR's attach control will start broadcasting frames to the device.
  61382. * Note that in certain browsers (chrome for example) this function must be called
  61383. * within a user-interaction callback. Example:
  61384. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  61385. *
  61386. * @param {HTMLElement} element
  61387. * @param {boolean} [noPreventDefault]
  61388. *
  61389. * @memberOf WebVRFreeCamera
  61390. */
  61391. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  61392. _super.prototype.attachControl.call(this, element, noPreventDefault);
  61393. this._attached = true;
  61394. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  61395. if (this._vrEnabled) {
  61396. this.getEngine().enableVR(this._vrDevice);
  61397. }
  61398. };
  61399. WebVRFreeCamera.prototype.detachControl = function (element) {
  61400. _super.prototype.detachControl.call(this, element);
  61401. this._vrEnabled = false;
  61402. this._attached = false;
  61403. this.getEngine().disableVR();
  61404. };
  61405. WebVRFreeCamera.prototype.getClassName = function () {
  61406. return "WebVRFreeCamera";
  61407. };
  61408. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  61409. //uses the vrDisplay's "resetPose()".
  61410. //pitch and roll won't be affected.
  61411. this._vrDevice.resetPose();
  61412. };
  61413. WebVRFreeCamera.prototype._updateRigCameras = function () {
  61414. var camLeft = this._rigCameras[0];
  61415. var camRight = this._rigCameras[1];
  61416. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61417. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61418. camLeft.position.copyFrom(this.devicePosition);
  61419. camRight.position.copyFrom(this.devicePosition);
  61420. };
  61421. /**
  61422. * This function is called by the two RIG cameras.
  61423. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  61424. */
  61425. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  61426. var _this = this;
  61427. //WebVR 1.0
  61428. if (this._cameraRigParams["specs"] === 1.0) {
  61429. this._updateCameraRotationMatrix();
  61430. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  61431. // Computing target and final matrix
  61432. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  61433. if (this.getScene().useRightHandedSystem) {
  61434. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  61435. }
  61436. else {
  61437. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  61438. }
  61439. //now move the eye in the right direction
  61440. var eyeParams = this._cameraRigParams["eyeParameters"];
  61441. var offset = eyeParams.offset;
  61442. // it will actually always be 0, but just in case
  61443. if (this.getScene().useRightHandedSystem) {
  61444. offset[2] *= -1;
  61445. }
  61446. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  61447. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  61448. }
  61449. else {
  61450. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  61451. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  61452. if (!this.getScene().useRightHandedSystem) {
  61453. [2, 6, 8, 9, 14].forEach(function (num) {
  61454. _this._webvrViewMatrix.m[num] *= -1;
  61455. });
  61456. }
  61457. // update the camera rotation matrix
  61458. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  61459. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  61460. // Computing target and final matrix
  61461. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  61462. }
  61463. var parentCamera = this._cameraRigParams["parentCamera"];
  61464. // should the view matrix be updated with scale and position offset?
  61465. if (parentCamera.deviceScaleFactor !== 1) {
  61466. this._webvrViewMatrix.invert();
  61467. // scale the position, if set
  61468. if (parentCamera.deviceScaleFactor) {
  61469. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  61470. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  61471. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  61472. }
  61473. this._webvrViewMatrix.invert();
  61474. }
  61475. return this._webvrViewMatrix;
  61476. };
  61477. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  61478. var _this = this;
  61479. if (this._cameraRigParams["specs"] === 1.0) {
  61480. var eyeParams = this._cameraRigParams["eyeParameters"];
  61481. // deprecated!!
  61482. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  61483. }
  61484. else {
  61485. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  61486. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  61487. //babylon compatible matrix
  61488. if (!this.getScene().useRightHandedSystem) {
  61489. [8, 9, 10, 11].forEach(function (num) {
  61490. _this._projectionMatrix.m[num] *= -1;
  61491. });
  61492. }
  61493. }
  61494. return this._projectionMatrix;
  61495. };
  61496. WebVRFreeCamera.prototype.initControllers = function () {
  61497. var _this = this;
  61498. this.controllers = [];
  61499. new BABYLON.Gamepads(function (gp) {
  61500. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  61501. var webVrController = gp;
  61502. if (_this.webVROptions.controllerMeshes) {
  61503. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  61504. if (_this.webVROptions.defaultLightningOnControllers) {
  61505. if (!_this._lightOnControllers) {
  61506. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  61507. }
  61508. loadedMesh.getChildren().forEach(function (mesh) {
  61509. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  61510. });
  61511. }
  61512. });
  61513. }
  61514. webVrController.attachToPoseControlledCamera(_this);
  61515. // since this is async - sanity check. Is the controller already stored?
  61516. if (_this.controllers.indexOf(webVrController) === -1) {
  61517. //add to the controllers array
  61518. _this.controllers.push(webVrController);
  61519. //did we find enough controllers? Great! let the developer know.
  61520. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  61521. _this._onControllersAttached(_this.controllers);
  61522. }
  61523. }
  61524. }
  61525. });
  61526. };
  61527. return WebVRFreeCamera;
  61528. }(BABYLON.FreeCamera));
  61529. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  61530. })(BABYLON || (BABYLON = {}));
  61531. //# sourceMappingURL=babylon.webVRCamera.js.map
  61532. /// <reference path="babylon.freeCamera.ts" />
  61533. var BABYLON;
  61534. (function (BABYLON) {
  61535. // We're mainly based on the logic defined into the FreeCamera code
  61536. var DeviceOrientationCamera = (function (_super) {
  61537. __extends(DeviceOrientationCamera, _super);
  61538. function DeviceOrientationCamera(name, position, scene) {
  61539. var _this = _super.call(this, name, position, scene) || this;
  61540. _this._quaternionCache = new BABYLON.Quaternion();
  61541. _this.inputs.addDeviceOrientation();
  61542. return _this;
  61543. }
  61544. DeviceOrientationCamera.prototype.getClassName = function () {
  61545. return "DeviceOrientationCamera";
  61546. };
  61547. DeviceOrientationCamera.prototype._checkInputs = function () {
  61548. _super.prototype._checkInputs.call(this);
  61549. this._quaternionCache.copyFrom(this.rotationQuaternion);
  61550. if (this._initialQuaternion) {
  61551. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  61552. }
  61553. };
  61554. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  61555. var _this = this;
  61556. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  61557. //can only work if this camera has a rotation quaternion already.
  61558. if (!this.rotationQuaternion)
  61559. return;
  61560. if (!this._initialQuaternion) {
  61561. this._initialQuaternion = new BABYLON.Quaternion();
  61562. }
  61563. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  61564. ['x', 'y', 'z'].forEach(function (axisName) {
  61565. if (!axis[axisName]) {
  61566. _this._initialQuaternion[axisName] = 0;
  61567. }
  61568. else {
  61569. _this._initialQuaternion[axisName] *= -1;
  61570. }
  61571. });
  61572. this._initialQuaternion.normalize();
  61573. //force rotation update
  61574. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  61575. };
  61576. return DeviceOrientationCamera;
  61577. }(BABYLON.FreeCamera));
  61578. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  61579. })(BABYLON || (BABYLON = {}));
  61580. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  61581. var BABYLON;
  61582. (function (BABYLON) {
  61583. var VRDeviceOrientationFreeCamera = (function (_super) {
  61584. __extends(VRDeviceOrientationFreeCamera, _super);
  61585. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  61586. if (compensateDistortion === void 0) { compensateDistortion = true; }
  61587. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  61588. var _this = _super.call(this, name, position, scene) || this;
  61589. vrCameraMetrics.compensateDistortion = compensateDistortion;
  61590. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  61591. return _this;
  61592. }
  61593. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  61594. return "VRDeviceOrientationFreeCamera";
  61595. };
  61596. return VRDeviceOrientationFreeCamera;
  61597. }(BABYLON.DeviceOrientationCamera));
  61598. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  61599. var VRDeviceOrientationGamepadCamera = (function (_super) {
  61600. __extends(VRDeviceOrientationGamepadCamera, _super);
  61601. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  61602. if (compensateDistortion === void 0) { compensateDistortion = true; }
  61603. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  61604. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  61605. _this.inputs.addGamepad();
  61606. return _this;
  61607. }
  61608. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  61609. return "VRDeviceOrientationGamepadCamera";
  61610. };
  61611. return VRDeviceOrientationGamepadCamera;
  61612. }(VRDeviceOrientationFreeCamera));
  61613. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  61614. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  61615. __extends(VRDeviceOrientationArcRotateCamera, _super);
  61616. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  61617. if (compensateDistortion === void 0) { compensateDistortion = true; }
  61618. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  61619. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  61620. vrCameraMetrics.compensateDistortion = compensateDistortion;
  61621. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  61622. _this.inputs.addVRDeviceOrientation();
  61623. return _this;
  61624. }
  61625. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  61626. return "VRDeviceOrientationArcRotateCamera";
  61627. };
  61628. return VRDeviceOrientationArcRotateCamera;
  61629. }(BABYLON.ArcRotateCamera));
  61630. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  61631. })(BABYLON || (BABYLON = {}));
  61632. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  61633. /// <reference path="babylon.freeCamera.ts" />
  61634. /// <reference path="babylon.arcRotateCamera.ts" />
  61635. /// <reference path="babylon.gamepadCamera.ts" />
  61636. /// <reference path="babylon.universalCamera.ts" />
  61637. var BABYLON;
  61638. (function (BABYLON) {
  61639. var AnaglyphFreeCamera = (function (_super) {
  61640. __extends(AnaglyphFreeCamera, _super);
  61641. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  61642. var _this = _super.call(this, name, position, scene) || this;
  61643. _this.interaxialDistance = interaxialDistance;
  61644. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61645. return _this;
  61646. }
  61647. AnaglyphFreeCamera.prototype.getClassName = function () {
  61648. return "AnaglyphFreeCamera";
  61649. };
  61650. return AnaglyphFreeCamera;
  61651. }(BABYLON.FreeCamera));
  61652. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  61653. var AnaglyphArcRotateCamera = (function (_super) {
  61654. __extends(AnaglyphArcRotateCamera, _super);
  61655. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  61656. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  61657. _this.interaxialDistance = interaxialDistance;
  61658. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61659. return _this;
  61660. }
  61661. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  61662. return "AnaglyphArcRotateCamera";
  61663. };
  61664. return AnaglyphArcRotateCamera;
  61665. }(BABYLON.ArcRotateCamera));
  61666. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  61667. var AnaglyphGamepadCamera = (function (_super) {
  61668. __extends(AnaglyphGamepadCamera, _super);
  61669. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  61670. var _this = _super.call(this, name, position, scene) || this;
  61671. _this.interaxialDistance = interaxialDistance;
  61672. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61673. return _this;
  61674. }
  61675. AnaglyphGamepadCamera.prototype.getClassName = function () {
  61676. return "AnaglyphGamepadCamera";
  61677. };
  61678. return AnaglyphGamepadCamera;
  61679. }(BABYLON.GamepadCamera));
  61680. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  61681. var AnaglyphUniversalCamera = (function (_super) {
  61682. __extends(AnaglyphUniversalCamera, _super);
  61683. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  61684. var _this = _super.call(this, name, position, scene) || this;
  61685. _this.interaxialDistance = interaxialDistance;
  61686. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61687. return _this;
  61688. }
  61689. AnaglyphUniversalCamera.prototype.getClassName = function () {
  61690. return "AnaglyphUniversalCamera";
  61691. };
  61692. return AnaglyphUniversalCamera;
  61693. }(BABYLON.UniversalCamera));
  61694. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  61695. var StereoscopicFreeCamera = (function (_super) {
  61696. __extends(StereoscopicFreeCamera, _super);
  61697. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  61698. var _this = _super.call(this, name, position, scene) || this;
  61699. _this.interaxialDistance = interaxialDistance;
  61700. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61701. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61702. return _this;
  61703. }
  61704. StereoscopicFreeCamera.prototype.getClassName = function () {
  61705. return "StereoscopicFreeCamera";
  61706. };
  61707. return StereoscopicFreeCamera;
  61708. }(BABYLON.FreeCamera));
  61709. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  61710. var StereoscopicArcRotateCamera = (function (_super) {
  61711. __extends(StereoscopicArcRotateCamera, _super);
  61712. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  61713. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  61714. _this.interaxialDistance = interaxialDistance;
  61715. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61716. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61717. return _this;
  61718. }
  61719. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  61720. return "StereoscopicArcRotateCamera";
  61721. };
  61722. return StereoscopicArcRotateCamera;
  61723. }(BABYLON.ArcRotateCamera));
  61724. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  61725. var StereoscopicGamepadCamera = (function (_super) {
  61726. __extends(StereoscopicGamepadCamera, _super);
  61727. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  61728. var _this = _super.call(this, name, position, scene) || this;
  61729. _this.interaxialDistance = interaxialDistance;
  61730. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61731. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61732. return _this;
  61733. }
  61734. StereoscopicGamepadCamera.prototype.getClassName = function () {
  61735. return "StereoscopicGamepadCamera";
  61736. };
  61737. return StereoscopicGamepadCamera;
  61738. }(BABYLON.GamepadCamera));
  61739. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  61740. var StereoscopicUniversalCamera = (function (_super) {
  61741. __extends(StereoscopicUniversalCamera, _super);
  61742. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  61743. var _this = _super.call(this, name, position, scene) || this;
  61744. _this.interaxialDistance = interaxialDistance;
  61745. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61746. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61747. return _this;
  61748. }
  61749. StereoscopicUniversalCamera.prototype.getClassName = function () {
  61750. return "StereoscopicUniversalCamera";
  61751. };
  61752. return StereoscopicUniversalCamera;
  61753. }(BABYLON.UniversalCamera));
  61754. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  61755. })(BABYLON || (BABYLON = {}));
  61756. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  61757. // Mainly based on these 2 articles :
  61758. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  61759. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  61760. var BABYLON;
  61761. (function (BABYLON) {
  61762. var JoystickAxis;
  61763. (function (JoystickAxis) {
  61764. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  61765. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  61766. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  61767. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  61768. var VirtualJoystick = (function () {
  61769. function VirtualJoystick(leftJoystick) {
  61770. var _this = this;
  61771. if (leftJoystick) {
  61772. this._leftJoystick = true;
  61773. }
  61774. else {
  61775. this._leftJoystick = false;
  61776. }
  61777. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  61778. VirtualJoystick._globalJoystickIndex++;
  61779. // By default left & right arrow keys are moving the X
  61780. // and up & down keys are moving the Y
  61781. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  61782. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  61783. this.reverseLeftRight = false;
  61784. this.reverseUpDown = false;
  61785. // collections of pointers
  61786. this._touches = new BABYLON.StringDictionary();
  61787. this.deltaPosition = BABYLON.Vector3.Zero();
  61788. this._joystickSensibility = 25;
  61789. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  61790. this._rotationSpeed = 25;
  61791. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  61792. this._rotateOnAxisRelativeToMesh = false;
  61793. this._onResize = function (evt) {
  61794. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  61795. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  61796. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  61797. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  61798. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  61799. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  61800. };
  61801. // injecting a canvas element on top of the canvas 3D game
  61802. if (!VirtualJoystick.vjCanvas) {
  61803. window.addEventListener("resize", this._onResize, false);
  61804. VirtualJoystick.vjCanvas = document.createElement("canvas");
  61805. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  61806. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  61807. VirtualJoystick.vjCanvas.width = window.innerWidth;
  61808. VirtualJoystick.vjCanvas.height = window.innerHeight;
  61809. VirtualJoystick.vjCanvas.style.width = "100%";
  61810. VirtualJoystick.vjCanvas.style.height = "100%";
  61811. VirtualJoystick.vjCanvas.style.position = "absolute";
  61812. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  61813. VirtualJoystick.vjCanvas.style.top = "0px";
  61814. VirtualJoystick.vjCanvas.style.left = "0px";
  61815. VirtualJoystick.vjCanvas.style.zIndex = "5";
  61816. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  61817. // Support for jQuery PEP polyfill
  61818. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  61819. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  61820. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  61821. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  61822. document.body.appendChild(VirtualJoystick.vjCanvas);
  61823. }
  61824. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  61825. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  61826. this.pressed = false;
  61827. // default joystick color
  61828. this._joystickColor = "cyan";
  61829. this._joystickPointerID = -1;
  61830. // current joystick position
  61831. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  61832. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  61833. // origin joystick position
  61834. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  61835. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  61836. this._onPointerDownHandlerRef = function (evt) {
  61837. _this._onPointerDown(evt);
  61838. };
  61839. this._onPointerMoveHandlerRef = function (evt) {
  61840. _this._onPointerMove(evt);
  61841. };
  61842. this._onPointerOutHandlerRef = function (evt) {
  61843. _this._onPointerUp(evt);
  61844. };
  61845. this._onPointerUpHandlerRef = function (evt) {
  61846. _this._onPointerUp(evt);
  61847. };
  61848. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  61849. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  61850. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  61851. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  61852. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  61853. evt.preventDefault(); // Disables system menu
  61854. }, false);
  61855. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  61856. }
  61857. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  61858. this._joystickSensibility = newJoystickSensibility;
  61859. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  61860. };
  61861. VirtualJoystick.prototype._onPointerDown = function (e) {
  61862. var positionOnScreenCondition;
  61863. e.preventDefault();
  61864. if (this._leftJoystick === true) {
  61865. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  61866. }
  61867. else {
  61868. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  61869. }
  61870. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  61871. // First contact will be dedicated to the virtual joystick
  61872. this._joystickPointerID = e.pointerId;
  61873. this._joystickPointerStartPos.x = e.clientX;
  61874. this._joystickPointerStartPos.y = e.clientY;
  61875. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  61876. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  61877. this._deltaJoystickVector.x = 0;
  61878. this._deltaJoystickVector.y = 0;
  61879. this.pressed = true;
  61880. this._touches.add(e.pointerId.toString(), e);
  61881. }
  61882. else {
  61883. // You can only trigger the action buttons with a joystick declared
  61884. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  61885. this._action();
  61886. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  61887. }
  61888. }
  61889. };
  61890. VirtualJoystick.prototype._onPointerMove = function (e) {
  61891. // If the current pointer is the one associated to the joystick (first touch contact)
  61892. if (this._joystickPointerID == e.pointerId) {
  61893. this._joystickPointerPos.x = e.clientX;
  61894. this._joystickPointerPos.y = e.clientY;
  61895. this._deltaJoystickVector = this._joystickPointerPos.clone();
  61896. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  61897. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  61898. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  61899. switch (this._axisTargetedByLeftAndRight) {
  61900. case JoystickAxis.X:
  61901. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  61902. break;
  61903. case JoystickAxis.Y:
  61904. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  61905. break;
  61906. case JoystickAxis.Z:
  61907. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  61908. break;
  61909. }
  61910. var directionUpDown = this.reverseUpDown ? 1 : -1;
  61911. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  61912. switch (this._axisTargetedByUpAndDown) {
  61913. case JoystickAxis.X:
  61914. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  61915. break;
  61916. case JoystickAxis.Y:
  61917. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  61918. break;
  61919. case JoystickAxis.Z:
  61920. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  61921. break;
  61922. }
  61923. }
  61924. else {
  61925. var data = this._touches.get(e.pointerId.toString());
  61926. if (data) {
  61927. data.x = e.clientX;
  61928. data.y = e.clientY;
  61929. }
  61930. }
  61931. };
  61932. VirtualJoystick.prototype._onPointerUp = function (e) {
  61933. if (this._joystickPointerID == e.pointerId) {
  61934. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  61935. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  61936. this._joystickPointerID = -1;
  61937. this.pressed = false;
  61938. }
  61939. else {
  61940. var touch = this._touches.get(e.pointerId.toString());
  61941. if (touch) {
  61942. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  61943. }
  61944. }
  61945. this._deltaJoystickVector.x = 0;
  61946. this._deltaJoystickVector.y = 0;
  61947. this._touches.remove(e.pointerId.toString());
  61948. };
  61949. /**
  61950. * Change the color of the virtual joystick
  61951. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  61952. */
  61953. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  61954. this._joystickColor = newColor;
  61955. };
  61956. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  61957. this._action = action;
  61958. };
  61959. // Define which axis you'd like to control for left & right
  61960. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  61961. switch (axis) {
  61962. case JoystickAxis.X:
  61963. case JoystickAxis.Y:
  61964. case JoystickAxis.Z:
  61965. this._axisTargetedByLeftAndRight = axis;
  61966. break;
  61967. default:
  61968. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  61969. break;
  61970. }
  61971. };
  61972. // Define which axis you'd like to control for up & down
  61973. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  61974. switch (axis) {
  61975. case JoystickAxis.X:
  61976. case JoystickAxis.Y:
  61977. case JoystickAxis.Z:
  61978. this._axisTargetedByUpAndDown = axis;
  61979. break;
  61980. default:
  61981. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  61982. break;
  61983. }
  61984. };
  61985. VirtualJoystick.prototype._clearCanvas = function () {
  61986. if (this._leftJoystick) {
  61987. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  61988. }
  61989. else {
  61990. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  61991. }
  61992. };
  61993. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  61994. var _this = this;
  61995. if (this.pressed) {
  61996. this._touches.forEach(function (key, touch) {
  61997. if (touch.pointerId === _this._joystickPointerID) {
  61998. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  61999. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  62000. VirtualJoystick.vjCanvasContext.beginPath();
  62001. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  62002. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62003. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  62004. VirtualJoystick.vjCanvasContext.stroke();
  62005. VirtualJoystick.vjCanvasContext.closePath();
  62006. VirtualJoystick.vjCanvasContext.beginPath();
  62007. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62008. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  62009. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  62010. VirtualJoystick.vjCanvasContext.stroke();
  62011. VirtualJoystick.vjCanvasContext.closePath();
  62012. VirtualJoystick.vjCanvasContext.beginPath();
  62013. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62014. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  62015. VirtualJoystick.vjCanvasContext.stroke();
  62016. VirtualJoystick.vjCanvasContext.closePath();
  62017. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  62018. }
  62019. else {
  62020. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  62021. VirtualJoystick.vjCanvasContext.beginPath();
  62022. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  62023. VirtualJoystick.vjCanvasContext.beginPath();
  62024. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  62025. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  62026. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  62027. VirtualJoystick.vjCanvasContext.stroke();
  62028. VirtualJoystick.vjCanvasContext.closePath();
  62029. touch.prevX = touch.x;
  62030. touch.prevY = touch.y;
  62031. }
  62032. ;
  62033. });
  62034. }
  62035. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  62036. };
  62037. VirtualJoystick.prototype.releaseCanvas = function () {
  62038. if (VirtualJoystick.vjCanvas) {
  62039. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  62040. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  62041. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  62042. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  62043. window.removeEventListener("resize", this._onResize);
  62044. document.body.removeChild(VirtualJoystick.vjCanvas);
  62045. VirtualJoystick.vjCanvas = null;
  62046. }
  62047. };
  62048. return VirtualJoystick;
  62049. }());
  62050. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  62051. VirtualJoystick._globalJoystickIndex = 0;
  62052. BABYLON.VirtualJoystick = VirtualJoystick;
  62053. })(BABYLON || (BABYLON = {}));
  62054. //# sourceMappingURL=babylon.virtualJoystick.js.map
  62055. var BABYLON;
  62056. (function (BABYLON) {
  62057. // We're mainly based on the logic defined into the FreeCamera code
  62058. var VirtualJoysticksCamera = (function (_super) {
  62059. __extends(VirtualJoysticksCamera, _super);
  62060. function VirtualJoysticksCamera(name, position, scene) {
  62061. var _this = _super.call(this, name, position, scene) || this;
  62062. _this.inputs.addVirtualJoystick();
  62063. return _this;
  62064. }
  62065. VirtualJoysticksCamera.prototype.getClassName = function () {
  62066. return "VirtualJoysticksCamera";
  62067. };
  62068. return VirtualJoysticksCamera;
  62069. }(BABYLON.FreeCamera));
  62070. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  62071. })(BABYLON || (BABYLON = {}));
  62072. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  62073. var BABYLON;
  62074. (function (BABYLON) {
  62075. var FreeCameraVirtualJoystickInput = (function () {
  62076. function FreeCameraVirtualJoystickInput() {
  62077. }
  62078. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  62079. return this._leftjoystick;
  62080. };
  62081. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  62082. return this._rightjoystick;
  62083. };
  62084. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  62085. if (this._leftjoystick) {
  62086. var camera = this.camera;
  62087. var speed = camera._computeLocalCameraSpeed() * 50;
  62088. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  62089. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  62090. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  62091. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  62092. if (!this._leftjoystick.pressed) {
  62093. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  62094. }
  62095. if (!this._rightjoystick.pressed) {
  62096. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  62097. }
  62098. }
  62099. };
  62100. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  62101. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  62102. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  62103. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  62104. this._leftjoystick.setJoystickSensibility(0.15);
  62105. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  62106. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  62107. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  62108. this._rightjoystick.reverseUpDown = true;
  62109. this._rightjoystick.setJoystickSensibility(0.05);
  62110. this._rightjoystick.setJoystickColor("yellow");
  62111. };
  62112. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  62113. this._leftjoystick.releaseCanvas();
  62114. this._rightjoystick.releaseCanvas();
  62115. };
  62116. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  62117. return "FreeCameraVirtualJoystickInput";
  62118. };
  62119. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  62120. return "virtualJoystick";
  62121. };
  62122. return FreeCameraVirtualJoystickInput;
  62123. }());
  62124. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  62125. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  62126. })(BABYLON || (BABYLON = {}));
  62127. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  62128. var BABYLON;
  62129. (function (BABYLON) {
  62130. var SimplificationSettings = (function () {
  62131. function SimplificationSettings(quality, distance, optimizeMesh) {
  62132. this.quality = quality;
  62133. this.distance = distance;
  62134. this.optimizeMesh = optimizeMesh;
  62135. }
  62136. return SimplificationSettings;
  62137. }());
  62138. BABYLON.SimplificationSettings = SimplificationSettings;
  62139. var SimplificationQueue = (function () {
  62140. function SimplificationQueue() {
  62141. this.running = false;
  62142. this._simplificationArray = [];
  62143. }
  62144. SimplificationQueue.prototype.addTask = function (task) {
  62145. this._simplificationArray.push(task);
  62146. };
  62147. SimplificationQueue.prototype.executeNext = function () {
  62148. var task = this._simplificationArray.pop();
  62149. if (task) {
  62150. this.running = true;
  62151. this.runSimplification(task);
  62152. }
  62153. else {
  62154. this.running = false;
  62155. }
  62156. };
  62157. SimplificationQueue.prototype.runSimplification = function (task) {
  62158. var _this = this;
  62159. if (task.parallelProcessing) {
  62160. //parallel simplifier
  62161. task.settings.forEach(function (setting) {
  62162. var simplifier = _this.getSimplifier(task);
  62163. simplifier.simplify(setting, function (newMesh) {
  62164. task.mesh.addLODLevel(setting.distance, newMesh);
  62165. newMesh.isVisible = true;
  62166. //check if it is the last
  62167. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  62168. //all done, run the success callback.
  62169. task.successCallback();
  62170. }
  62171. _this.executeNext();
  62172. });
  62173. });
  62174. }
  62175. else {
  62176. //single simplifier.
  62177. var simplifier = this.getSimplifier(task);
  62178. var runDecimation = function (setting, callback) {
  62179. simplifier.simplify(setting, function (newMesh) {
  62180. task.mesh.addLODLevel(setting.distance, newMesh);
  62181. newMesh.isVisible = true;
  62182. //run the next quality level
  62183. callback();
  62184. });
  62185. };
  62186. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  62187. runDecimation(task.settings[loop.index], function () {
  62188. loop.executeNext();
  62189. });
  62190. }, function () {
  62191. //execution ended, run the success callback.
  62192. if (task.successCallback) {
  62193. task.successCallback();
  62194. }
  62195. _this.executeNext();
  62196. });
  62197. }
  62198. };
  62199. SimplificationQueue.prototype.getSimplifier = function (task) {
  62200. switch (task.simplificationType) {
  62201. case SimplificationType.QUADRATIC:
  62202. default:
  62203. return new QuadraticErrorSimplification(task.mesh);
  62204. }
  62205. };
  62206. return SimplificationQueue;
  62207. }());
  62208. BABYLON.SimplificationQueue = SimplificationQueue;
  62209. /**
  62210. * The implemented types of simplification.
  62211. * At the moment only Quadratic Error Decimation is implemented.
  62212. */
  62213. var SimplificationType;
  62214. (function (SimplificationType) {
  62215. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  62216. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  62217. var DecimationTriangle = (function () {
  62218. function DecimationTriangle(vertices) {
  62219. this.vertices = vertices;
  62220. this.error = new Array(4);
  62221. this.deleted = false;
  62222. this.isDirty = false;
  62223. this.deletePending = false;
  62224. this.borderFactor = 0;
  62225. }
  62226. return DecimationTriangle;
  62227. }());
  62228. BABYLON.DecimationTriangle = DecimationTriangle;
  62229. var DecimationVertex = (function () {
  62230. function DecimationVertex(position, id) {
  62231. this.position = position;
  62232. this.id = id;
  62233. this.isBorder = true;
  62234. this.q = new QuadraticMatrix();
  62235. this.triangleCount = 0;
  62236. this.triangleStart = 0;
  62237. this.originalOffsets = [];
  62238. }
  62239. DecimationVertex.prototype.updatePosition = function (newPosition) {
  62240. this.position.copyFrom(newPosition);
  62241. };
  62242. return DecimationVertex;
  62243. }());
  62244. BABYLON.DecimationVertex = DecimationVertex;
  62245. var QuadraticMatrix = (function () {
  62246. function QuadraticMatrix(data) {
  62247. this.data = new Array(10);
  62248. for (var i = 0; i < 10; ++i) {
  62249. if (data && data[i]) {
  62250. this.data[i] = data[i];
  62251. }
  62252. else {
  62253. this.data[i] = 0;
  62254. }
  62255. }
  62256. }
  62257. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  62258. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  62259. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  62260. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  62261. return det;
  62262. };
  62263. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  62264. for (var i = 0; i < 10; ++i) {
  62265. this.data[i] += matrix.data[i];
  62266. }
  62267. };
  62268. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  62269. for (var i = 0; i < 10; ++i) {
  62270. this.data[i] += data[i];
  62271. }
  62272. };
  62273. QuadraticMatrix.prototype.add = function (matrix) {
  62274. var m = new QuadraticMatrix();
  62275. for (var i = 0; i < 10; ++i) {
  62276. m.data[i] = this.data[i] + matrix.data[i];
  62277. }
  62278. return m;
  62279. };
  62280. QuadraticMatrix.FromData = function (a, b, c, d) {
  62281. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  62282. };
  62283. //returning an array to avoid garbage collection
  62284. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  62285. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  62286. };
  62287. return QuadraticMatrix;
  62288. }());
  62289. BABYLON.QuadraticMatrix = QuadraticMatrix;
  62290. var Reference = (function () {
  62291. function Reference(vertexId, triangleId) {
  62292. this.vertexId = vertexId;
  62293. this.triangleId = triangleId;
  62294. }
  62295. return Reference;
  62296. }());
  62297. BABYLON.Reference = Reference;
  62298. /**
  62299. * An implementation of the Quadratic Error simplification algorithm.
  62300. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  62301. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  62302. * @author RaananW
  62303. */
  62304. var QuadraticErrorSimplification = (function () {
  62305. function QuadraticErrorSimplification(_mesh) {
  62306. this._mesh = _mesh;
  62307. this.initialized = false;
  62308. this.syncIterations = 5000;
  62309. this.aggressiveness = 7;
  62310. this.decimationIterations = 100;
  62311. this.boundingBoxEpsilon = BABYLON.Epsilon;
  62312. }
  62313. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  62314. var _this = this;
  62315. this.initDecimatedMesh();
  62316. //iterating through the submeshes array, one after the other.
  62317. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  62318. _this.initWithMesh(loop.index, function () {
  62319. _this.runDecimation(settings, loop.index, function () {
  62320. loop.executeNext();
  62321. });
  62322. }, settings.optimizeMesh);
  62323. }, function () {
  62324. setTimeout(function () {
  62325. successCallback(_this._reconstructedMesh);
  62326. }, 0);
  62327. });
  62328. };
  62329. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  62330. var _this = this;
  62331. var gCount = 0;
  62332. triangle.vertices.forEach(function (vertex) {
  62333. var count = 0;
  62334. var vPos = vertex.position;
  62335. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  62336. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  62337. ++count;
  62338. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  62339. ++count;
  62340. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  62341. ++count;
  62342. if (count > 1) {
  62343. ++gCount;
  62344. }
  62345. ;
  62346. });
  62347. if (gCount > 1) {
  62348. console.log(triangle, gCount);
  62349. }
  62350. return gCount > 1;
  62351. };
  62352. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  62353. var _this = this;
  62354. var targetCount = ~~(this.triangles.length * settings.quality);
  62355. var deletedTriangles = 0;
  62356. var triangleCount = this.triangles.length;
  62357. var iterationFunction = function (iteration, callback) {
  62358. setTimeout(function () {
  62359. if (iteration % 5 === 0) {
  62360. _this.updateMesh(iteration === 0);
  62361. }
  62362. for (var i = 0; i < _this.triangles.length; ++i) {
  62363. _this.triangles[i].isDirty = false;
  62364. }
  62365. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  62366. var trianglesIterator = function (i) {
  62367. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  62368. var t = _this.triangles[tIdx];
  62369. if (!t)
  62370. return;
  62371. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  62372. return;
  62373. }
  62374. for (var j = 0; j < 3; ++j) {
  62375. if (t.error[j] < threshold) {
  62376. var deleted0 = [];
  62377. var deleted1 = [];
  62378. var v0 = t.vertices[j];
  62379. var v1 = t.vertices[(j + 1) % 3];
  62380. if (v0.isBorder || v1.isBorder)
  62381. continue;
  62382. var p = BABYLON.Vector3.Zero();
  62383. var n = BABYLON.Vector3.Zero();
  62384. var uv = BABYLON.Vector2.Zero();
  62385. var color = new BABYLON.Color4(0, 0, 0, 1);
  62386. _this.calculateError(v0, v1, p, n, uv, color);
  62387. var delTr = [];
  62388. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  62389. continue;
  62390. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  62391. continue;
  62392. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  62393. continue;
  62394. var uniqueArray = [];
  62395. delTr.forEach(function (deletedT) {
  62396. if (uniqueArray.indexOf(deletedT) === -1) {
  62397. deletedT.deletePending = true;
  62398. uniqueArray.push(deletedT);
  62399. }
  62400. });
  62401. if (uniqueArray.length % 2 !== 0) {
  62402. continue;
  62403. }
  62404. v0.q = v1.q.add(v0.q);
  62405. v0.updatePosition(p);
  62406. var tStart = _this.references.length;
  62407. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  62408. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  62409. var tCount = _this.references.length - tStart;
  62410. if (tCount <= v0.triangleCount) {
  62411. if (tCount) {
  62412. for (var c = 0; c < tCount; c++) {
  62413. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  62414. }
  62415. }
  62416. }
  62417. else {
  62418. v0.triangleStart = tStart;
  62419. }
  62420. v0.triangleCount = tCount;
  62421. break;
  62422. }
  62423. }
  62424. };
  62425. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  62426. }, 0);
  62427. };
  62428. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  62429. if (triangleCount - deletedTriangles <= targetCount)
  62430. loop.breakLoop();
  62431. else {
  62432. iterationFunction(loop.index, function () {
  62433. loop.executeNext();
  62434. });
  62435. }
  62436. }, function () {
  62437. setTimeout(function () {
  62438. //reconstruct this part of the mesh
  62439. _this.reconstructMesh(submeshIndex);
  62440. successCallback();
  62441. }, 0);
  62442. });
  62443. };
  62444. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  62445. var _this = this;
  62446. this.vertices = [];
  62447. this.triangles = [];
  62448. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62449. var indices = this._mesh.getIndices();
  62450. var submesh = this._mesh.subMeshes[submeshIndex];
  62451. var findInVertices = function (positionToSearch) {
  62452. if (optimizeMesh) {
  62453. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  62454. if (_this.vertices[ii].position.equals(positionToSearch)) {
  62455. return _this.vertices[ii];
  62456. }
  62457. }
  62458. }
  62459. return null;
  62460. };
  62461. var vertexReferences = [];
  62462. var vertexInit = function (i) {
  62463. var offset = i + submesh.verticesStart;
  62464. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  62465. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  62466. vertex.originalOffsets.push(offset);
  62467. if (vertex.id === _this.vertices.length) {
  62468. _this.vertices.push(vertex);
  62469. }
  62470. vertexReferences.push(vertex.id);
  62471. };
  62472. //var totalVertices = mesh.getTotalVertices();
  62473. var totalVertices = submesh.verticesCount;
  62474. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  62475. var indicesInit = function (i) {
  62476. var offset = (submesh.indexStart / 3) + i;
  62477. var pos = (offset * 3);
  62478. var i0 = indices[pos + 0];
  62479. var i1 = indices[pos + 1];
  62480. var i2 = indices[pos + 2];
  62481. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  62482. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  62483. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  62484. var triangle = new DecimationTriangle([v0, v1, v2]);
  62485. triangle.originalOffset = pos;
  62486. _this.triangles.push(triangle);
  62487. };
  62488. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  62489. _this.init(callback);
  62490. });
  62491. });
  62492. };
  62493. QuadraticErrorSimplification.prototype.init = function (callback) {
  62494. var _this = this;
  62495. var triangleInit1 = function (i) {
  62496. var t = _this.triangles[i];
  62497. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  62498. for (var j = 0; j < 3; j++) {
  62499. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  62500. }
  62501. };
  62502. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  62503. var triangleInit2 = function (i) {
  62504. var t = _this.triangles[i];
  62505. for (var j = 0; j < 3; ++j) {
  62506. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  62507. }
  62508. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  62509. };
  62510. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  62511. _this.initialized = true;
  62512. callback();
  62513. });
  62514. });
  62515. };
  62516. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  62517. var newTriangles = [];
  62518. var i;
  62519. for (i = 0; i < this.vertices.length; ++i) {
  62520. this.vertices[i].triangleCount = 0;
  62521. }
  62522. var t;
  62523. var j;
  62524. for (i = 0; i < this.triangles.length; ++i) {
  62525. if (!this.triangles[i].deleted) {
  62526. t = this.triangles[i];
  62527. for (j = 0; j < 3; ++j) {
  62528. t.vertices[j].triangleCount = 1;
  62529. }
  62530. newTriangles.push(t);
  62531. }
  62532. }
  62533. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  62534. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  62535. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  62536. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  62537. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62538. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62539. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62540. var vertexCount = 0;
  62541. for (i = 0; i < this.vertices.length; ++i) {
  62542. var vertex = this.vertices[i];
  62543. vertex.id = vertexCount;
  62544. if (vertex.triangleCount) {
  62545. vertex.originalOffsets.forEach(function (originalOffset) {
  62546. newPositionData.push(vertex.position.x);
  62547. newPositionData.push(vertex.position.y);
  62548. newPositionData.push(vertex.position.z);
  62549. newNormalData.push(normalData[originalOffset * 3]);
  62550. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  62551. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  62552. if (uvs && uvs.length) {
  62553. newUVsData.push(uvs[(originalOffset * 2)]);
  62554. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  62555. }
  62556. else if (colorsData && colorsData.length) {
  62557. newColorsData.push(colorsData[(originalOffset * 4)]);
  62558. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  62559. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  62560. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  62561. }
  62562. ++vertexCount;
  62563. });
  62564. }
  62565. }
  62566. var startingIndex = this._reconstructedMesh.getTotalIndices();
  62567. var startingVertex = this._reconstructedMesh.getTotalVertices();
  62568. var submeshesArray = this._reconstructedMesh.subMeshes;
  62569. this._reconstructedMesh.subMeshes = [];
  62570. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  62571. var originalIndices = this._mesh.getIndices();
  62572. for (i = 0; i < newTriangles.length; ++i) {
  62573. t = newTriangles[i]; //now get the new referencing point for each vertex
  62574. [0, 1, 2].forEach(function (idx) {
  62575. var id = originalIndices[t.originalOffset + idx];
  62576. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  62577. if (offset < 0)
  62578. offset = 0;
  62579. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  62580. });
  62581. }
  62582. //overwriting the old vertex buffers and indices.
  62583. this._reconstructedMesh.setIndices(newIndicesArray);
  62584. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  62585. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  62586. if (newUVsData.length > 0)
  62587. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  62588. if (newColorsData.length > 0)
  62589. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  62590. //create submesh
  62591. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  62592. if (submeshIndex > 0) {
  62593. this._reconstructedMesh.subMeshes = [];
  62594. submeshesArray.forEach(function (submesh) {
  62595. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  62596. });
  62597. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  62598. }
  62599. };
  62600. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  62601. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  62602. this._reconstructedMesh.material = this._mesh.material;
  62603. this._reconstructedMesh.parent = this._mesh.parent;
  62604. this._reconstructedMesh.isVisible = false;
  62605. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  62606. };
  62607. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  62608. for (var i = 0; i < vertex1.triangleCount; ++i) {
  62609. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  62610. if (t.deleted)
  62611. continue;
  62612. var s = this.references[vertex1.triangleStart + i].vertexId;
  62613. var v1 = t.vertices[(s + 1) % 3];
  62614. var v2 = t.vertices[(s + 2) % 3];
  62615. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  62616. deletedArray[i] = true;
  62617. delTr.push(t);
  62618. continue;
  62619. }
  62620. var d1 = v1.position.subtract(point);
  62621. d1 = d1.normalize();
  62622. var d2 = v2.position.subtract(point);
  62623. d2 = d2.normalize();
  62624. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  62625. return true;
  62626. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  62627. deletedArray[i] = false;
  62628. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  62629. return true;
  62630. }
  62631. return false;
  62632. };
  62633. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  62634. var newDeleted = deletedTriangles;
  62635. for (var i = 0; i < vertex.triangleCount; ++i) {
  62636. var ref = this.references[vertex.triangleStart + i];
  62637. var t = this.triangles[ref.triangleId];
  62638. if (t.deleted)
  62639. continue;
  62640. if (deletedArray[i] && t.deletePending) {
  62641. t.deleted = true;
  62642. newDeleted++;
  62643. continue;
  62644. }
  62645. t.vertices[ref.vertexId] = origVertex;
  62646. t.isDirty = true;
  62647. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  62648. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  62649. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  62650. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  62651. this.references.push(ref);
  62652. }
  62653. return newDeleted;
  62654. };
  62655. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  62656. for (var i = 0; i < this.vertices.length; ++i) {
  62657. var vCount = [];
  62658. var vId = [];
  62659. var v = this.vertices[i];
  62660. var j;
  62661. for (j = 0; j < v.triangleCount; ++j) {
  62662. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  62663. for (var ii = 0; ii < 3; ii++) {
  62664. var ofs = 0;
  62665. var vv = triangle.vertices[ii];
  62666. while (ofs < vCount.length) {
  62667. if (vId[ofs] === vv.id)
  62668. break;
  62669. ++ofs;
  62670. }
  62671. if (ofs === vCount.length) {
  62672. vCount.push(1);
  62673. vId.push(vv.id);
  62674. }
  62675. else {
  62676. vCount[ofs]++;
  62677. }
  62678. }
  62679. }
  62680. for (j = 0; j < vCount.length; ++j) {
  62681. if (vCount[j] === 1) {
  62682. this.vertices[vId[j]].isBorder = true;
  62683. }
  62684. else {
  62685. this.vertices[vId[j]].isBorder = false;
  62686. }
  62687. }
  62688. }
  62689. };
  62690. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  62691. if (identifyBorders === void 0) { identifyBorders = false; }
  62692. var i;
  62693. if (!identifyBorders) {
  62694. var newTrianglesVector = [];
  62695. for (i = 0; i < this.triangles.length; ++i) {
  62696. if (!this.triangles[i].deleted) {
  62697. newTrianglesVector.push(this.triangles[i]);
  62698. }
  62699. }
  62700. this.triangles = newTrianglesVector;
  62701. }
  62702. for (i = 0; i < this.vertices.length; ++i) {
  62703. this.vertices[i].triangleCount = 0;
  62704. this.vertices[i].triangleStart = 0;
  62705. }
  62706. var t;
  62707. var j;
  62708. var v;
  62709. for (i = 0; i < this.triangles.length; ++i) {
  62710. t = this.triangles[i];
  62711. for (j = 0; j < 3; ++j) {
  62712. v = t.vertices[j];
  62713. v.triangleCount++;
  62714. }
  62715. }
  62716. var tStart = 0;
  62717. for (i = 0; i < this.vertices.length; ++i) {
  62718. this.vertices[i].triangleStart = tStart;
  62719. tStart += this.vertices[i].triangleCount;
  62720. this.vertices[i].triangleCount = 0;
  62721. }
  62722. var newReferences = new Array(this.triangles.length * 3);
  62723. for (i = 0; i < this.triangles.length; ++i) {
  62724. t = this.triangles[i];
  62725. for (j = 0; j < 3; ++j) {
  62726. v = t.vertices[j];
  62727. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  62728. v.triangleCount++;
  62729. }
  62730. }
  62731. this.references = newReferences;
  62732. if (identifyBorders) {
  62733. this.identifyBorder();
  62734. }
  62735. };
  62736. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  62737. var x = point.x;
  62738. var y = point.y;
  62739. var z = point.z;
  62740. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  62741. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  62742. };
  62743. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  62744. var q = vertex1.q.add(vertex2.q);
  62745. var border = vertex1.isBorder && vertex2.isBorder;
  62746. var error = 0;
  62747. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  62748. if (qDet !== 0 && !border) {
  62749. if (!pointResult) {
  62750. pointResult = BABYLON.Vector3.Zero();
  62751. }
  62752. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  62753. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  62754. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  62755. error = this.vertexError(q, pointResult);
  62756. }
  62757. else {
  62758. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  62759. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  62760. var error1 = this.vertexError(q, vertex1.position);
  62761. var error2 = this.vertexError(q, vertex2.position);
  62762. var error3 = this.vertexError(q, p3);
  62763. error = Math.min(error1, error2, error3);
  62764. if (error === error1) {
  62765. if (pointResult) {
  62766. pointResult.copyFrom(vertex1.position);
  62767. }
  62768. }
  62769. else if (error === error2) {
  62770. if (pointResult) {
  62771. pointResult.copyFrom(vertex2.position);
  62772. }
  62773. }
  62774. else {
  62775. if (pointResult) {
  62776. pointResult.copyFrom(p3);
  62777. }
  62778. }
  62779. }
  62780. return error;
  62781. };
  62782. return QuadraticErrorSimplification;
  62783. }());
  62784. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  62785. })(BABYLON || (BABYLON = {}));
  62786. //# sourceMappingURL=babylon.meshSimplification.js.map
  62787. var BABYLON;
  62788. (function (BABYLON) {
  62789. var Internals;
  62790. (function (Internals) {
  62791. var MeshLODLevel = (function () {
  62792. function MeshLODLevel(distance, mesh) {
  62793. this.distance = distance;
  62794. this.mesh = mesh;
  62795. }
  62796. return MeshLODLevel;
  62797. }());
  62798. Internals.MeshLODLevel = MeshLODLevel;
  62799. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62800. })(BABYLON || (BABYLON = {}));
  62801. //# sourceMappingURL=babylon.meshLODLevel.js.map
  62802. var BABYLON;
  62803. (function (BABYLON) {
  62804. // Standard optimizations
  62805. var SceneOptimization = (function () {
  62806. function SceneOptimization(priority) {
  62807. if (priority === void 0) { priority = 0; }
  62808. this.priority = priority;
  62809. this.apply = function (scene) {
  62810. return true; // Return true if everything that can be done was applied
  62811. };
  62812. }
  62813. return SceneOptimization;
  62814. }());
  62815. BABYLON.SceneOptimization = SceneOptimization;
  62816. var TextureOptimization = (function (_super) {
  62817. __extends(TextureOptimization, _super);
  62818. function TextureOptimization(priority, maximumSize) {
  62819. if (priority === void 0) { priority = 0; }
  62820. if (maximumSize === void 0) { maximumSize = 1024; }
  62821. var _this = _super.call(this, priority) || this;
  62822. _this.priority = priority;
  62823. _this.maximumSize = maximumSize;
  62824. _this.apply = function (scene) {
  62825. var allDone = true;
  62826. for (var index = 0; index < scene.textures.length; index++) {
  62827. var texture = scene.textures[index];
  62828. if (!texture.canRescale) {
  62829. continue;
  62830. }
  62831. var currentSize = texture.getSize();
  62832. var maxDimension = Math.max(currentSize.width, currentSize.height);
  62833. if (maxDimension > _this.maximumSize) {
  62834. texture.scale(0.5);
  62835. allDone = false;
  62836. }
  62837. }
  62838. return allDone;
  62839. };
  62840. return _this;
  62841. }
  62842. return TextureOptimization;
  62843. }(SceneOptimization));
  62844. BABYLON.TextureOptimization = TextureOptimization;
  62845. var HardwareScalingOptimization = (function (_super) {
  62846. __extends(HardwareScalingOptimization, _super);
  62847. function HardwareScalingOptimization(priority, maximumScale) {
  62848. if (priority === void 0) { priority = 0; }
  62849. if (maximumScale === void 0) { maximumScale = 2; }
  62850. var _this = _super.call(this, priority) || this;
  62851. _this.priority = priority;
  62852. _this.maximumScale = maximumScale;
  62853. _this._currentScale = 1;
  62854. _this.apply = function (scene) {
  62855. _this._currentScale++;
  62856. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  62857. return _this._currentScale >= _this.maximumScale;
  62858. };
  62859. return _this;
  62860. }
  62861. return HardwareScalingOptimization;
  62862. }(SceneOptimization));
  62863. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  62864. var ShadowsOptimization = (function (_super) {
  62865. __extends(ShadowsOptimization, _super);
  62866. function ShadowsOptimization() {
  62867. var _this = _super !== null && _super.apply(this, arguments) || this;
  62868. _this.apply = function (scene) {
  62869. scene.shadowsEnabled = false;
  62870. return true;
  62871. };
  62872. return _this;
  62873. }
  62874. return ShadowsOptimization;
  62875. }(SceneOptimization));
  62876. BABYLON.ShadowsOptimization = ShadowsOptimization;
  62877. var PostProcessesOptimization = (function (_super) {
  62878. __extends(PostProcessesOptimization, _super);
  62879. function PostProcessesOptimization() {
  62880. var _this = _super !== null && _super.apply(this, arguments) || this;
  62881. _this.apply = function (scene) {
  62882. scene.postProcessesEnabled = false;
  62883. return true;
  62884. };
  62885. return _this;
  62886. }
  62887. return PostProcessesOptimization;
  62888. }(SceneOptimization));
  62889. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  62890. var LensFlaresOptimization = (function (_super) {
  62891. __extends(LensFlaresOptimization, _super);
  62892. function LensFlaresOptimization() {
  62893. var _this = _super !== null && _super.apply(this, arguments) || this;
  62894. _this.apply = function (scene) {
  62895. scene.lensFlaresEnabled = false;
  62896. return true;
  62897. };
  62898. return _this;
  62899. }
  62900. return LensFlaresOptimization;
  62901. }(SceneOptimization));
  62902. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  62903. var ParticlesOptimization = (function (_super) {
  62904. __extends(ParticlesOptimization, _super);
  62905. function ParticlesOptimization() {
  62906. var _this = _super !== null && _super.apply(this, arguments) || this;
  62907. _this.apply = function (scene) {
  62908. scene.particlesEnabled = false;
  62909. return true;
  62910. };
  62911. return _this;
  62912. }
  62913. return ParticlesOptimization;
  62914. }(SceneOptimization));
  62915. BABYLON.ParticlesOptimization = ParticlesOptimization;
  62916. var RenderTargetsOptimization = (function (_super) {
  62917. __extends(RenderTargetsOptimization, _super);
  62918. function RenderTargetsOptimization() {
  62919. var _this = _super !== null && _super.apply(this, arguments) || this;
  62920. _this.apply = function (scene) {
  62921. scene.renderTargetsEnabled = false;
  62922. return true;
  62923. };
  62924. return _this;
  62925. }
  62926. return RenderTargetsOptimization;
  62927. }(SceneOptimization));
  62928. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  62929. var MergeMeshesOptimization = (function (_super) {
  62930. __extends(MergeMeshesOptimization, _super);
  62931. function MergeMeshesOptimization() {
  62932. var _this = _super !== null && _super.apply(this, arguments) || this;
  62933. _this._canBeMerged = function (abstractMesh) {
  62934. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  62935. return false;
  62936. }
  62937. var mesh = abstractMesh;
  62938. if (!mesh.isVisible || !mesh.isEnabled()) {
  62939. return false;
  62940. }
  62941. if (mesh.instances.length > 0) {
  62942. return false;
  62943. }
  62944. if (mesh.skeleton || mesh.hasLODLevels) {
  62945. return false;
  62946. }
  62947. if (mesh.parent) {
  62948. return false;
  62949. }
  62950. return true;
  62951. };
  62952. _this.apply = function (scene, updateSelectionTree) {
  62953. var globalPool = scene.meshes.slice(0);
  62954. var globalLength = globalPool.length;
  62955. for (var index = 0; index < globalLength; index++) {
  62956. var currentPool = new Array();
  62957. var current = globalPool[index];
  62958. // Checks
  62959. if (!_this._canBeMerged(current)) {
  62960. continue;
  62961. }
  62962. currentPool.push(current);
  62963. // Find compatible meshes
  62964. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  62965. var otherMesh = globalPool[subIndex];
  62966. if (!_this._canBeMerged(otherMesh)) {
  62967. continue;
  62968. }
  62969. if (otherMesh.material !== current.material) {
  62970. continue;
  62971. }
  62972. if (otherMesh.checkCollisions !== current.checkCollisions) {
  62973. continue;
  62974. }
  62975. currentPool.push(otherMesh);
  62976. globalLength--;
  62977. globalPool.splice(subIndex, 1);
  62978. subIndex--;
  62979. }
  62980. if (currentPool.length < 2) {
  62981. continue;
  62982. }
  62983. // Merge meshes
  62984. BABYLON.Mesh.MergeMeshes(currentPool);
  62985. }
  62986. if (updateSelectionTree != undefined) {
  62987. if (updateSelectionTree) {
  62988. scene.createOrUpdateSelectionOctree();
  62989. }
  62990. }
  62991. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  62992. scene.createOrUpdateSelectionOctree();
  62993. }
  62994. return true;
  62995. };
  62996. return _this;
  62997. }
  62998. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  62999. get: function () {
  63000. return MergeMeshesOptimization._UpdateSelectionTree;
  63001. },
  63002. set: function (value) {
  63003. MergeMeshesOptimization._UpdateSelectionTree = value;
  63004. },
  63005. enumerable: true,
  63006. configurable: true
  63007. });
  63008. return MergeMeshesOptimization;
  63009. }(SceneOptimization));
  63010. MergeMeshesOptimization._UpdateSelectionTree = false;
  63011. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  63012. // Options
  63013. var SceneOptimizerOptions = (function () {
  63014. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  63015. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  63016. if (trackerDuration === void 0) { trackerDuration = 2000; }
  63017. this.targetFrameRate = targetFrameRate;
  63018. this.trackerDuration = trackerDuration;
  63019. this.optimizations = new Array();
  63020. }
  63021. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  63022. var result = new SceneOptimizerOptions(targetFrameRate);
  63023. var priority = 0;
  63024. result.optimizations.push(new MergeMeshesOptimization(priority));
  63025. result.optimizations.push(new ShadowsOptimization(priority));
  63026. result.optimizations.push(new LensFlaresOptimization(priority));
  63027. // Next priority
  63028. priority++;
  63029. result.optimizations.push(new PostProcessesOptimization(priority));
  63030. result.optimizations.push(new ParticlesOptimization(priority));
  63031. // Next priority
  63032. priority++;
  63033. result.optimizations.push(new TextureOptimization(priority, 1024));
  63034. return result;
  63035. };
  63036. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  63037. var result = new SceneOptimizerOptions(targetFrameRate);
  63038. var priority = 0;
  63039. result.optimizations.push(new MergeMeshesOptimization(priority));
  63040. result.optimizations.push(new ShadowsOptimization(priority));
  63041. result.optimizations.push(new LensFlaresOptimization(priority));
  63042. // Next priority
  63043. priority++;
  63044. result.optimizations.push(new PostProcessesOptimization(priority));
  63045. result.optimizations.push(new ParticlesOptimization(priority));
  63046. // Next priority
  63047. priority++;
  63048. result.optimizations.push(new TextureOptimization(priority, 512));
  63049. // Next priority
  63050. priority++;
  63051. result.optimizations.push(new RenderTargetsOptimization(priority));
  63052. // Next priority
  63053. priority++;
  63054. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  63055. return result;
  63056. };
  63057. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  63058. var result = new SceneOptimizerOptions(targetFrameRate);
  63059. var priority = 0;
  63060. result.optimizations.push(new MergeMeshesOptimization(priority));
  63061. result.optimizations.push(new ShadowsOptimization(priority));
  63062. result.optimizations.push(new LensFlaresOptimization(priority));
  63063. // Next priority
  63064. priority++;
  63065. result.optimizations.push(new PostProcessesOptimization(priority));
  63066. result.optimizations.push(new ParticlesOptimization(priority));
  63067. // Next priority
  63068. priority++;
  63069. result.optimizations.push(new TextureOptimization(priority, 256));
  63070. // Next priority
  63071. priority++;
  63072. result.optimizations.push(new RenderTargetsOptimization(priority));
  63073. // Next priority
  63074. priority++;
  63075. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  63076. return result;
  63077. };
  63078. return SceneOptimizerOptions;
  63079. }());
  63080. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  63081. // Scene optimizer tool
  63082. var SceneOptimizer = (function () {
  63083. function SceneOptimizer() {
  63084. }
  63085. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  63086. // TODO: add an epsilon
  63087. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  63088. if (onSuccess) {
  63089. onSuccess();
  63090. }
  63091. return;
  63092. }
  63093. // Apply current level of optimizations
  63094. var allDone = true;
  63095. var noOptimizationApplied = true;
  63096. for (var index = 0; index < options.optimizations.length; index++) {
  63097. var optimization = options.optimizations[index];
  63098. if (optimization.priority === currentPriorityLevel) {
  63099. noOptimizationApplied = false;
  63100. allDone = allDone && optimization.apply(scene);
  63101. }
  63102. }
  63103. // If no optimization was applied, this is a failure :(
  63104. if (noOptimizationApplied) {
  63105. if (onFailure) {
  63106. onFailure();
  63107. }
  63108. return;
  63109. }
  63110. // If all optimizations were done, move to next level
  63111. if (allDone) {
  63112. currentPriorityLevel++;
  63113. }
  63114. // Let's the system running for a specific amount of time before checking FPS
  63115. scene.executeWhenReady(function () {
  63116. setTimeout(function () {
  63117. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  63118. }, options.trackerDuration);
  63119. });
  63120. };
  63121. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  63122. if (!options) {
  63123. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  63124. }
  63125. // Let's the system running for a specific amount of time before checking FPS
  63126. scene.executeWhenReady(function () {
  63127. setTimeout(function () {
  63128. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  63129. }, options.trackerDuration);
  63130. });
  63131. };
  63132. return SceneOptimizer;
  63133. }());
  63134. BABYLON.SceneOptimizer = SceneOptimizer;
  63135. })(BABYLON || (BABYLON = {}));
  63136. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  63137. var BABYLON;
  63138. (function (BABYLON) {
  63139. var OutlineRenderer = (function () {
  63140. function OutlineRenderer(scene) {
  63141. this._scene = scene;
  63142. }
  63143. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  63144. var _this = this;
  63145. if (useOverlay === void 0) { useOverlay = false; }
  63146. var scene = this._scene;
  63147. var engine = this._scene.getEngine();
  63148. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63149. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  63150. return;
  63151. }
  63152. var mesh = subMesh.getRenderingMesh();
  63153. var material = subMesh.getMaterial();
  63154. engine.enableEffect(this._effect);
  63155. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  63156. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  63157. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63158. // Bones
  63159. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63160. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63161. }
  63162. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  63163. // Alpha test
  63164. if (material && material.needAlphaTesting()) {
  63165. var alphaTexture = material.getAlphaTestTexture();
  63166. this._effect.setTexture("diffuseSampler", alphaTexture);
  63167. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63168. }
  63169. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  63170. };
  63171. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  63172. var defines = [];
  63173. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63174. var mesh = subMesh.getMesh();
  63175. var material = subMesh.getMaterial();
  63176. // Alpha test
  63177. if (material && material.needAlphaTesting()) {
  63178. defines.push("#define ALPHATEST");
  63179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63180. attribs.push(BABYLON.VertexBuffer.UVKind);
  63181. defines.push("#define UV1");
  63182. }
  63183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63185. defines.push("#define UV2");
  63186. }
  63187. }
  63188. // Bones
  63189. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63190. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63191. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63192. if (mesh.numBoneInfluencers > 4) {
  63193. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63194. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63195. }
  63196. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63197. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63198. }
  63199. else {
  63200. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63201. }
  63202. // Instances
  63203. if (useInstances) {
  63204. defines.push("#define INSTANCES");
  63205. attribs.push("world0");
  63206. attribs.push("world1");
  63207. attribs.push("world2");
  63208. attribs.push("world3");
  63209. }
  63210. // Get correct effect
  63211. var join = defines.join("\n");
  63212. if (this._cachedDefines !== join) {
  63213. this._cachedDefines = join;
  63214. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  63215. }
  63216. return this._effect.isReady();
  63217. };
  63218. return OutlineRenderer;
  63219. }());
  63220. BABYLON.OutlineRenderer = OutlineRenderer;
  63221. })(BABYLON || (BABYLON = {}));
  63222. //# sourceMappingURL=babylon.outlineRenderer.js.map
  63223. var BABYLON;
  63224. (function (BABYLON) {
  63225. var FaceAdjacencies = (function () {
  63226. function FaceAdjacencies() {
  63227. this.edges = new Array();
  63228. this.edgesConnectedCount = 0;
  63229. }
  63230. return FaceAdjacencies;
  63231. }());
  63232. var EdgesRenderer = (function () {
  63233. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  63234. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  63235. if (epsilon === void 0) { epsilon = 0.95; }
  63236. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  63237. this.edgesWidthScalerForOrthographic = 1000.0;
  63238. this.edgesWidthScalerForPerspective = 50.0;
  63239. this._linesPositions = new Array();
  63240. this._linesNormals = new Array();
  63241. this._linesIndices = new Array();
  63242. this._buffers = {};
  63243. this._checkVerticesInsteadOfIndices = false;
  63244. this._source = source;
  63245. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  63246. this._epsilon = epsilon;
  63247. this._prepareRessources();
  63248. this._generateEdgesLines();
  63249. }
  63250. EdgesRenderer.prototype._prepareRessources = function () {
  63251. if (this._lineShader) {
  63252. return;
  63253. }
  63254. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  63255. attributes: ["position", "normal"],
  63256. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  63257. });
  63258. this._lineShader.disableDepthWrite = true;
  63259. this._lineShader.backFaceCulling = false;
  63260. };
  63261. EdgesRenderer.prototype.dispose = function () {
  63262. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  63263. if (buffer) {
  63264. buffer.dispose();
  63265. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  63266. }
  63267. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  63268. if (buffer) {
  63269. buffer.dispose();
  63270. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  63271. }
  63272. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  63273. this._lineShader.dispose();
  63274. };
  63275. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  63276. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  63277. return 0;
  63278. }
  63279. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  63280. return 1;
  63281. }
  63282. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  63283. return 2;
  63284. }
  63285. return -1;
  63286. };
  63287. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  63288. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  63289. return 0;
  63290. }
  63291. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  63292. return 1;
  63293. }
  63294. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  63295. return 2;
  63296. }
  63297. return -1;
  63298. };
  63299. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  63300. var needToCreateLine;
  63301. if (edge === undefined) {
  63302. needToCreateLine = true;
  63303. }
  63304. else {
  63305. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  63306. needToCreateLine = dotProduct < this._epsilon;
  63307. }
  63308. if (needToCreateLine) {
  63309. var offset = this._linesPositions.length / 3;
  63310. var normal = p0.subtract(p1);
  63311. normal.normalize();
  63312. // Positions
  63313. this._linesPositions.push(p0.x);
  63314. this._linesPositions.push(p0.y);
  63315. this._linesPositions.push(p0.z);
  63316. this._linesPositions.push(p0.x);
  63317. this._linesPositions.push(p0.y);
  63318. this._linesPositions.push(p0.z);
  63319. this._linesPositions.push(p1.x);
  63320. this._linesPositions.push(p1.y);
  63321. this._linesPositions.push(p1.z);
  63322. this._linesPositions.push(p1.x);
  63323. this._linesPositions.push(p1.y);
  63324. this._linesPositions.push(p1.z);
  63325. // Normals
  63326. this._linesNormals.push(p1.x);
  63327. this._linesNormals.push(p1.y);
  63328. this._linesNormals.push(p1.z);
  63329. this._linesNormals.push(-1);
  63330. this._linesNormals.push(p1.x);
  63331. this._linesNormals.push(p1.y);
  63332. this._linesNormals.push(p1.z);
  63333. this._linesNormals.push(1);
  63334. this._linesNormals.push(p0.x);
  63335. this._linesNormals.push(p0.y);
  63336. this._linesNormals.push(p0.z);
  63337. this._linesNormals.push(-1);
  63338. this._linesNormals.push(p0.x);
  63339. this._linesNormals.push(p0.y);
  63340. this._linesNormals.push(p0.z);
  63341. this._linesNormals.push(1);
  63342. // Indices
  63343. this._linesIndices.push(offset);
  63344. this._linesIndices.push(offset + 1);
  63345. this._linesIndices.push(offset + 2);
  63346. this._linesIndices.push(offset);
  63347. this._linesIndices.push(offset + 2);
  63348. this._linesIndices.push(offset + 3);
  63349. }
  63350. };
  63351. EdgesRenderer.prototype._generateEdgesLines = function () {
  63352. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63353. var indices = this._source.getIndices();
  63354. // First let's find adjacencies
  63355. var adjacencies = new Array();
  63356. var faceNormals = new Array();
  63357. var index;
  63358. var faceAdjacencies;
  63359. // Prepare faces
  63360. for (index = 0; index < indices.length; index += 3) {
  63361. faceAdjacencies = new FaceAdjacencies();
  63362. var p0Index = indices[index];
  63363. var p1Index = indices[index + 1];
  63364. var p2Index = indices[index + 2];
  63365. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  63366. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  63367. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  63368. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  63369. faceNormal.normalize();
  63370. faceNormals.push(faceNormal);
  63371. adjacencies.push(faceAdjacencies);
  63372. }
  63373. // Scan
  63374. for (index = 0; index < adjacencies.length; index++) {
  63375. faceAdjacencies = adjacencies[index];
  63376. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  63377. var otherFaceAdjacencies = adjacencies[otherIndex];
  63378. if (faceAdjacencies.edgesConnectedCount === 3) {
  63379. break;
  63380. }
  63381. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  63382. continue;
  63383. }
  63384. var otherP0 = indices[otherIndex * 3];
  63385. var otherP1 = indices[otherIndex * 3 + 1];
  63386. var otherP2 = indices[otherIndex * 3 + 2];
  63387. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  63388. var otherEdgeIndex;
  63389. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  63390. continue;
  63391. }
  63392. switch (edgeIndex) {
  63393. case 0:
  63394. if (this._checkVerticesInsteadOfIndices) {
  63395. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  63396. }
  63397. else {
  63398. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  63399. }
  63400. break;
  63401. case 1:
  63402. if (this._checkVerticesInsteadOfIndices) {
  63403. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  63404. }
  63405. else {
  63406. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  63407. }
  63408. break;
  63409. case 2:
  63410. if (this._checkVerticesInsteadOfIndices) {
  63411. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  63412. }
  63413. else {
  63414. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  63415. }
  63416. break;
  63417. }
  63418. if (otherEdgeIndex === -1) {
  63419. continue;
  63420. }
  63421. faceAdjacencies.edges[edgeIndex] = otherIndex;
  63422. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  63423. faceAdjacencies.edgesConnectedCount++;
  63424. otherFaceAdjacencies.edgesConnectedCount++;
  63425. if (faceAdjacencies.edgesConnectedCount === 3) {
  63426. break;
  63427. }
  63428. }
  63429. }
  63430. }
  63431. // Create lines
  63432. for (index = 0; index < adjacencies.length; index++) {
  63433. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  63434. var current = adjacencies[index];
  63435. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  63436. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  63437. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  63438. }
  63439. // Merge into a single mesh
  63440. var engine = this._source.getScene().getEngine();
  63441. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  63442. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  63443. this._ib = engine.createIndexBuffer(this._linesIndices);
  63444. this._indicesCount = this._linesIndices.length;
  63445. };
  63446. EdgesRenderer.prototype.render = function () {
  63447. if (!this._lineShader.isReady()) {
  63448. return;
  63449. }
  63450. var scene = this._source.getScene();
  63451. var engine = scene.getEngine();
  63452. this._lineShader._preBind();
  63453. // VBOs
  63454. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  63455. scene.resetCachedMaterial();
  63456. this._lineShader.setColor4("color", this._source.edgesColor);
  63457. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  63458. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  63459. }
  63460. else {
  63461. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  63462. }
  63463. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  63464. this._lineShader.bind(this._source.getWorldMatrix());
  63465. // Draw order
  63466. engine.draw(true, 0, this._indicesCount);
  63467. this._lineShader.unbind();
  63468. engine.setDepthWrite(true);
  63469. };
  63470. return EdgesRenderer;
  63471. }());
  63472. BABYLON.EdgesRenderer = EdgesRenderer;
  63473. })(BABYLON || (BABYLON = {}));
  63474. //# sourceMappingURL=babylon.edgesRenderer.js.map
  63475. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  63476. /// <reference path="..\Math\babylon.math.ts" />
  63477. var BABYLON;
  63478. (function (BABYLON) {
  63479. /**
  63480. * Special Glow Blur post process only blurring the alpha channel
  63481. * It enforces keeping the most luminous color in the color channel.
  63482. */
  63483. var GlowBlurPostProcess = (function (_super) {
  63484. __extends(GlowBlurPostProcess, _super);
  63485. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  63486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63487. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  63488. _this.direction = direction;
  63489. _this.kernel = kernel;
  63490. _this.onApplyObservable.add(function (effect) {
  63491. effect.setFloat2("screenSize", _this.width, _this.height);
  63492. effect.setVector2("direction", _this.direction);
  63493. effect.setFloat("blurWidth", _this.kernel);
  63494. });
  63495. return _this;
  63496. }
  63497. return GlowBlurPostProcess;
  63498. }(BABYLON.PostProcess));
  63499. /**
  63500. * The highlight layer Helps adding a glow effect around a mesh.
  63501. *
  63502. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  63503. * glowy meshes to your scene.
  63504. *
  63505. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  63506. */
  63507. var HighlightLayer = (function () {
  63508. /**
  63509. * Instantiates a new highlight Layer and references it to the scene..
  63510. * @param name The name of the layer
  63511. * @param scene The scene to use the layer in
  63512. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  63513. */
  63514. function HighlightLayer(name, scene, options) {
  63515. this.name = name;
  63516. this._vertexBuffers = {};
  63517. this._mainTextureDesiredSize = { width: 0, height: 0 };
  63518. this._meshes = {};
  63519. this._maxSize = 0;
  63520. this._shouldRender = false;
  63521. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  63522. this._excludedMeshes = {};
  63523. /**
  63524. * Specifies whether or not the inner glow is ACTIVE in the layer.
  63525. */
  63526. this.innerGlow = true;
  63527. /**
  63528. * Specifies whether or not the outer glow is ACTIVE in the layer.
  63529. */
  63530. this.outerGlow = true;
  63531. /**
  63532. * Specifies wether the highlight layer is enabled or not.
  63533. */
  63534. this.isEnabled = true;
  63535. /**
  63536. * An event triggered when the highlight layer has been disposed.
  63537. * @type {BABYLON.Observable}
  63538. */
  63539. this.onDisposeObservable = new BABYLON.Observable();
  63540. /**
  63541. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  63542. * @type {BABYLON.Observable}
  63543. */
  63544. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  63545. /**
  63546. * An event triggered when the highlight layer is being blurred.
  63547. * @type {BABYLON.Observable}
  63548. */
  63549. this.onBeforeBlurObservable = new BABYLON.Observable();
  63550. /**
  63551. * An event triggered when the highlight layer has been blurred.
  63552. * @type {BABYLON.Observable}
  63553. */
  63554. this.onAfterBlurObservable = new BABYLON.Observable();
  63555. /**
  63556. * An event triggered when the glowing blurred texture is being merged in the scene.
  63557. * @type {BABYLON.Observable}
  63558. */
  63559. this.onBeforeComposeObservable = new BABYLON.Observable();
  63560. /**
  63561. * An event triggered when the glowing blurred texture has been merged in the scene.
  63562. * @type {BABYLON.Observable}
  63563. */
  63564. this.onAfterComposeObservable = new BABYLON.Observable();
  63565. /**
  63566. * An event triggered when the highlight layer changes its size.
  63567. * @type {BABYLON.Observable}
  63568. */
  63569. this.onSizeChangedObservable = new BABYLON.Observable();
  63570. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63571. var engine = scene.getEngine();
  63572. this._engine = engine;
  63573. this._maxSize = this._engine.getCaps().maxTextureSize;
  63574. this._scene.highlightLayers.push(this);
  63575. // Warn on stencil.
  63576. if (!this._engine.isStencilEnable) {
  63577. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  63578. }
  63579. // Adapt options
  63580. this._options = options || {
  63581. mainTextureRatio: 0.25,
  63582. blurTextureSizeRatio: 0.5,
  63583. blurHorizontalSize: 1,
  63584. blurVerticalSize: 1,
  63585. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  63586. };
  63587. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  63588. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  63589. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  63590. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  63591. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  63592. // VBO
  63593. var vertices = [];
  63594. vertices.push(1, 1);
  63595. vertices.push(-1, 1);
  63596. vertices.push(-1, -1);
  63597. vertices.push(1, -1);
  63598. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  63600. // Indices
  63601. var indices = [];
  63602. indices.push(0);
  63603. indices.push(1);
  63604. indices.push(2);
  63605. indices.push(0);
  63606. indices.push(2);
  63607. indices.push(3);
  63608. this._indexBuffer = engine.createIndexBuffer(indices);
  63609. // Effect
  63610. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  63611. // Render target
  63612. this.setMainTextureSize();
  63613. // Create Textures and post processes
  63614. this.createTextureAndPostProcesses();
  63615. }
  63616. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  63617. /**
  63618. * Gets the horizontal size of the blur.
  63619. */
  63620. get: function () {
  63621. return this._horizontalBlurPostprocess.kernel;
  63622. },
  63623. /**
  63624. * Specifies the horizontal size of the blur.
  63625. */
  63626. set: function (value) {
  63627. this._horizontalBlurPostprocess.kernel = value;
  63628. },
  63629. enumerable: true,
  63630. configurable: true
  63631. });
  63632. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  63633. /**
  63634. * Gets the vertical size of the blur.
  63635. */
  63636. get: function () {
  63637. return this._verticalBlurPostprocess.kernel;
  63638. },
  63639. /**
  63640. * Specifies the vertical size of the blur.
  63641. */
  63642. set: function (value) {
  63643. this._verticalBlurPostprocess.kernel = value;
  63644. },
  63645. enumerable: true,
  63646. configurable: true
  63647. });
  63648. Object.defineProperty(HighlightLayer.prototype, "camera", {
  63649. /**
  63650. * Gets the camera attached to the layer.
  63651. */
  63652. get: function () {
  63653. return this._options.camera;
  63654. },
  63655. enumerable: true,
  63656. configurable: true
  63657. });
  63658. /**
  63659. * Creates the render target textures and post processes used in the highlight layer.
  63660. */
  63661. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  63662. var _this = this;
  63663. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  63664. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  63665. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  63666. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  63667. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  63668. width: this._mainTextureDesiredSize.width,
  63669. height: this._mainTextureDesiredSize.height
  63670. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63671. this._mainTexture.activeCamera = this._options.camera;
  63672. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63673. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63674. this._mainTexture.anisotropicFilteringLevel = 1;
  63675. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63676. this._mainTexture.renderParticles = false;
  63677. this._mainTexture.renderList = null;
  63678. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  63679. width: blurTextureWidth,
  63680. height: blurTextureHeight
  63681. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63682. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63683. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63684. this._blurTexture.anisotropicFilteringLevel = 16;
  63685. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63686. this._blurTexture.renderParticles = false;
  63687. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63688. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  63689. effect.setTexture("textureSampler", _this._mainTexture);
  63690. });
  63691. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  63692. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63693. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  63694. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63695. });
  63696. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63697. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  63698. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63699. });
  63700. }
  63701. else {
  63702. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63703. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  63704. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63705. });
  63706. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63707. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  63708. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63709. });
  63710. }
  63711. this._mainTexture.onAfterUnbindObservable.add(function () {
  63712. _this.onBeforeBlurObservable.notifyObservers(_this);
  63713. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  63714. _this.onAfterBlurObservable.notifyObservers(_this);
  63715. });
  63716. // Custom render function
  63717. var renderSubMesh = function (subMesh) {
  63718. var mesh = subMesh.getRenderingMesh();
  63719. var scene = _this._scene;
  63720. var engine = scene.getEngine();
  63721. // Culling
  63722. engine.setState(subMesh.getMaterial().backFaceCulling);
  63723. // Managing instances
  63724. var batch = mesh._getInstancesRenderList(subMesh._id);
  63725. if (batch.mustReturn) {
  63726. return;
  63727. }
  63728. // Excluded Mesh
  63729. if (_this._excludedMeshes[mesh.uniqueId]) {
  63730. return;
  63731. }
  63732. ;
  63733. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63734. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  63735. var material = subMesh.getMaterial();
  63736. var emissiveTexture = null;
  63737. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  63738. emissiveTexture = material.emissiveTexture;
  63739. }
  63740. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  63741. engine.enableEffect(_this._glowMapGenerationEffect);
  63742. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  63743. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  63744. if (highlightLayerMesh) {
  63745. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  63746. }
  63747. else {
  63748. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  63749. }
  63750. // Alpha test
  63751. if (material && material.needAlphaTesting()) {
  63752. var alphaTexture = material.getAlphaTestTexture();
  63753. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  63754. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63755. }
  63756. // Glow emissive only
  63757. if (emissiveTexture) {
  63758. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  63759. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  63760. }
  63761. // Bones
  63762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63763. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63764. }
  63765. // Draw
  63766. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  63767. }
  63768. else {
  63769. // Need to reset refresh rate of the shadowMap
  63770. _this._mainTexture.resetRefreshCounter();
  63771. }
  63772. };
  63773. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  63774. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  63775. var index;
  63776. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63777. renderSubMesh(opaqueSubMeshes.data[index]);
  63778. }
  63779. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63780. renderSubMesh(alphaTestSubMeshes.data[index]);
  63781. }
  63782. for (index = 0; index < transparentSubMeshes.length; index++) {
  63783. renderSubMesh(transparentSubMeshes.data[index]);
  63784. }
  63785. };
  63786. this._mainTexture.onClearObservable.add(function (engine) {
  63787. engine.clear(HighlightLayer.neutralColor, true, true, true);
  63788. });
  63789. };
  63790. /**
  63791. * Checks for the readiness of the element composing the layer.
  63792. * @param subMesh the mesh to check for
  63793. * @param useInstances specify wether or not to use instances to render the mesh
  63794. * @param emissiveTexture the associated emissive texture used to generate the glow
  63795. * @return true if ready otherwise, false
  63796. */
  63797. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  63798. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  63799. return false;
  63800. }
  63801. var defines = [];
  63802. var attribs = [BABYLON.VertexBuffer.PositionKind];
  63803. var mesh = subMesh.getMesh();
  63804. var material = subMesh.getMaterial();
  63805. var uv1 = false;
  63806. var uv2 = false;
  63807. // Alpha test
  63808. if (material && material.needAlphaTesting()) {
  63809. var alphaTexture = material.getAlphaTestTexture();
  63810. if (alphaTexture) {
  63811. defines.push("#define ALPHATEST");
  63812. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  63813. alphaTexture.coordinatesIndex === 1) {
  63814. defines.push("#define DIFFUSEUV2");
  63815. uv2 = true;
  63816. }
  63817. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63818. defines.push("#define DIFFUSEUV1");
  63819. uv1 = true;
  63820. }
  63821. }
  63822. }
  63823. // Emissive
  63824. if (emissiveTexture) {
  63825. defines.push("#define EMISSIVE");
  63826. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  63827. emissiveTexture.coordinatesIndex === 1) {
  63828. defines.push("#define EMISSIVEUV2");
  63829. uv2 = true;
  63830. }
  63831. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63832. defines.push("#define EMISSIVEUV1");
  63833. uv1 = true;
  63834. }
  63835. }
  63836. if (uv1) {
  63837. attribs.push(BABYLON.VertexBuffer.UVKind);
  63838. defines.push("#define UV1");
  63839. }
  63840. if (uv2) {
  63841. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63842. defines.push("#define UV2");
  63843. }
  63844. // Bones
  63845. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63848. if (mesh.numBoneInfluencers > 4) {
  63849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63851. }
  63852. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63853. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63854. }
  63855. else {
  63856. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63857. }
  63858. // Instances
  63859. if (useInstances) {
  63860. defines.push("#define INSTANCES");
  63861. attribs.push("world0");
  63862. attribs.push("world1");
  63863. attribs.push("world2");
  63864. attribs.push("world3");
  63865. }
  63866. // Get correct effect
  63867. var join = defines.join("\n");
  63868. if (this._cachedDefines !== join) {
  63869. this._cachedDefines = join;
  63870. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  63871. }
  63872. return this._glowMapGenerationEffect.isReady();
  63873. };
  63874. /**
  63875. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  63876. */
  63877. HighlightLayer.prototype.render = function () {
  63878. var currentEffect = this._glowMapMergeEffect;
  63879. // Check
  63880. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  63881. return;
  63882. var engine = this._scene.getEngine();
  63883. this.onBeforeComposeObservable.notifyObservers(this);
  63884. // Render
  63885. engine.enableEffect(currentEffect);
  63886. engine.setState(false);
  63887. // Cache
  63888. var previousStencilBuffer = engine.getStencilBuffer();
  63889. var previousStencilFunction = engine.getStencilFunction();
  63890. var previousStencilMask = engine.getStencilMask();
  63891. var previousStencilOperationPass = engine.getStencilOperationPass();
  63892. var previousStencilOperationFail = engine.getStencilOperationFail();
  63893. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  63894. var previousAlphaMode = engine.getAlphaMode();
  63895. // Texture
  63896. currentEffect.setTexture("textureSampler", this._blurTexture);
  63897. // VBOs
  63898. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  63899. // Stencil operations
  63900. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  63901. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  63902. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  63903. // Draw order
  63904. engine.setAlphaMode(this._options.alphaBlendingMode);
  63905. engine.setStencilMask(0x00);
  63906. engine.setStencilBuffer(true);
  63907. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  63908. if (this.outerGlow) {
  63909. currentEffect.setFloat("offset", 0);
  63910. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  63911. engine.draw(true, 0, 6);
  63912. }
  63913. if (this.innerGlow) {
  63914. currentEffect.setFloat("offset", 1);
  63915. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  63916. engine.draw(true, 0, 6);
  63917. }
  63918. // Restore Cache
  63919. engine.setStencilFunction(previousStencilFunction);
  63920. engine.setStencilMask(previousStencilMask);
  63921. engine.setAlphaMode(previousAlphaMode);
  63922. engine.setStencilBuffer(previousStencilBuffer);
  63923. engine.setStencilOperationPass(previousStencilOperationPass);
  63924. engine.setStencilOperationFail(previousStencilOperationFail);
  63925. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  63926. engine._stencilState.reset();
  63927. this.onAfterComposeObservable.notifyObservers(this);
  63928. // Handle size changes.
  63929. var size = this._mainTexture.getSize();
  63930. this.setMainTextureSize();
  63931. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  63932. // Recreate RTT and post processes on size change.
  63933. this.onSizeChangedObservable.notifyObservers(this);
  63934. this.disposeTextureAndPostProcesses();
  63935. this.createTextureAndPostProcesses();
  63936. }
  63937. };
  63938. /**
  63939. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  63940. * @param mesh The mesh to exclude from the highlight layer
  63941. */
  63942. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  63943. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  63944. if (!meshExcluded) {
  63945. this._excludedMeshes[mesh.uniqueId] = {
  63946. mesh: mesh,
  63947. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  63948. mesh.getEngine().setStencilBuffer(false);
  63949. }),
  63950. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  63951. mesh.getEngine().setStencilBuffer(true);
  63952. }),
  63953. };
  63954. }
  63955. };
  63956. /**
  63957. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  63958. * @param mesh The mesh to highlight
  63959. */
  63960. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  63961. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  63962. if (meshExcluded) {
  63963. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  63964. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  63965. }
  63966. this._excludedMeshes[mesh.uniqueId] = undefined;
  63967. };
  63968. /**
  63969. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  63970. * @param mesh The mesh to highlight
  63971. * @param color The color of the highlight
  63972. * @param glowEmissiveOnly Extract the glow from the emissive texture
  63973. */
  63974. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  63975. var _this = this;
  63976. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  63977. var meshHighlight = this._meshes[mesh.uniqueId];
  63978. if (meshHighlight) {
  63979. meshHighlight.color = color;
  63980. }
  63981. else {
  63982. this._meshes[mesh.uniqueId] = {
  63983. mesh: mesh,
  63984. color: color,
  63985. // Lambda required for capture due to Observable this context
  63986. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  63987. if (_this._excludedMeshes[mesh.uniqueId]) {
  63988. _this.defaultStencilReference(mesh);
  63989. }
  63990. else {
  63991. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  63992. }
  63993. }),
  63994. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  63995. glowEmissiveOnly: glowEmissiveOnly
  63996. };
  63997. }
  63998. this._shouldRender = true;
  63999. };
  64000. /**
  64001. * Remove a mesh from the highlight layer in order to make it stop glowing.
  64002. * @param mesh The mesh to highlight
  64003. */
  64004. HighlightLayer.prototype.removeMesh = function (mesh) {
  64005. var meshHighlight = this._meshes[mesh.uniqueId];
  64006. if (meshHighlight) {
  64007. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  64008. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  64009. }
  64010. this._meshes[mesh.uniqueId] = undefined;
  64011. this._shouldRender = false;
  64012. for (var meshHighlightToCheck in this._meshes) {
  64013. if (meshHighlightToCheck) {
  64014. this._shouldRender = true;
  64015. break;
  64016. }
  64017. }
  64018. };
  64019. /**
  64020. * Returns true if the layer contains information to display, otherwise false.
  64021. */
  64022. HighlightLayer.prototype.shouldRender = function () {
  64023. return this.isEnabled && this._shouldRender;
  64024. };
  64025. /**
  64026. * Sets the main texture desired size which is the closest power of two
  64027. * of the engine canvas size.
  64028. */
  64029. HighlightLayer.prototype.setMainTextureSize = function () {
  64030. if (this._options.mainTextureFixedSize) {
  64031. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  64032. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  64033. }
  64034. else {
  64035. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  64036. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  64037. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  64038. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  64039. }
  64040. };
  64041. /**
  64042. * Force the stencil to the normal expected value for none glowing parts
  64043. */
  64044. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  64045. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  64046. };
  64047. /**
  64048. * Dispose only the render target textures and post process.
  64049. */
  64050. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  64051. this._blurTexture.dispose();
  64052. this._mainTexture.dispose();
  64053. this._downSamplePostprocess.dispose();
  64054. this._horizontalBlurPostprocess.dispose();
  64055. this._verticalBlurPostprocess.dispose();
  64056. };
  64057. /**
  64058. * Dispose the highlight layer and free resources.
  64059. */
  64060. HighlightLayer.prototype.dispose = function () {
  64061. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64062. if (vertexBuffer) {
  64063. vertexBuffer.dispose();
  64064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64065. }
  64066. if (this._indexBuffer) {
  64067. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64068. this._indexBuffer = null;
  64069. }
  64070. // Clean textures and post processes
  64071. this.disposeTextureAndPostProcesses();
  64072. // Clean mesh references
  64073. for (var id in this._meshes) {
  64074. var meshHighlight = this._meshes[id];
  64075. if (meshHighlight && meshHighlight.mesh) {
  64076. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  64077. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  64078. }
  64079. }
  64080. this._meshes = null;
  64081. for (var id in this._excludedMeshes) {
  64082. var meshHighlight = this._excludedMeshes[id];
  64083. if (meshHighlight) {
  64084. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  64085. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  64086. }
  64087. }
  64088. this._excludedMeshes = null;
  64089. // Remove from scene
  64090. var index = this._scene.highlightLayers.indexOf(this, 0);
  64091. if (index > -1) {
  64092. this._scene.highlightLayers.splice(index, 1);
  64093. }
  64094. // Callback
  64095. this.onDisposeObservable.notifyObservers(this);
  64096. this.onDisposeObservable.clear();
  64097. this.onBeforeRenderMainTextureObservable.clear();
  64098. this.onBeforeBlurObservable.clear();
  64099. this.onBeforeComposeObservable.clear();
  64100. this.onAfterComposeObservable.clear();
  64101. this.onSizeChangedObservable.clear();
  64102. };
  64103. return HighlightLayer;
  64104. }());
  64105. /**
  64106. * The neutral color used during the preparation of the glow effect.
  64107. * This is black by default as the blend operation is a blend operation.
  64108. */
  64109. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  64110. /**
  64111. * Stencil value used for glowing meshes.
  64112. */
  64113. HighlightLayer.glowingMeshStencilReference = 0x02;
  64114. /**
  64115. * Stencil value used for the other meshes in the scene.
  64116. */
  64117. HighlightLayer.normalMeshStencilReference = 0x01;
  64118. BABYLON.HighlightLayer = HighlightLayer;
  64119. })(BABYLON || (BABYLON = {}));
  64120. //# sourceMappingURL=babylon.highlightlayer.js.map
  64121. var BABYLON;
  64122. (function (BABYLON) {
  64123. var MeshAssetTask = (function () {
  64124. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  64125. this.name = name;
  64126. this.meshesNames = meshesNames;
  64127. this.rootUrl = rootUrl;
  64128. this.sceneFilename = sceneFilename;
  64129. this.isCompleted = false;
  64130. }
  64131. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64132. var _this = this;
  64133. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  64134. _this.loadedMeshes = meshes;
  64135. _this.loadedParticleSystems = particleSystems;
  64136. _this.loadedSkeletons = skeletons;
  64137. _this.isCompleted = true;
  64138. if (_this.onSuccess) {
  64139. _this.onSuccess(_this);
  64140. }
  64141. onSuccess();
  64142. }, null, function () {
  64143. if (_this.onError) {
  64144. _this.onError(_this);
  64145. }
  64146. onError();
  64147. });
  64148. };
  64149. return MeshAssetTask;
  64150. }());
  64151. BABYLON.MeshAssetTask = MeshAssetTask;
  64152. var TextFileAssetTask = (function () {
  64153. function TextFileAssetTask(name, url) {
  64154. this.name = name;
  64155. this.url = url;
  64156. this.isCompleted = false;
  64157. }
  64158. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64159. var _this = this;
  64160. BABYLON.Tools.LoadFile(this.url, function (data) {
  64161. _this.text = data;
  64162. _this.isCompleted = true;
  64163. if (_this.onSuccess) {
  64164. _this.onSuccess(_this);
  64165. }
  64166. onSuccess();
  64167. }, null, scene.database, false, function () {
  64168. if (_this.onError) {
  64169. _this.onError(_this);
  64170. }
  64171. onError();
  64172. });
  64173. };
  64174. return TextFileAssetTask;
  64175. }());
  64176. BABYLON.TextFileAssetTask = TextFileAssetTask;
  64177. var BinaryFileAssetTask = (function () {
  64178. function BinaryFileAssetTask(name, url) {
  64179. this.name = name;
  64180. this.url = url;
  64181. this.isCompleted = false;
  64182. }
  64183. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64184. var _this = this;
  64185. BABYLON.Tools.LoadFile(this.url, function (data) {
  64186. _this.data = data;
  64187. _this.isCompleted = true;
  64188. if (_this.onSuccess) {
  64189. _this.onSuccess(_this);
  64190. }
  64191. onSuccess();
  64192. }, null, scene.database, true, function () {
  64193. if (_this.onError) {
  64194. _this.onError(_this);
  64195. }
  64196. onError();
  64197. });
  64198. };
  64199. return BinaryFileAssetTask;
  64200. }());
  64201. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  64202. var ImageAssetTask = (function () {
  64203. function ImageAssetTask(name, url) {
  64204. this.name = name;
  64205. this.url = url;
  64206. this.isCompleted = false;
  64207. }
  64208. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64209. var _this = this;
  64210. var img = new Image();
  64211. BABYLON.Tools.SetCorsBehavior(this.url, img);
  64212. img.onload = function () {
  64213. _this.image = img;
  64214. _this.isCompleted = true;
  64215. if (_this.onSuccess) {
  64216. _this.onSuccess(_this);
  64217. }
  64218. onSuccess();
  64219. };
  64220. img.onerror = function () {
  64221. if (_this.onError) {
  64222. _this.onError(_this);
  64223. }
  64224. onError();
  64225. };
  64226. img.src = this.url;
  64227. };
  64228. return ImageAssetTask;
  64229. }());
  64230. BABYLON.ImageAssetTask = ImageAssetTask;
  64231. var TextureAssetTask = (function () {
  64232. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  64233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64234. this.name = name;
  64235. this.url = url;
  64236. this.noMipmap = noMipmap;
  64237. this.invertY = invertY;
  64238. this.samplingMode = samplingMode;
  64239. this.isCompleted = false;
  64240. }
  64241. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64242. var _this = this;
  64243. var onload = function () {
  64244. _this.isCompleted = true;
  64245. if (_this.onSuccess) {
  64246. _this.onSuccess(_this);
  64247. }
  64248. onSuccess();
  64249. };
  64250. var onerror = function () {
  64251. if (_this.onError) {
  64252. _this.onError(_this);
  64253. }
  64254. onError();
  64255. };
  64256. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  64257. };
  64258. return TextureAssetTask;
  64259. }());
  64260. BABYLON.TextureAssetTask = TextureAssetTask;
  64261. var CubeTextureAssetTask = (function () {
  64262. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  64263. this.name = name;
  64264. this.url = url;
  64265. this.extensions = extensions;
  64266. this.noMipmap = noMipmap;
  64267. this.files = files;
  64268. this.isCompleted = false;
  64269. }
  64270. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64271. var _this = this;
  64272. var onload = function () {
  64273. _this.isCompleted = true;
  64274. if (_this.onSuccess) {
  64275. _this.onSuccess(_this);
  64276. }
  64277. onSuccess();
  64278. };
  64279. var onerror = function () {
  64280. if (_this.onError) {
  64281. _this.onError(_this);
  64282. }
  64283. onError();
  64284. };
  64285. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  64286. };
  64287. return CubeTextureAssetTask;
  64288. }());
  64289. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  64290. var HDRCubeTextureAssetTask = (function () {
  64291. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  64292. if (noMipmap === void 0) { noMipmap = false; }
  64293. if (generateHarmonics === void 0) { generateHarmonics = true; }
  64294. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  64295. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  64296. this.name = name;
  64297. this.url = url;
  64298. this.size = size;
  64299. this.noMipmap = noMipmap;
  64300. this.generateHarmonics = generateHarmonics;
  64301. this.useInGammaSpace = useInGammaSpace;
  64302. this.usePMREMGenerator = usePMREMGenerator;
  64303. this.isCompleted = false;
  64304. }
  64305. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64306. var _this = this;
  64307. var onload = function () {
  64308. _this.isCompleted = true;
  64309. if (_this.onSuccess) {
  64310. _this.onSuccess(_this);
  64311. }
  64312. onSuccess();
  64313. };
  64314. var onerror = function () {
  64315. if (_this.onError) {
  64316. _this.onError(_this);
  64317. }
  64318. onError();
  64319. };
  64320. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  64321. };
  64322. return HDRCubeTextureAssetTask;
  64323. }());
  64324. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  64325. var AssetsManager = (function () {
  64326. function AssetsManager(scene) {
  64327. this.tasks = new Array();
  64328. this.waitingTasksCount = 0;
  64329. this.useDefaultLoadingScreen = true;
  64330. this._scene = scene;
  64331. }
  64332. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  64333. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  64334. this.tasks.push(task);
  64335. return task;
  64336. };
  64337. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  64338. var task = new TextFileAssetTask(taskName, url);
  64339. this.tasks.push(task);
  64340. return task;
  64341. };
  64342. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  64343. var task = new BinaryFileAssetTask(taskName, url);
  64344. this.tasks.push(task);
  64345. return task;
  64346. };
  64347. AssetsManager.prototype.addImageTask = function (taskName, url) {
  64348. var task = new ImageAssetTask(taskName, url);
  64349. this.tasks.push(task);
  64350. return task;
  64351. };
  64352. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  64353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64354. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  64355. this.tasks.push(task);
  64356. return task;
  64357. };
  64358. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  64359. this.waitingTasksCount--;
  64360. if (this.waitingTasksCount === 0) {
  64361. if (this.onFinish) {
  64362. this.onFinish(this.tasks);
  64363. }
  64364. this._scene.getEngine().hideLoadingUI();
  64365. }
  64366. };
  64367. AssetsManager.prototype._runTask = function (task) {
  64368. var _this = this;
  64369. task.run(this._scene, function () {
  64370. if (_this.onTaskSuccess) {
  64371. _this.onTaskSuccess(task);
  64372. }
  64373. _this._decreaseWaitingTasksCount();
  64374. }, function () {
  64375. if (_this.onTaskError) {
  64376. _this.onTaskError(task);
  64377. }
  64378. _this._decreaseWaitingTasksCount();
  64379. });
  64380. };
  64381. AssetsManager.prototype.reset = function () {
  64382. this.tasks = new Array();
  64383. return this;
  64384. };
  64385. AssetsManager.prototype.load = function () {
  64386. this.waitingTasksCount = this.tasks.length;
  64387. if (this.waitingTasksCount === 0) {
  64388. if (this.onFinish) {
  64389. this.onFinish(this.tasks);
  64390. }
  64391. return this;
  64392. }
  64393. if (this.useDefaultLoadingScreen) {
  64394. this._scene.getEngine().displayLoadingUI();
  64395. }
  64396. for (var index = 0; index < this.tasks.length; index++) {
  64397. var task = this.tasks[index];
  64398. this._runTask(task);
  64399. }
  64400. return this;
  64401. };
  64402. return AssetsManager;
  64403. }());
  64404. BABYLON.AssetsManager = AssetsManager;
  64405. })(BABYLON || (BABYLON = {}));
  64406. //# sourceMappingURL=babylon.assetsManager.js.map
  64407. var BABYLON;
  64408. (function (BABYLON) {
  64409. var MapTexture = (function (_super) {
  64410. __extends(MapTexture, _super);
  64411. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  64412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64413. if (useMipMap === void 0) { useMipMap = false; }
  64414. if (margin === void 0) { margin = 0; }
  64415. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  64416. _this.name = name;
  64417. _this._size = size;
  64418. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64419. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64420. // Create the rectPackMap that will allocate portion of the texture
  64421. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  64422. // Create the texture that will store the content
  64423. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  64424. return _this;
  64425. }
  64426. /**
  64427. * Allocate a rectangle of a given size in the texture map
  64428. * @param size the size of the rectangle to allocation
  64429. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  64430. */
  64431. MapTexture.prototype.allocateRect = function (size) {
  64432. return this._rectPackingMap.addRect(size);
  64433. };
  64434. /**
  64435. * Free a given rectangle from the texture map
  64436. * @param rectInfo the instance corresponding to the rect to free.
  64437. */
  64438. MapTexture.prototype.freeRect = function (rectInfo) {
  64439. if (rectInfo) {
  64440. rectInfo.freeContent();
  64441. }
  64442. };
  64443. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  64444. /**
  64445. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  64446. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  64447. * @returns {}
  64448. */
  64449. get: function () {
  64450. return this._rectPackingMap.freeSpace;
  64451. },
  64452. enumerable: true,
  64453. configurable: true
  64454. });
  64455. /**
  64456. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  64457. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  64458. * Don't forget to call unbindTexture when you're done rendering
  64459. * @param rect the zone to render to
  64460. * @param clear true to clear the portion's color/depth data
  64461. */
  64462. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  64463. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  64464. };
  64465. /**
  64466. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  64467. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  64468. * Don't forget to call unbindTexture when you're done rendering
  64469. * @param pos the position into the texture
  64470. * @param size the portion to fit the clip space to
  64471. * @param clear true to clear the portion's color/depth data
  64472. */
  64473. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  64474. var engine = this.getScene().getEngine();
  64475. engine.bindFramebuffer(this._texture);
  64476. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  64477. if (clear) {
  64478. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  64479. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  64480. }
  64481. };
  64482. /**
  64483. * Unbind the texture map from the rendering engine.
  64484. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  64485. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  64486. */
  64487. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  64488. // Dump ?
  64489. if (dumpForDebug) {
  64490. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  64491. }
  64492. var engine = this.getScene().getEngine();
  64493. if (this._replacedViewport) {
  64494. engine.setViewport(this._replacedViewport);
  64495. this._replacedViewport = null;
  64496. }
  64497. engine.unBindFramebuffer(this._texture);
  64498. };
  64499. Object.defineProperty(MapTexture.prototype, "canRescale", {
  64500. get: function () {
  64501. return false;
  64502. },
  64503. enumerable: true,
  64504. configurable: true
  64505. });
  64506. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  64507. // Anyway, there's not much point to use this method for this kind of texture I guess
  64508. MapTexture.prototype.clone = function () {
  64509. return null;
  64510. };
  64511. return MapTexture;
  64512. }(BABYLON.Texture));
  64513. BABYLON.MapTexture = MapTexture;
  64514. })(BABYLON || (BABYLON = {}));
  64515. //# sourceMappingURL=babylon.mapTexture.js.map
  64516. var BABYLON;
  64517. (function (BABYLON) {
  64518. /**
  64519. * This class describe a rectangle that were added to the map.
  64520. * You have access to its coordinates either in pixel or normalized (UV)
  64521. */
  64522. var PackedRect = (function () {
  64523. function PackedRect(root, parent, pos, size) {
  64524. this._pos = pos;
  64525. this._size = size;
  64526. this._root = root;
  64527. this._parent = parent;
  64528. this._contentSize = null;
  64529. this._bottomNode = null;
  64530. this._leftNode = null;
  64531. this._initialSize = null;
  64532. this._rightNode = null;
  64533. }
  64534. Object.defineProperty(PackedRect.prototype, "pos", {
  64535. /**
  64536. * @returns the position of this node into the map
  64537. */
  64538. get: function () {
  64539. return this._pos;
  64540. },
  64541. enumerable: true,
  64542. configurable: true
  64543. });
  64544. Object.defineProperty(PackedRect.prototype, "contentSize", {
  64545. /**
  64546. * @returns the size of the rectangle this node handles
  64547. */
  64548. get: function () {
  64549. return this._contentSize;
  64550. },
  64551. enumerable: true,
  64552. configurable: true
  64553. });
  64554. /**
  64555. * Retrieve the inner position (considering the margin) and stores it into the res object
  64556. * @param res must be a valid Vector2 that will contain the inner position after this call
  64557. */
  64558. PackedRect.prototype.getInnerPosToRef = function (res) {
  64559. var m = this._root._margin;
  64560. res.x = this._pos.x + m;
  64561. res.y = this._pos.y + m;
  64562. };
  64563. /**
  64564. * Retrieve the inner size (considering the margin) and stores it into the res object
  64565. * @param res must be a valid Size that will contain the inner size after this call
  64566. */
  64567. PackedRect.prototype.getInnerSizeToRef = function (res) {
  64568. var m = this._root._margin;
  64569. res.width = this._contentSize.width - (m * 2);
  64570. res.height = this._contentSize.height - (m * 2);
  64571. };
  64572. Object.defineProperty(PackedRect.prototype, "UVs", {
  64573. /**
  64574. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  64575. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  64576. */
  64577. get: function () {
  64578. if (!this._contentSize) {
  64579. throw new Error("Can't compute UVs for this object because it's nor allocated");
  64580. }
  64581. return this.getUVsForCustomSize(this._contentSize);
  64582. },
  64583. enumerable: true,
  64584. configurable: true
  64585. });
  64586. /**
  64587. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  64588. * and then using only a part of the PackRect.
  64589. * This method will return the UVs for this part by given the custom size of what you really use
  64590. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  64591. */
  64592. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  64593. var mainWidth = this._root._size.width;
  64594. var mainHeight = this._root._size.height;
  64595. var margin = this._root._margin;
  64596. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  64597. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  64598. var uvs = new Array();
  64599. uvs.push(topLeft);
  64600. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  64601. uvs.push(rightBottom);
  64602. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  64603. return uvs;
  64604. };
  64605. /**
  64606. * Free this rectangle from the map.
  64607. * Call this method when you no longer need the rectangle to be in the map.
  64608. */
  64609. PackedRect.prototype.freeContent = function () {
  64610. if (!this.contentSize) {
  64611. return;
  64612. }
  64613. this._contentSize = null;
  64614. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  64615. this.attemptDefrag();
  64616. };
  64617. Object.defineProperty(PackedRect.prototype, "isUsed", {
  64618. get: function () {
  64619. return this._contentSize != null || this._leftNode != null;
  64620. },
  64621. enumerable: true,
  64622. configurable: true
  64623. });
  64624. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  64625. var node = this.findNode(contentSize);
  64626. // Not enough space...
  64627. if (!node) {
  64628. return null;
  64629. }
  64630. node.splitNode(contentSize);
  64631. return node;
  64632. };
  64633. PackedRect.prototype.findNode = function (size) {
  64634. var resNode = null;
  64635. var margin = this._root._margin * 2;
  64636. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  64637. if (this.isUsed) {
  64638. if (this._leftNode) {
  64639. resNode = this._leftNode.findNode(size);
  64640. }
  64641. if (!resNode && this._rightNode) {
  64642. resNode = this._rightNode.findNode(size);
  64643. }
  64644. if (!resNode && this._bottomNode) {
  64645. resNode = this._bottomNode.findNode(size);
  64646. }
  64647. }
  64648. else if (this._initialSize) {
  64649. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  64650. resNode = this;
  64651. }
  64652. else {
  64653. return null;
  64654. }
  64655. }
  64656. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  64657. resNode = this;
  64658. }
  64659. return resNode;
  64660. };
  64661. PackedRect.prototype.splitNode = function (contentSize) {
  64662. var cs = PackedRect.TpsSize;
  64663. var margin = this._root._margin * 2;
  64664. cs.copyFrom(contentSize);
  64665. cs.width += margin;
  64666. cs.height += margin;
  64667. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  64668. if (!this._contentSize && this._initialSize) {
  64669. this._contentSize = cs.clone();
  64670. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  64671. return this._leftNode.splitNode(contentSize);
  64672. }
  64673. else {
  64674. this._contentSize = cs.clone();
  64675. this._initialSize = cs.clone();
  64676. if (cs.width !== this._size.width) {
  64677. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  64678. }
  64679. if (cs.height !== this._size.height) {
  64680. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  64681. }
  64682. return this;
  64683. }
  64684. };
  64685. PackedRect.prototype.attemptDefrag = function () {
  64686. if (!this.isUsed && this.isRecursiveFree) {
  64687. this.clearNode();
  64688. if (this._parent) {
  64689. this._parent.attemptDefrag();
  64690. }
  64691. }
  64692. };
  64693. PackedRect.prototype.clearNode = function () {
  64694. this._initialSize = null;
  64695. this._rightNode = null;
  64696. this._bottomNode = null;
  64697. };
  64698. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  64699. get: function () {
  64700. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  64701. },
  64702. enumerable: true,
  64703. configurable: true
  64704. });
  64705. PackedRect.prototype.evalFreeSize = function (size) {
  64706. var levelSize = 0;
  64707. if (!this.isUsed) {
  64708. var margin = this._root._margin;
  64709. var is = this._initialSize;
  64710. if (is) {
  64711. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  64712. }
  64713. else {
  64714. var size_1 = this._size;
  64715. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  64716. }
  64717. }
  64718. if (this._rightNode) {
  64719. levelSize += this._rightNode.evalFreeSize(0);
  64720. }
  64721. if (this._bottomNode) {
  64722. levelSize += this._bottomNode.evalFreeSize(0);
  64723. }
  64724. return levelSize + size;
  64725. };
  64726. return PackedRect;
  64727. }());
  64728. PackedRect.TpsSize = BABYLON.Size.Zero();
  64729. BABYLON.PackedRect = PackedRect;
  64730. /**
  64731. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  64732. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  64733. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  64734. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  64735. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  64736. */
  64737. var RectPackingMap = (function (_super) {
  64738. __extends(RectPackingMap, _super);
  64739. /**
  64740. * Create an instance of the object with a dimension using the given size
  64741. * @param size The dimension of the rectangle that will contain all the sub ones.
  64742. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  64743. */
  64744. function RectPackingMap(size, margin) {
  64745. if (margin === void 0) { margin = 0; }
  64746. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  64747. _this._margin = margin;
  64748. _this._root = _this;
  64749. return _this;
  64750. }
  64751. /**
  64752. * Add a rectangle, finding the best location to store it into the map
  64753. * @param size the dimension of the rectangle to store
  64754. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  64755. */
  64756. RectPackingMap.prototype.addRect = function (size) {
  64757. var node = this.findAndSplitNode(size);
  64758. return node;
  64759. };
  64760. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  64761. /**
  64762. * Return the current space free normalized between [0;1]
  64763. * @returns {}
  64764. */
  64765. get: function () {
  64766. var freeSize = 0;
  64767. freeSize = this.evalFreeSize(freeSize);
  64768. return freeSize / (this._size.width * this._size.height);
  64769. },
  64770. enumerable: true,
  64771. configurable: true
  64772. });
  64773. return RectPackingMap;
  64774. }(PackedRect));
  64775. BABYLON.RectPackingMap = RectPackingMap;
  64776. })(BABYLON || (BABYLON = {}));
  64777. //# sourceMappingURL=babylon.rectPackingMap.js.map
  64778. var BABYLON;
  64779. (function (BABYLON) {
  64780. var serializedGeometries = [];
  64781. var serializeGeometry = function (geometry, serializationGeometries) {
  64782. if (serializedGeometries[geometry.id]) {
  64783. return;
  64784. }
  64785. if (geometry.doNotSerialize) {
  64786. return;
  64787. }
  64788. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  64789. serializationGeometries.boxes.push(geometry.serialize());
  64790. }
  64791. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  64792. serializationGeometries.spheres.push(geometry.serialize());
  64793. }
  64794. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  64795. serializationGeometries.cylinders.push(geometry.serialize());
  64796. }
  64797. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  64798. serializationGeometries.toruses.push(geometry.serialize());
  64799. }
  64800. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  64801. serializationGeometries.grounds.push(geometry.serialize());
  64802. }
  64803. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  64804. serializationGeometries.planes.push(geometry.serialize());
  64805. }
  64806. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  64807. serializationGeometries.torusKnots.push(geometry.serialize());
  64808. }
  64809. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  64810. throw new Error("Unknown primitive type");
  64811. }
  64812. else {
  64813. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  64814. }
  64815. serializedGeometries[geometry.id] = true;
  64816. };
  64817. var serializeMesh = function (mesh, serializationScene) {
  64818. var serializationObject = {};
  64819. // Geometry
  64820. var geometry = mesh._geometry;
  64821. if (geometry) {
  64822. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  64823. // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  64824. serializeGeometry(geometry, serializationScene.geometries);
  64825. }
  64826. }
  64827. // Custom
  64828. if (mesh.serialize) {
  64829. mesh.serialize(serializationObject);
  64830. }
  64831. return serializationObject;
  64832. };
  64833. var finalizeSingleMesh = function (mesh, serializationObject) {
  64834. //only works if the mesh is already loaded
  64835. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  64836. //serialize material
  64837. if (mesh.material) {
  64838. if (mesh.material instanceof BABYLON.StandardMaterial) {
  64839. serializationObject.materials = serializationObject.materials || [];
  64840. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  64841. serializationObject.materials.push(mesh.material.serialize());
  64842. }
  64843. }
  64844. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  64845. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  64846. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  64847. serializationObject.multiMaterials.push(mesh.material.serialize());
  64848. }
  64849. }
  64850. }
  64851. //serialize geometry
  64852. var geometry = mesh._geometry;
  64853. if (geometry) {
  64854. if (!serializationObject.geometries) {
  64855. serializationObject.geometries = {};
  64856. serializationObject.geometries.boxes = [];
  64857. serializationObject.geometries.spheres = [];
  64858. serializationObject.geometries.cylinders = [];
  64859. serializationObject.geometries.toruses = [];
  64860. serializationObject.geometries.grounds = [];
  64861. serializationObject.geometries.planes = [];
  64862. serializationObject.geometries.torusKnots = [];
  64863. serializationObject.geometries.vertexData = [];
  64864. }
  64865. serializeGeometry(geometry, serializationObject.geometries);
  64866. }
  64867. // Skeletons
  64868. if (mesh.skeleton) {
  64869. serializationObject.skeletons = serializationObject.skeletons || [];
  64870. serializationObject.skeletons.push(mesh.skeleton.serialize());
  64871. }
  64872. //serialize the actual mesh
  64873. serializationObject.meshes = serializationObject.meshes || [];
  64874. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  64875. }
  64876. };
  64877. var SceneSerializer = (function () {
  64878. function SceneSerializer() {
  64879. }
  64880. SceneSerializer.ClearCache = function () {
  64881. serializedGeometries = [];
  64882. };
  64883. SceneSerializer.Serialize = function (scene) {
  64884. var serializationObject = {};
  64885. SceneSerializer.ClearCache();
  64886. // Scene
  64887. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  64888. serializationObject.autoClear = scene.autoClear;
  64889. serializationObject.clearColor = scene.clearColor.asArray();
  64890. serializationObject.ambientColor = scene.ambientColor.asArray();
  64891. serializationObject.gravity = scene.gravity.asArray();
  64892. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  64893. serializationObject.workerCollisions = scene.workerCollisions;
  64894. // Fog
  64895. if (scene.fogMode && scene.fogMode !== 0) {
  64896. serializationObject.fogMode = scene.fogMode;
  64897. serializationObject.fogColor = scene.fogColor.asArray();
  64898. serializationObject.fogStart = scene.fogStart;
  64899. serializationObject.fogEnd = scene.fogEnd;
  64900. serializationObject.fogDensity = scene.fogDensity;
  64901. }
  64902. //Physics
  64903. if (scene.isPhysicsEnabled()) {
  64904. serializationObject.physicsEnabled = true;
  64905. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  64906. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  64907. }
  64908. // Metadata
  64909. if (scene.metadata) {
  64910. serializationObject.metadata = scene.metadata;
  64911. }
  64912. // Morph targets
  64913. serializationObject.morphTargetManagers = [];
  64914. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  64915. var abstractMesh = _a[_i];
  64916. var manager = abstractMesh.morphTargetManager;
  64917. if (manager) {
  64918. serializationObject.morphTargetManagers.push(manager.serialize());
  64919. }
  64920. }
  64921. // Lights
  64922. serializationObject.lights = [];
  64923. var index;
  64924. var light;
  64925. for (index = 0; index < scene.lights.length; index++) {
  64926. light = scene.lights[index];
  64927. if (!light.doNotSerialize) {
  64928. serializationObject.lights.push(light.serialize());
  64929. }
  64930. }
  64931. // Cameras
  64932. serializationObject.cameras = [];
  64933. for (index = 0; index < scene.cameras.length; index++) {
  64934. var camera = scene.cameras[index];
  64935. if (!camera.doNotSerialize) {
  64936. serializationObject.cameras.push(camera.serialize());
  64937. }
  64938. }
  64939. if (scene.activeCamera) {
  64940. serializationObject.activeCameraID = scene.activeCamera.id;
  64941. }
  64942. // Animations
  64943. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  64944. // Materials
  64945. serializationObject.materials = [];
  64946. serializationObject.multiMaterials = [];
  64947. var material;
  64948. for (index = 0; index < scene.materials.length; index++) {
  64949. material = scene.materials[index];
  64950. if (!material.doNotSerialize) {
  64951. serializationObject.materials.push(material.serialize());
  64952. }
  64953. }
  64954. // MultiMaterials
  64955. serializationObject.multiMaterials = [];
  64956. for (index = 0; index < scene.multiMaterials.length; index++) {
  64957. var multiMaterial = scene.multiMaterials[index];
  64958. serializationObject.multiMaterials.push(multiMaterial.serialize());
  64959. }
  64960. // Skeletons
  64961. serializationObject.skeletons = [];
  64962. for (index = 0; index < scene.skeletons.length; index++) {
  64963. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  64964. }
  64965. // Geometries
  64966. serializationObject.geometries = {};
  64967. serializationObject.geometries.boxes = [];
  64968. serializationObject.geometries.spheres = [];
  64969. serializationObject.geometries.cylinders = [];
  64970. serializationObject.geometries.toruses = [];
  64971. serializationObject.geometries.grounds = [];
  64972. serializationObject.geometries.planes = [];
  64973. serializationObject.geometries.torusKnots = [];
  64974. serializationObject.geometries.vertexData = [];
  64975. serializedGeometries = [];
  64976. var geometries = scene.getGeometries();
  64977. for (index = 0; index < geometries.length; index++) {
  64978. var geometry = geometries[index];
  64979. if (geometry.isReady()) {
  64980. serializeGeometry(geometry, serializationObject.geometries);
  64981. }
  64982. }
  64983. // Meshes
  64984. serializationObject.meshes = [];
  64985. for (index = 0; index < scene.meshes.length; index++) {
  64986. var abstractMesh = scene.meshes[index];
  64987. if (abstractMesh instanceof BABYLON.Mesh) {
  64988. var mesh = abstractMesh;
  64989. if (!mesh.doNotSerialize) {
  64990. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  64991. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  64992. }
  64993. }
  64994. }
  64995. }
  64996. // Particles Systems
  64997. serializationObject.particleSystems = [];
  64998. for (index = 0; index < scene.particleSystems.length; index++) {
  64999. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  65000. }
  65001. // Lens flares
  65002. serializationObject.lensFlareSystems = [];
  65003. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  65004. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  65005. }
  65006. // Shadows
  65007. serializationObject.shadowGenerators = [];
  65008. for (index = 0; index < scene.lights.length; index++) {
  65009. light = scene.lights[index];
  65010. var shadowGenerator = light.getShadowGenerator();
  65011. if (shadowGenerator) {
  65012. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  65013. }
  65014. }
  65015. // Action Manager
  65016. if (scene.actionManager) {
  65017. serializationObject.actions = scene.actionManager.serialize("scene");
  65018. }
  65019. // Audio
  65020. serializationObject.sounds = [];
  65021. for (index = 0; index < scene.soundTracks.length; index++) {
  65022. var soundtrack = scene.soundTracks[index];
  65023. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  65024. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  65025. }
  65026. }
  65027. return serializationObject;
  65028. };
  65029. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  65030. if (withParents === void 0) { withParents = false; }
  65031. if (withChildren === void 0) { withChildren = false; }
  65032. var serializationObject = {};
  65033. SceneSerializer.ClearCache();
  65034. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  65035. if (withParents || withChildren) {
  65036. //deliberate for loop! not for each, appended should be processed as well.
  65037. for (var i = 0; i < toSerialize.length; ++i) {
  65038. if (withChildren) {
  65039. toSerialize[i].getDescendants().forEach(function (node) {
  65040. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  65041. toSerialize.push(node);
  65042. }
  65043. });
  65044. }
  65045. //make sure the array doesn't contain the object already
  65046. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  65047. toSerialize.push(toSerialize[i].parent);
  65048. }
  65049. }
  65050. }
  65051. toSerialize.forEach(function (mesh) {
  65052. finalizeSingleMesh(mesh, serializationObject);
  65053. });
  65054. return serializationObject;
  65055. };
  65056. return SceneSerializer;
  65057. }());
  65058. BABYLON.SceneSerializer = SceneSerializer;
  65059. })(BABYLON || (BABYLON = {}));
  65060. //# sourceMappingURL=babylon.sceneSerializer.js.map
  65061. var BABYLON;
  65062. (function (BABYLON) {
  65063. var ReflectionProbe = (function () {
  65064. function ReflectionProbe(name, size, scene, generateMipMaps) {
  65065. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65066. var _this = this;
  65067. this.name = name;
  65068. this._viewMatrix = BABYLON.Matrix.Identity();
  65069. this._target = BABYLON.Vector3.Zero();
  65070. this._add = BABYLON.Vector3.Zero();
  65071. this.invertYAxis = false;
  65072. this.position = BABYLON.Vector3.Zero();
  65073. this._scene = scene;
  65074. this._scene.reflectionProbes.push(this);
  65075. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  65076. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  65077. switch (faceIndex) {
  65078. case 0:
  65079. _this._add.copyFromFloats(1, 0, 0);
  65080. break;
  65081. case 1:
  65082. _this._add.copyFromFloats(-1, 0, 0);
  65083. break;
  65084. case 2:
  65085. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  65086. break;
  65087. case 3:
  65088. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  65089. break;
  65090. case 4:
  65091. _this._add.copyFromFloats(0, 0, 1);
  65092. break;
  65093. case 5:
  65094. _this._add.copyFromFloats(0, 0, -1);
  65095. break;
  65096. }
  65097. if (_this._attachedMesh) {
  65098. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  65099. }
  65100. _this.position.addToRef(_this._add, _this._target);
  65101. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  65102. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  65103. });
  65104. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  65105. scene.updateTransformMatrix(true);
  65106. });
  65107. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  65108. }
  65109. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  65110. get: function () {
  65111. return this._renderTargetTexture.samples;
  65112. },
  65113. set: function (value) {
  65114. this._renderTargetTexture.samples = value;
  65115. },
  65116. enumerable: true,
  65117. configurable: true
  65118. });
  65119. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  65120. get: function () {
  65121. return this._renderTargetTexture.refreshRate;
  65122. },
  65123. set: function (value) {
  65124. this._renderTargetTexture.refreshRate = value;
  65125. },
  65126. enumerable: true,
  65127. configurable: true
  65128. });
  65129. ReflectionProbe.prototype.getScene = function () {
  65130. return this._scene;
  65131. };
  65132. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  65133. get: function () {
  65134. return this._renderTargetTexture;
  65135. },
  65136. enumerable: true,
  65137. configurable: true
  65138. });
  65139. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  65140. get: function () {
  65141. return this._renderTargetTexture.renderList;
  65142. },
  65143. enumerable: true,
  65144. configurable: true
  65145. });
  65146. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  65147. this._attachedMesh = mesh;
  65148. };
  65149. ReflectionProbe.prototype.dispose = function () {
  65150. var index = this._scene.reflectionProbes.indexOf(this);
  65151. if (index !== -1) {
  65152. // Remove from the scene if found
  65153. this._scene.reflectionProbes.splice(index, 1);
  65154. }
  65155. if (this._renderTargetTexture) {
  65156. this._renderTargetTexture.dispose();
  65157. this._renderTargetTexture = null;
  65158. }
  65159. };
  65160. return ReflectionProbe;
  65161. }());
  65162. BABYLON.ReflectionProbe = ReflectionProbe;
  65163. })(BABYLON || (BABYLON = {}));
  65164. //# sourceMappingURL=babylon.reflectionProbe.js.map
  65165. var BABYLON;
  65166. (function (BABYLON) {
  65167. var Layer = (function () {
  65168. function Layer(name, imgUrl, scene, isBackground, color) {
  65169. this.name = name;
  65170. this.scale = new BABYLON.Vector2(1, 1);
  65171. this.offset = new BABYLON.Vector2(0, 0);
  65172. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  65173. this.layerMask = 0x0FFFFFFF;
  65174. this._vertexBuffers = {};
  65175. // Events
  65176. /**
  65177. * An event triggered when the layer is disposed.
  65178. * @type {BABYLON.Observable}
  65179. */
  65180. this.onDisposeObservable = new BABYLON.Observable();
  65181. /**
  65182. * An event triggered before rendering the scene
  65183. * @type {BABYLON.Observable}
  65184. */
  65185. this.onBeforeRenderObservable = new BABYLON.Observable();
  65186. /**
  65187. * An event triggered after rendering the scene
  65188. * @type {BABYLON.Observable}
  65189. */
  65190. this.onAfterRenderObservable = new BABYLON.Observable();
  65191. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  65192. this.isBackground = isBackground === undefined ? true : isBackground;
  65193. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  65194. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65195. this._scene.layers.push(this);
  65196. var engine = this._scene.getEngine();
  65197. // VBO
  65198. var vertices = [];
  65199. vertices.push(1, 1);
  65200. vertices.push(-1, 1);
  65201. vertices.push(-1, -1);
  65202. vertices.push(1, -1);
  65203. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65204. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65205. // Indices
  65206. var indices = [];
  65207. indices.push(0);
  65208. indices.push(1);
  65209. indices.push(2);
  65210. indices.push(0);
  65211. indices.push(2);
  65212. indices.push(3);
  65213. this._indexBuffer = engine.createIndexBuffer(indices);
  65214. // Effects
  65215. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  65216. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  65217. }
  65218. Object.defineProperty(Layer.prototype, "onDispose", {
  65219. set: function (callback) {
  65220. if (this._onDisposeObserver) {
  65221. this.onDisposeObservable.remove(this._onDisposeObserver);
  65222. }
  65223. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  65224. },
  65225. enumerable: true,
  65226. configurable: true
  65227. });
  65228. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  65229. set: function (callback) {
  65230. if (this._onBeforeRenderObserver) {
  65231. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65232. }
  65233. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65234. },
  65235. enumerable: true,
  65236. configurable: true
  65237. });
  65238. Object.defineProperty(Layer.prototype, "onAfterRender", {
  65239. set: function (callback) {
  65240. if (this._onAfterRenderObserver) {
  65241. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65242. }
  65243. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65244. },
  65245. enumerable: true,
  65246. configurable: true
  65247. });
  65248. Layer.prototype.render = function () {
  65249. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  65250. // Check
  65251. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  65252. return;
  65253. var engine = this._scene.getEngine();
  65254. this.onBeforeRenderObservable.notifyObservers(this);
  65255. // Render
  65256. engine.enableEffect(currentEffect);
  65257. engine.setState(false);
  65258. // Texture
  65259. currentEffect.setTexture("textureSampler", this.texture);
  65260. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  65261. // Color
  65262. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  65263. // Scale / offset
  65264. currentEffect.setVector2("offset", this.offset);
  65265. currentEffect.setVector2("scale", this.scale);
  65266. // VBOs
  65267. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  65268. // Draw order
  65269. if (!this.alphaTest) {
  65270. engine.setAlphaMode(this.alphaBlendingMode);
  65271. engine.draw(true, 0, 6);
  65272. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65273. }
  65274. else {
  65275. engine.draw(true, 0, 6);
  65276. }
  65277. this.onAfterRenderObservable.notifyObservers(this);
  65278. };
  65279. Layer.prototype.dispose = function () {
  65280. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65281. if (vertexBuffer) {
  65282. vertexBuffer.dispose();
  65283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65284. }
  65285. if (this._indexBuffer) {
  65286. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65287. this._indexBuffer = null;
  65288. }
  65289. if (this.texture) {
  65290. this.texture.dispose();
  65291. this.texture = null;
  65292. }
  65293. // Remove from scene
  65294. var index = this._scene.layers.indexOf(this);
  65295. this._scene.layers.splice(index, 1);
  65296. // Callback
  65297. this.onDisposeObservable.notifyObservers(this);
  65298. this.onDisposeObservable.clear();
  65299. this.onAfterRenderObservable.clear();
  65300. this.onBeforeRenderObservable.clear();
  65301. };
  65302. return Layer;
  65303. }());
  65304. BABYLON.Layer = Layer;
  65305. })(BABYLON || (BABYLON = {}));
  65306. //# sourceMappingURL=babylon.layer.js.map
  65307. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n#ifdef LDROUTPUT\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\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}","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;\nvarying vec4 vPosition;\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>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\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 FULLFLOAT\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 vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nuniform vec2 biasAndScale;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5; \n#endif\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\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}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\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>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\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}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\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(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","geometryVertexShader":"#version 300 es\nprecision highp float;\nprecision highp int;\n#include<bones300Declaration>\n#include<instances300Declaration>\nin vec3 position;\nin vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nout vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nin vec2 uv;\n#endif\n#ifdef UV2\nin vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nout vec3 vNormalV;\nout vec4 vViewPos;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\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}","geometryPixelShader":"#version 300 es\nprecision highp float;\nprecision highp int;\nin vec3 vNormalV;\nin vec4 vViewPos;\n#ifdef ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\nvoid main() {\n#ifdef ALPHATEST\nif (texture(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ncolor0=vec4(vViewPos.z/vViewPos.w,0.0,0.0,0.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\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 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\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}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst float GammaEncodePowerApprox=1.0/2.2;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nuniform float contrast;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\nuniform float cameraExposureLinear;\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color)\n{\nfloat sliceSize=2.0*colorTransformSettings.y; \nfloat sliceContinuous=(color.y-colorTransformSettings.y)*colorTransformSettings.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\nvec2 sliceUV=color.xz;\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=result.bgr;\nreturn color;\n}\nvec4 applyImageProcessing(vec4 result,vec2 viewportXY){\nresult.rgb*=cameraExposureLinear;\n\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#ifdef TONEMAPPING \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n\nfloat luma=dot(result.rgb,RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\nreturn result;\n}\nvoid main(void) \n{\nvec4 result=texture2D(textureSampler,vUV);\nvec2 viewportXY=vUV*2.0-1.0;\nresult=applyImageProcessing(result,viewportXY);\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\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{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\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}\n","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\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}"};
  65308. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\nreturn esm;\n}\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  65309. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  65310. module.exports = BABYLON;
  65311. };